-
Notifications
You must be signed in to change notification settings - Fork 10
/
validator.py
2458 lines (2270 loc) · 102 KB
/
validator.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
import datetime
from itertools import chain
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import pandas as pd
import pyarrow as pa
from arize.pandas.validation import errors as err
from arize.utils.constants import (
LLM_RUN_METADATA_PROMPT_TOKEN_COUNT_TAG_NAME,
LLM_RUN_METADATA_RESPONSE_LATENCY_MS_TAG_NAME,
LLM_RUN_METADATA_RESPONSE_TOKEN_COUNT_TAG_NAME,
LLM_RUN_METADATA_TOTAL_TOKEN_COUNT_TAG_NAME,
MAX_DOCUMENT_ID_LEN,
MAX_EMBEDDING_DIMENSIONALITY,
MAX_FUTURE_YEARS_FROM_CURRENT_TIME,
MAX_LLM_MODEL_NAME_LENGTH,
MAX_LLM_MODEL_NAME_LENGTH_TRUNCATION,
MAX_NUMBER_OF_EMBEDDINGS,
MAX_PAST_YEARS_FROM_CURRENT_TIME,
MAX_PREDICTION_ID_LEN,
MAX_PROMPT_TEMPLATE_LENGTH,
MAX_PROMPT_TEMPLATE_LENGTH_TRUNCATION,
MAX_PROMPT_TEMPLATE_VERSION_LENGTH,
MAX_PROMPT_TEMPLATE_VERSION_LENGTH_TRUNCATION,
MAX_RAW_DATA_CHARACTERS,
MAX_RAW_DATA_CHARACTERS_TRUNCATION,
MAX_TAG_LENGTH,
MAX_TAG_LENGTH_TRUNCATION,
MIN_DOCUMENT_ID_LEN,
MIN_PREDICTION_ID_LEN,
MODEL_MAPPING_CONFIG,
)
from arize.utils.logging import get_truncation_warning_message, logger
from arize.utils.types import (
CATEGORICAL_MODEL_TYPES,
NUMERIC_MODEL_TYPES,
BaseSchema,
CorpusSchema,
EmbeddingColumnNames,
Environments,
LLMConfigColumnNames,
Metrics,
ModelTypes,
PromptTemplateColumnNames,
Schema,
count_characters_raw_data,
is_dict_of,
)
from arize.utils.utils import is_delayed_schema
class Validator:
@staticmethod
def validate_required_checks(
dataframe: pd.DataFrame,
model_id: str,
environment: Environments,
schema: BaseSchema,
model_version: Optional[str] = None,
batch_id: Optional[str] = None,
) -> List[err.ValidationError]:
general_checks = chain(
Validator._check_valid_schema_type(schema, environment),
Validator._check_field_convertible_to_str(model_id, model_version, batch_id),
Validator._check_invalid_index(dataframe),
)
# If the schema is a CorpusSchema then for the log to be valid the environment must
# be CORPUS. By including both conditions here we do not need to modify the
# other checks below to account for possible CorpusSchema (which would not be valid
# in those checks).
if environment == Environments.CORPUS or isinstance(schema, CorpusSchema):
return list(general_checks)
elif isinstance(schema, Schema):
return list(
chain(
general_checks,
Validator._check_field_type_embedding_features_column_names(schema),
Validator._check_field_type_prompt_response(schema),
Validator._check_field_type_prompt_templates(schema),
Validator._check_field_type_llm_config(dataframe, schema),
)
)
return []
@staticmethod
def validate_params(
dataframe: pd.DataFrame,
model_id: str,
model_type: ModelTypes,
environment: Environments,
schema: BaseSchema,
metric_families: Optional[List[Metrics]] = None,
model_version: Optional[str] = None,
batch_id: Optional[str] = None,
) -> List[err.ValidationError]:
# general checks
general_checks = chain(
Validator._check_column_names_for_empty_strings(schema),
Validator._check_invalid_model_id(model_id),
Validator._check_invalid_model_version(model_version),
Validator._check_invalid_model_type(model_type),
Validator._check_invalid_environment(environment),
Validator._check_dataframe_for_duplicate_columns(schema, dataframe),
Validator._check_missing_columns(dataframe, schema),
Validator._check_reserved_columns(schema, model_type),
)
if isinstance(schema, CorpusSchema):
return list(general_checks)
elif isinstance(schema, Schema):
general_checks = chain(
general_checks,
Validator._check_existence_prediction_id_column_delayed_schema(schema, model_type),
Validator._check_invalid_batch_id(batch_id, environment),
Validator._check_invalid_number_of_embeddings(schema),
Validator._check_invalid_shap_suffix(schema),
# model mapping checks
Validator._check_model_type_and_metrics(model_type, metric_families, schema),
)
if model_type in NUMERIC_MODEL_TYPES:
num_checks = chain(
Validator._check_existence_pred_act_shap_score_or_label(schema),
Validator._check_existence_preprod_pred_act_score_or_label(schema, environment),
Validator._check_missing_object_detection_columns(schema, model_type),
)
return list(chain(general_checks, num_checks))
elif model_type in CATEGORICAL_MODEL_TYPES:
sc_checks = chain(
Validator._check_existence_pred_act_shap_score_or_label(schema),
Validator._check_existence_preprod_pred_act_score_or_label(schema, environment),
Validator._check_missing_object_detection_columns(schema, model_type),
)
return list(chain(general_checks, sc_checks))
elif model_type == ModelTypes.GENERATIVE_LLM:
gllm_checks = chain(
Validator._check_existence_preprod_act(schema, environment),
Validator._check_missing_object_detection_columns(schema, model_type),
)
return list(chain(general_checks, gllm_checks))
elif model_type == ModelTypes.RANKING:
r_checks = chain(
Validator._check_existence_group_id_rank_category_relevance(schema),
Validator._check_missing_object_detection_columns(schema, model_type),
)
return list(chain(general_checks, r_checks))
elif model_type == ModelTypes.OBJECT_DETECTION:
od_checks = chain(
Validator._check_existence_pred_act_od_column_names(schema, environment),
Validator._check_missing_non_object_detection_columns(schema, model_type),
)
return list(chain(general_checks, od_checks))
return list(general_checks)
@staticmethod
def validate_types(
model_type: ModelTypes,
schema: BaseSchema,
pyarrow_schema: pa.Schema,
) -> List[err.ValidationError]:
column_types = dict(zip(pyarrow_schema.names, pyarrow_schema.types))
if isinstance(schema, CorpusSchema):
return list(chain(Validator._check_type_document_columns(schema, column_types)))
elif isinstance(schema, Schema):
general_checks = chain(
Validator._check_type_prediction_id(schema, column_types),
Validator._check_type_timestamp(schema, column_types),
Validator._check_type_features(schema, column_types),
Validator._check_type_embedding_features(schema, column_types),
Validator._check_type_tags(schema, column_types),
Validator._check_type_shap_values(schema, column_types),
Validator._check_type_retrieved_document_ids(schema, column_types),
)
if model_type in CATEGORICAL_MODEL_TYPES or model_type in NUMERIC_MODEL_TYPES:
scn_checks = chain(
Validator._check_type_pred_act_labels(model_type, schema, column_types),
Validator._check_type_pred_act_scores(model_type, schema, column_types),
)
return list(chain(general_checks, scn_checks))
if model_type == ModelTypes.GENERATIVE_LLM:
gllm_checks = chain(
Validator._check_type_pred_act_labels(model_type, schema, column_types),
Validator._check_type_pred_act_scores(model_type, schema, column_types),
Validator._check_type_prompt_response(schema, column_types),
Validator._check_type_llm_prompt_templates(schema, column_types),
Validator._check_type_llm_config(schema, column_types),
Validator._check_type_llm_run_metadata(schema, column_types),
)
return list(chain(general_checks, gllm_checks))
elif model_type == ModelTypes.RANKING:
r_checks = chain(
Validator._check_type_prediction_group_id(schema, column_types),
Validator._check_type_rank(schema, column_types),
Validator._check_type_ranking_category(schema, column_types),
Validator._check_type_pred_act_scores(model_type, schema, column_types),
)
return list(chain(general_checks, r_checks))
elif model_type == ModelTypes.OBJECT_DETECTION:
od_checks = chain(
Validator._check_type_bounding_boxes_coordinates(schema, column_types),
Validator._check_type_bounding_boxes_categories(schema, column_types),
Validator._check_type_bounding_boxes_scores(schema, column_types),
)
return list(chain(general_checks, od_checks))
return list(general_checks)
return []
@staticmethod
def validate_values(
dataframe: pd.DataFrame,
environment: Environments,
schema: BaseSchema,
model_type: ModelTypes,
) -> List[err.ValidationError]:
# ASSUMPTION: at this point the param and type checks should have passed.
# This function may crash if that is not true, e.g. if columns are missing
# or are of the wrong types.
if len(dataframe) == 0:
return []
general_checks = chain(
Validator._check_invalid_missing_values(dataframe, schema, model_type),
)
if isinstance(schema, CorpusSchema):
return list(
chain(
general_checks,
Validator._check_document_id_field_str_length(
dataframe, "document_id_column_name", schema.document_id_column_name
),
)
)
elif isinstance(schema, Schema):
general_checks = chain(
general_checks,
Validator._check_value_timestamp(dataframe, schema),
Validator._check_id_field_str_length(
dataframe, "prediction_id_column_name", schema.prediction_id_column_name
),
Validator._check_embedding_vectors_dimensionality(dataframe, schema),
Validator._check_embedding_raw_data_characters(dataframe, schema),
Validator._check_invalid_record_prod(dataframe, environment, schema, model_type),
Validator._check_invalid_record_preprod(dataframe, environment, schema, model_type),
Validator._check_value_tag(dataframe, schema),
)
if model_type == ModelTypes.RANKING:
r_checks = chain(
Validator._check_value_rank(dataframe, schema),
Validator._check_id_field_str_length(
dataframe,
"prediction_group_id_column_name",
schema.prediction_group_id_column_name,
),
Validator._check_value_ranking_category(dataframe, schema),
)
return list(chain(general_checks, r_checks))
if model_type == ModelTypes.OBJECT_DETECTION:
od_checks = chain(
Validator._check_value_bounding_boxes_coordinates(dataframe, schema),
Validator._check_value_bounding_boxes_categories(dataframe, schema),
Validator._check_value_bounding_boxes_scores(dataframe, schema),
)
return list(chain(general_checks, od_checks))
if model_type == ModelTypes.GENERATIVE_LLM:
gen_llm_checks = chain(
Validator._check_value_prompt_response(dataframe, schema),
Validator._check_value_llm_model_name(dataframe, schema),
Validator._check_value_llm_prompt_template(dataframe, schema),
Validator._check_value_llm_prompt_template_version(dataframe, schema),
)
return list(chain(general_checks, gen_llm_checks))
return list(general_checks)
return []
# ----------------------
# Minimum requred checks
# ----------------------
@staticmethod
def _check_column_names_for_empty_strings(
schema: BaseSchema,
) -> List[err.InvalidColumnNameEmptyString]:
if "" in schema.get_used_columns():
return [err.InvalidColumnNameEmptyString()]
return []
@staticmethod
def _check_field_convertible_to_str(
model_id, model_version, batch_id
) -> List[err.InvalidFieldTypeConversion]:
# converting to a set first makes the checks run a lot faster
wrong_fields = []
if model_id is not None and not isinstance(model_id, str):
try:
str(model_id)
except Exception:
wrong_fields.append("model_id")
if model_version is not None and not isinstance(model_version, str):
try:
str(model_version)
except Exception:
wrong_fields.append("model_version")
if batch_id is not None and not isinstance(batch_id, str):
try:
str(batch_id)
except Exception:
wrong_fields.append("batch_id")
if wrong_fields:
return [err.InvalidFieldTypeConversion(wrong_fields, "string")]
return []
@staticmethod
def _check_field_type_embedding_features_column_names(
schema: Schema,
) -> List[err.InvalidFieldTypeEmbeddingFeatures]:
if schema.embedding_feature_column_names is not None:
if not isinstance(schema.embedding_feature_column_names, dict):
return [err.InvalidFieldTypeEmbeddingFeatures()]
for k, v in schema.embedding_feature_column_names.items():
if not isinstance(k, str) or not isinstance(v, EmbeddingColumnNames):
return [err.InvalidFieldTypeEmbeddingFeatures()]
return []
@staticmethod
def _check_field_type_prompt_response(
schema: Schema,
) -> List[err.InvalidFieldTypePromptResponse]:
errors = []
if schema.prompt_column_names is not None and not isinstance(
schema.prompt_column_names, (str, EmbeddingColumnNames)
):
errors.append(err.InvalidFieldTypePromptResponse("prompt_column_names"))
if schema.response_column_names is not None and not isinstance(
schema.response_column_names, (str, EmbeddingColumnNames)
):
errors.append(err.InvalidFieldTypePromptResponse("response_column_names"))
return errors
@staticmethod
def _check_field_type_prompt_templates(
schema: Schema,
) -> List[err.InvalidFieldTypePromptTemplates]:
if schema.prompt_template_column_names is not None and not isinstance(
schema.prompt_template_column_names, PromptTemplateColumnNames
):
return [err.InvalidFieldTypePromptTemplates()]
return []
@staticmethod
def _check_field_type_llm_config(
dataframe: pd.DataFrame,
schema: Schema,
) -> List[Union[err.InvalidFieldTypeLlmConfig, err.InvalidTypeColumns]]:
if schema.llm_config_column_names is None:
return []
if not isinstance(schema.llm_config_column_names, LLMConfigColumnNames):
return [err.InvalidFieldTypeLlmConfig()]
col = schema.llm_config_column_names.params_column_name
# We check the types if the columns are in the dataframe.
# If the columns are reflected in the schema but not present
# in the dataframe, it will be caught by _check_missing_columns
if col is not None and col in dataframe.columns:
if any(
not is_dict_of(
val,
key_allowed_types=str,
value_allowed_types=(bool, int, float, str),
value_list_allowed_types=str,
)
for val in dataframe[col]
):
return [
err.InvalidTypeColumns(
wrong_type_columns=[col],
expected_types=["Dict[str, (bool, int, float, string or list[str])]"],
)
]
return []
@staticmethod
def _check_invalid_index(dataframe: pd.DataFrame) -> List[err.InvalidIndex]:
if (dataframe.index != dataframe.reset_index(drop=True).index).any():
return [err.InvalidIndex()]
return []
# ----------------
# Parameter checks
# ----------------
@staticmethod
def _check_model_type_and_metrics(
model_type: ModelTypes, metric_families: Optional[List[Metrics]], schema: Schema
) -> List[err.ValidationError]:
if metric_families is None:
return []
external_model_types = MODEL_MAPPING_CONFIG.get("external_model_types")
if not external_model_types:
return []
if model_type.name.lower() not in external_model_types:
# model_type is an old model type, e.g. SCORE_CATEGORICAL.
# We can't do model mapping validations with this type.
return []
required_columns_map = MODEL_MAPPING_CONFIG.get("required_columns_map")
if not required_columns_map:
return []
(
valid_combination,
missing_columns,
suggested_model_metric_combinations,
) = Validator._check_model_mapping_combinations(
model_type, metric_families, schema, required_columns_map
)
if not valid_combination:
# Model type + metrics combination is not valid.
return [
err.InvalidModelTypeAndMetricsCombination(
model_type, metric_families, suggested_model_metric_combinations
)
]
if missing_columns:
# For this model type, the schema is missing columns required for the requested metrics.
return [
err.MissingRequiredColumnsMetricsValidation(
model_type, metric_families, missing_columns
)
]
return []
@staticmethod
def _check_model_mapping_combinations(
model_type: ModelTypes,
metric_families: List[Metrics],
schema: Schema,
required_columns_map: List[Dict[str, Any]],
) -> Tuple[bool, List[str], List[List[str]]]:
missing_columns = []
for item in required_columns_map:
if model_type.name.lower() == item.get("external_model_type"):
is_valid_combination = False
metric_combinations = []
mappings = item.get("mappings")
if mappings is not None:
for mapping in mappings:
# This is a list of lists of metrics.
# There may be a few metric combinations that map to the same column
# enforcement rules.
for metrics_list in mapping.get("metrics"):
metric_combinations.append([metric.upper() for metric in metrics_list])
if set(metrics_list) == set(
metric_family.name.lower() for metric_family in metric_families
):
# This is a valid combination of model type + metrics.
# Now validate that required columns are in the schema.
is_valid_combination = True
# If no prediction values are present, then delayed actuals are being
# logged, and we can't validate required columns.
if schema.has_prediction_columns():
# This is a list of lists.
# In some cases, either one set of columns OR another set of
# columns is required.
required_columns = (
mapping.get("required_columns").get("arrow").get("required")
)
for column_combination in required_columns:
missing_columns = []
if None in {
getattr(schema, column, None)
for column in column_combination
}:
for column in column_combination:
if not getattr(schema, column, None):
missing_columns.append(column)
else:
break
if not is_valid_combination:
return False, [], metric_combinations
return True, missing_columns, []
@staticmethod
def _check_existence_prediction_id_column_delayed_schema(
schema: Schema, model_type: ModelTypes
) -> List[err.MissingPredictionIdColumnForDelayedRecords]:
if schema.prediction_id_column_name is not None:
return []
# TODO: Revise logic once predicion_label column addition (for generative models)
# is moved to beginning of log function
if is_delayed_schema(schema) and model_type is not ModelTypes.GENERATIVE_LLM:
# We skip GENERATIVE model types since they are assigned a default
# prediction label column with values equal 1
return [
err.MissingPredictionIdColumnForDelayedRecords(
schema.has_actual_columns(), schema.has_feature_importance_columns()
)
]
# We don't allow delayed actuals for generative models, since we give a default prediction
# label column with 1 as default value
if model_type is not ModelTypes.GENERATIVE_LLM:
# Warning for when prediction_id is not provided by the user and we generate the default
# prediction ids
logger.warning(
"Prediction ID is not specified. Arize generates UUIDs for the model's predictions "
"if not provided by the user. Please note, you won't be able to send delayed data for "
"joining if a Prediction ID is not provided."
)
return []
@staticmethod
def _check_missing_columns(
dataframe: pd.DataFrame,
schema: BaseSchema,
) -> List[err.MissingColumns]:
if isinstance(schema, CorpusSchema):
return Validator._check_missing_columns_corpus_schema(dataframe, schema)
elif isinstance(schema, Schema):
return Validator._check_missing_columns_schema(dataframe, schema)
return []
@staticmethod
def _check_missing_columns_schema(
dataframe: pd.DataFrame,
schema: Schema,
) -> List[err.MissingColumns]:
# converting to a set first makes the checks run a lot faster
existing_columns = set(dataframe.columns)
missing_columns = []
for field in schema.__dataclass_fields__:
if field.endswith("column_name"):
col = getattr(schema, field)
if col is not None and col not in existing_columns:
missing_columns.append(col)
if schema.feature_column_names is not None:
for col in schema.feature_column_names:
if col not in existing_columns:
missing_columns.append(col)
if schema.embedding_feature_column_names is not None:
for emb_feat_col_names in schema.embedding_feature_column_names.values():
if emb_feat_col_names.vector_column_name not in existing_columns:
missing_columns.append(emb_feat_col_names.vector_column_name)
if (
emb_feat_col_names.data_column_name is not None
and emb_feat_col_names.data_column_name not in existing_columns
):
missing_columns.append(emb_feat_col_names.data_column_name)
if (
emb_feat_col_names.link_to_data_column_name is not None
and emb_feat_col_names.link_to_data_column_name not in existing_columns
):
missing_columns.append(emb_feat_col_names.link_to_data_column_name)
if schema.tag_column_names is not None:
for col in schema.tag_column_names:
if col not in existing_columns:
missing_columns.append(col)
if schema.shap_values_column_names is not None:
for col in schema.shap_values_column_names.values():
if col not in existing_columns:
missing_columns.append(col)
if schema.object_detection_prediction_column_names is not None:
for col in schema.object_detection_prediction_column_names:
if col is not None and col not in existing_columns:
missing_columns.append(col)
if schema.object_detection_actual_column_names is not None:
for col in schema.object_detection_actual_column_names:
if col is not None and col not in existing_columns:
missing_columns.append(col)
if schema.prompt_column_names is not None:
if isinstance(schema.prompt_column_names, str):
col = schema.prompt_column_names
if col not in existing_columns:
missing_columns.append(col)
elif isinstance(schema.prompt_column_names, EmbeddingColumnNames):
prompt_emb_col_names = schema.prompt_column_names
if prompt_emb_col_names.vector_column_name not in existing_columns:
missing_columns.append(prompt_emb_col_names.vector_column_name)
if (
prompt_emb_col_names.data_column_name is not None
and prompt_emb_col_names.data_column_name not in existing_columns
):
missing_columns.append(prompt_emb_col_names.data_column_name)
if schema.response_column_names is not None:
if isinstance(schema.response_column_names, str):
col = schema.response_column_names
if col not in existing_columns:
missing_columns.append(col)
elif isinstance(schema.response_column_names, EmbeddingColumnNames):
response_emb_col_names = schema.response_column_names
if response_emb_col_names.vector_column_name not in existing_columns:
missing_columns.append(response_emb_col_names.vector_column_name)
if (
response_emb_col_names.data_column_name is not None
and response_emb_col_names.data_column_name not in existing_columns
):
missing_columns.append(response_emb_col_names.data_column_name)
if schema.prompt_template_column_names is not None:
for col in schema.prompt_template_column_names:
if col is not None and col not in existing_columns:
missing_columns.append(col)
if schema.llm_config_column_names is not None:
for col in schema.llm_config_column_names:
if col is not None and col not in existing_columns:
missing_columns.append(col)
if missing_columns:
return [err.MissingColumns(missing_columns)]
return []
@staticmethod
def _check_missing_columns_corpus_schema(
dataframe: pd.DataFrame,
schema: CorpusSchema,
) -> List[err.MissingColumns]:
# converting to a set first makes the checks run a lot faster
existing_columns = set(dataframe.columns)
missing_columns = []
for field in schema.__dataclass_fields__:
if field.endswith("column_name"):
col = getattr(schema, field)
if col is not None and col not in existing_columns:
missing_columns.append(col)
if (
schema.document_id_column_name is not None
and schema.document_id_column_name not in existing_columns
):
missing_columns.append(schema.document_id_column_name)
if (
schema.document_version_column_name is not None
and schema.document_version_column_name not in existing_columns
):
missing_columns.append(schema.document_version_column_name)
if schema.document_text_embedding_column_names is not None:
if (
schema.document_text_embedding_column_names.vector_column_name is not None
and schema.document_text_embedding_column_names.vector_column_name
not in existing_columns
):
missing_columns.append(
schema.document_text_embedding_column_names.vector_column_name
)
if (
schema.document_text_embedding_column_names.data_column_name is not None
and schema.document_text_embedding_column_names.data_column_name
not in existing_columns
):
missing_columns.append(schema.document_text_embedding_column_names.data_column_name)
if (
schema.document_text_embedding_column_names.link_to_data_column_name is not None
and schema.document_text_embedding_column_names.link_to_data_column_name
not in existing_columns
):
missing_columns.append(
schema.document_text_embedding_column_names.link_to_data_column_name
)
if missing_columns:
return [err.MissingColumns(missing_columns)]
return []
@staticmethod
def _check_valid_schema_type(
schema: BaseSchema,
environment: Environments,
) -> List[err.InvalidSchemaType]:
if environment == Environments.CORPUS and not (isinstance(schema, CorpusSchema)):
return [err.InvalidSchemaType(schema_type=str(type(schema)), environment=environment)]
if environment != Environments.CORPUS and isinstance(schema, CorpusSchema):
return [err.InvalidSchemaType(schema_type=str(type(schema)), environment=environment)]
return []
@staticmethod
def _check_invalid_shap_suffix(
schema: Schema,
) -> List[err.InvalidShapSuffix]:
invalid_column_names = set()
if schema.feature_column_names is not None:
for col in schema.feature_column_names:
if isinstance(col, str) and col.endswith("_shap"):
invalid_column_names.add(col)
if schema.embedding_feature_column_names is not None:
for emb_col_names in schema.embedding_feature_column_names.values():
for col in emb_col_names:
if col is not None and isinstance(col, str) and col.endswith("_shap"):
invalid_column_names.add(col)
if schema.tag_column_names is not None:
for col in schema.tag_column_names:
if isinstance(col, str) and col.endswith("_shap"):
invalid_column_names.add(col)
if schema.shap_values_column_names is not None:
for col in schema.shap_values_column_names.keys():
if isinstance(col, str) and col.endswith("_shap"):
invalid_column_names.add(col)
if invalid_column_names:
return [err.InvalidShapSuffix(invalid_column_names)]
return []
@staticmethod
def _check_reserved_columns(
schema: BaseSchema,
model_type: ModelTypes,
) -> List[err.ReservedColumns]:
if isinstance(schema, CorpusSchema):
return []
elif isinstance(schema, Schema):
reserved_columns = []
column_counts = schema.get_used_columns_counts()
if model_type == ModelTypes.GENERATIVE_LLM:
# Check whether the reserved columns are found in any parts of the schema they are not
# permitted to be. To do this, count the number of times the reserved columns appear in
# the schema. If it's found just once, make sure it's in the correct place. If it's found
# more than once, we know it is somewhere it should not be.
if column_counts.get(LLM_RUN_METADATA_TOTAL_TOKEN_COUNT_TAG_NAME, 0) == 1:
if (
not schema.llm_run_metadata_column_names
or schema.llm_run_metadata_column_names.total_token_count_column_name
!= LLM_RUN_METADATA_TOTAL_TOKEN_COUNT_TAG_NAME
):
reserved_columns.append(LLM_RUN_METADATA_TOTAL_TOKEN_COUNT_TAG_NAME)
if column_counts.get(LLM_RUN_METADATA_TOTAL_TOKEN_COUNT_TAG_NAME, 0) > 1:
reserved_columns.append(LLM_RUN_METADATA_TOTAL_TOKEN_COUNT_TAG_NAME)
if column_counts.get(LLM_RUN_METADATA_PROMPT_TOKEN_COUNT_TAG_NAME, 0) == 1:
if (
not schema.llm_run_metadata_column_names
or schema.llm_run_metadata_column_names.prompt_token_count_column_name
!= LLM_RUN_METADATA_PROMPT_TOKEN_COUNT_TAG_NAME
):
reserved_columns.append(LLM_RUN_METADATA_PROMPT_TOKEN_COUNT_TAG_NAME)
if column_counts.get(LLM_RUN_METADATA_PROMPT_TOKEN_COUNT_TAG_NAME, 0) > 1:
reserved_columns.append(LLM_RUN_METADATA_PROMPT_TOKEN_COUNT_TAG_NAME)
if column_counts.get(LLM_RUN_METADATA_RESPONSE_TOKEN_COUNT_TAG_NAME, 0) == 1:
if (
not schema.llm_run_metadata_column_names
or schema.llm_run_metadata_column_names.response_token_count_column_name
!= LLM_RUN_METADATA_RESPONSE_TOKEN_COUNT_TAG_NAME
):
reserved_columns.append(LLM_RUN_METADATA_RESPONSE_TOKEN_COUNT_TAG_NAME)
if column_counts.get(LLM_RUN_METADATA_RESPONSE_TOKEN_COUNT_TAG_NAME, 0) > 1:
reserved_columns.append(LLM_RUN_METADATA_RESPONSE_TOKEN_COUNT_TAG_NAME)
if column_counts.get(LLM_RUN_METADATA_RESPONSE_LATENCY_MS_TAG_NAME, 0) == 1:
if (
not schema.llm_run_metadata_column_names
or schema.llm_run_metadata_column_names.response_latency_ms_column_name
!= LLM_RUN_METADATA_RESPONSE_LATENCY_MS_TAG_NAME
):
reserved_columns.append(LLM_RUN_METADATA_RESPONSE_LATENCY_MS_TAG_NAME)
if column_counts.get(LLM_RUN_METADATA_RESPONSE_LATENCY_MS_TAG_NAME, 0) > 1:
reserved_columns.append(LLM_RUN_METADATA_RESPONSE_LATENCY_MS_TAG_NAME)
if reserved_columns:
return [err.ReservedColumns(reserved_columns)]
return []
@staticmethod
def _check_invalid_model_id(model_id: Optional[str]) -> List[err.InvalidModelId]:
# assume it's been coerced to string beforehand
if (not isinstance(model_id, str)) or len(model_id.strip()) == 0:
return [err.InvalidModelId()]
return []
@staticmethod
def _check_invalid_model_version(
model_version: Optional[str] = None,
) -> List[err.InvalidModelVersion]:
if model_version is None:
return []
if not isinstance(model_version, str) or len(model_version.strip()) == 0:
return [err.InvalidModelVersion()]
return []
@staticmethod
def _check_invalid_batch_id(
batch_id: Optional[str],
environment: Environments,
) -> List[err.InvalidBatchId]:
# assume it's been coerced to string beforehand
if environment in (Environments.VALIDATION,) and (
(not isinstance(batch_id, str)) or len(batch_id.strip()) == 0
):
return [err.InvalidBatchId()]
return []
@staticmethod
def _check_invalid_model_type(model_type: ModelTypes) -> List[err.InvalidModelType]:
if model_type in (mt for mt in ModelTypes):
return []
return [err.InvalidModelType()]
@staticmethod
def _check_invalid_environment(
environment: Environments,
) -> List[err.InvalidEnvironment]:
if environment in (env for env in Environments):
return []
return [err.InvalidEnvironment()]
@staticmethod
def _check_existence_pred_act_shap_score_or_label(
schema: Schema,
) -> List[err.MissingPredActShapNumericAndCategorical]:
if (
(
schema.prediction_label_column_name is not None
or schema.prediction_score_column_name is not None
)
or (
schema.actual_label_column_name is not None
or schema.actual_score_column_name is not None
)
or schema.shap_values_column_names is not None
):
return []
return [err.MissingPredActShapNumericAndCategorical()]
@staticmethod
def _check_existence_preprod_pred_act_score_or_label(
schema: Schema,
environment: Environments,
) -> List[err.MissingPreprodPredActNumericAndCategorical]:
if environment in (Environments.VALIDATION, Environments.TRAINING) and (
(
schema.prediction_label_column_name is None
and schema.prediction_score_column_name is None
)
or (schema.actual_label_column_name is None and schema.actual_score_column_name is None)
):
return [err.MissingPreprodPredActNumericAndCategorical()]
return []
@staticmethod
def _check_existence_pred_act_od_column_names(
schema: Schema, environment: Environments
) -> List[err.MissingObjectDetectionPredAct]:
# Checks that the required prediction/actual columns are given in the schema depending on
# the environment, for object detection models
if environment == Environments.PRODUCTION:
if (
schema.object_detection_prediction_column_names is None
and schema.object_detection_actual_column_names is None
):
return [err.MissingObjectDetectionPredAct(environment)]
elif environment in (Environments.TRAINING, Environments.VALIDATION):
if (
schema.object_detection_prediction_column_names is None
or schema.object_detection_actual_column_names is None
):
return [err.MissingObjectDetectionPredAct(environment)]
return []
@staticmethod
def _check_missing_object_detection_columns(
schema: Schema, model_type: ModelTypes
) -> List[err.InvalidPredActObjectDetectionColumnNamesForModelType]:
# Checks that models that are not Object Detection models don't have, in the schema, the
# object detection dedicated prediciton/actual column names
if (
schema.object_detection_prediction_column_names is not None
or schema.object_detection_actual_column_names is not None
):
return [err.InvalidPredActObjectDetectionColumnNamesForModelType(model_type)]
return []
@staticmethod
def _check_missing_non_object_detection_columns(
schema: Schema, model_type: ModelTypes
) -> List[err.InvalidPredActColumnNamesForObjectDetectionModelType]:
# Checks that object detection models don't have, in the schema, the columns reserved for
# other model types
columns_to_check = (
schema.prediction_label_column_name,
schema.prediction_score_column_name,
schema.actual_label_column_name,
schema.actual_score_column_name,
schema.prediction_group_id_column_name,
schema.rank_column_name,
schema.attributions_column_name,
schema.relevance_score_column_name,
schema.relevance_labels_column_name,
)
wrong_cols = []
for col in columns_to_check:
if col is not None:
wrong_cols.append(col)
if wrong_cols:
return [err.InvalidPredActColumnNamesForObjectDetectionModelType(wrong_cols)]
return []
@staticmethod
def _check_existence_preprod_act(
schema: Schema,
environment: Environments,
) -> List[err.MissingPreprodAct]:
if environment in (Environments.VALIDATION, Environments.TRAINING) and (
schema.actual_label_column_name is None
):
return [err.MissingPreprodAct()]
return []
@staticmethod
def _check_existence_group_id_rank_category_relevance(
schema: Schema,
) -> List[err.MissingRequiredColumnsForRankingModel]:
# prediction_group_id and rank columns are required as ranking prediction columns.
ranking_prediction_cols = (
schema.prediction_label_column_name,
schema.prediction_score_column_name,
schema.rank_column_name,
schema.prediction_group_id_column_name,
)
has_prediction_info = any(col is not None for col in ranking_prediction_cols)
required = (
schema.prediction_group_id_column_name,
schema.rank_column_name,
)
# If there is prediction information (not delayed actuals),
# there must exist a rank and prediction group id columns
if has_prediction_info and any(col is None for col in required):
return [err.MissingRequiredColumnsForRankingModel()]
return []
@staticmethod
def _check_dataframe_for_duplicate_columns(
schema: BaseSchema, dataframe: pd.DataFrame
) -> List[err.DuplicateColumnsInDataframe]:
# Get the columns used in the schema
schema_col_used = schema.get_used_columns()
# Get the duplicated column names from the dataframe
duplicate_columns = dataframe.columns[dataframe.columns.duplicated()]
# These are the duplicated columns from the dataframe that are referred to by the schema
schema_duplicate_cols = [col for col in duplicate_columns if col in schema_col_used]
if schema_duplicate_cols:
return [err.DuplicateColumnsInDataframe(schema_duplicate_cols)]
return []
@staticmethod
def _check_invalid_number_of_embeddings(
schema: Schema,
) -> List[err.InvalidNumberOfEmbeddings]:
if schema.embedding_feature_column_names is not None:
number_of_embeddings = len(schema.embedding_feature_column_names)
if number_of_embeddings > MAX_NUMBER_OF_EMBEDDINGS:
return [err.InvalidNumberOfEmbeddings(number_of_embeddings)]
return []
# -----------
# Type checks
# -----------
@staticmethod
def _check_type_prediction_id(
schema: Schema, column_types: Dict[str, Any]
) -> List[err.InvalidType]:
col = schema.prediction_id_column_name
if col in column_types:
# should mirror server side
allowed_datatypes = (
pa.string(),
pa.int64(),
pa.int32(),
pa.int16(),
pa.int8(),
)
if column_types[col] not in allowed_datatypes:
return [
err.InvalidType(
"Prediction IDs",
expected_types=["str", "int"],
found_data_type=column_types[col],
)
]
return []
@staticmethod
def _check_type_timestamp(
schema: Schema, column_types: Dict[str, Any]
) -> List[err.InvalidType]: