forked from logicalclocks/hopsworks-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector_server.py
executable file
·1525 lines (1395 loc) · 61.1 KB
/
vector_server.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
#
# Copyright 2022 Logical Clocks AB
#
# 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.
#
from __future__ import annotations
import itertools
import logging
import warnings
from base64 import b64decode
from datetime import datetime, timezone
from io import BytesIO
from typing import Any, Callable, Dict, List, Literal, Optional, Set, Tuple, Union
import avro.io
import avro.schema
import numpy as np
import pandas as pd
from hopsworks_common import client
from hopsworks_common.core.constants import (
HAS_FAST_AVRO,
HAS_POLARS,
polars_not_installed_message,
)
from hsfs import (
feature_view,
training_dataset,
transformation_function,
)
from hsfs import (
serving_key as sk_mod,
)
from hsfs import training_dataset_feature as tdf_mod
from hsfs.client import exceptions, online_store_rest_client
from hsfs.core import (
online_store_rest_client_engine,
online_store_sql_engine,
)
from hsfs.core import (
transformation_function_engine as tf_engine_mod,
)
if HAS_FAST_AVRO:
from fastavro import schemaless_reader
else:
from avro.io import BinaryDecoder
if HAS_POLARS:
import polars as pl
_logger = logging.getLogger(__name__)
class VectorServer:
DEFAULT_REST_CLIENT = "rest"
DEFAULT_SQL_CLIENT = "sql"
# Compatibility with 3.7
DEFAULT_CLIENT_KEY = "default_online_store_client"
REST_CLIENT_CONFIG_OPTIONS_KEY = "config_online_store_rest_client"
RESET_REST_CLIENT_OPTIONS_KEY = "reset_online_store_rest_client"
SQL_TIMESTAMP_STRING_FORMAT = "%Y-%m-%d %H:%M:%S"
def __init__(
self,
feature_store_id: int,
features: Optional[List[tdf_mod.TrainingDatasetFeature]] = None,
serving_keys: Optional[List[sk_mod.ServingKey]] = None,
skip_fg_ids: Optional[Set[int]] = None,
feature_store_name: Optional[str] = None,
feature_view_name: Optional[str] = None,
feature_view_version: Optional[int] = None,
):
self._training_dataset_version = None
self._feature_store_id = feature_store_id
self._feature_store_name = feature_store_name
self._feature_view_name = feature_view_name
self._feature_view_version = feature_view_version
if features is None:
features = []
self._features = features
self._feature_vector_col_name = [
feat.name
for feat in features
if not (
feat.label
or feat.inference_helper_column
or feat.training_helper_column
)
]
self._untransformed_feature_vector_col_name = [
feat.name
for feat in features
if not (
feat.label
or feat.training_helper_column
or feat.on_demand_transformation_function
)
]
self._on_demand_feature_vector_col_name = [
feat.name
for feat in features
if not (feat.label or feat.training_helper_column)
]
self._inference_helper_col_name = [
feat.name for feat in features if feat.inference_helper_column
]
self._transformed_feature_vector_col_name: List[str] = None
self._skip_fg_ids = skip_fg_ids or set()
self._serving_keys = serving_keys or []
self._required_serving_keys = []
self._transformation_function_engine = (
tf_engine_mod.TransformationFunctionEngine(feature_store_id)
)
self._model_dependent_transformation_functions: List[
transformation_function.TransformationFunction
] = []
self._on_demand_transformation_functions: List[
transformation_function.TransformationFunction
] = []
self._sql_client = None
self._rest_client_engine = None
self._init_rest_client: Optional[bool] = None
self._init_sql_client: Optional[bool] = None
self._default_client: Optional[Literal["rest", "sql"]] = None
self._return_feature_value_handlers: Dict[str, Callable] = {}
self._feature_to_handle_if_rest: Optional[Set[str]] = None
self._feature_to_handle_if_sql: Optional[Set[str]] = None
self._valid_serving_keys: Set[str] = set()
self._serving_initialized: bool = False
def init_serving(
self,
entity: Union[feature_view.FeatureView],
training_dataset_version: int,
external: Optional[bool] = None,
inference_helper_columns: bool = False,
options: Optional[Dict[str, Any]] = None,
init_sql_client: Optional[bool] = None,
init_rest_client: bool = False,
reset_rest_client: bool = False,
config_rest_client: Optional[Dict[str, Any]] = None,
default_client: Optional[Literal["rest", "sql"]] = None,
):
self._training_dataset_version = training_dataset_version
if options is not None:
reset_rest_client = reset_rest_client or options.get(
self.RESET_REST_CLIENT_OPTIONS_KEY, False
)
if config_rest_client is None:
config_rest_client = options.get(
self.REST_CLIENT_CONFIG_OPTIONS_KEY,
None,
)
if default_client is None:
default_client = (
options.pop(self.DEFAULT_CLIENT_KEY, self.DEFAULT_SQL_CLIENT)
if isinstance(options, dict)
else self.DEFAULT_SQL_CLIENT
)
self._set_default_client(
init_rest_client=init_rest_client,
init_sql_client=init_sql_client,
default_client=default_client,
)
if external is None:
external = client._is_external()
# `init_prepared_statement` should be the last because other initialisations
# has to be done successfully before it is able to fetch feature vectors.
self.init_transformation(entity)
self.set_return_feature_value_handlers(features=entity.features)
if self._init_rest_client:
self.setup_rest_client_and_engine(
entity=entity,
config_rest_client=config_rest_client,
reset_rest_client=reset_rest_client,
)
if self._init_sql_client:
self.setup_sql_client(
entity=entity,
external=external,
inference_helper_columns=inference_helper_columns,
options=options,
)
self._serving_initialized = True
def init_batch_scoring(
self,
entity: Union[feature_view.FeatureView, training_dataset.TrainingDataset],
training_dataset_version: int,
):
self._training_dataset_version = training_dataset_version
self.init_transformation(entity)
self._serving_initialized = True
def init_transformation(
self,
entity: Union[feature_view.FeatureView],
):
# attach transformation functions
self._model_dependent_transformation_functions = tf_engine_mod.TransformationFunctionEngine.get_ready_to_use_transformation_fns(
entity,
self._training_dataset_version,
)
self._on_demand_transformation_functions = [
feature.on_demand_transformation_function
for feature in entity.features
if feature.on_demand_transformation_function
]
self._on_demand_feature_names = [
feature.name
for feature in entity.features
if feature.on_demand_transformation_function
]
def setup_sql_client(
self,
entity: Union[feature_view.FeatureView, training_dataset.TrainingDataset],
external: bool,
inference_helper_columns: bool,
options: Optional[Dict[str, Any]] = None,
) -> None:
_logger.debug("Initialising Online Store SQL client")
self._sql_client = online_store_sql_engine.OnlineStoreSqlClient(
feature_store_id=self._feature_store_id,
skip_fg_ids=self._skip_fg_ids,
serving_keys=self.serving_keys,
external=external,
)
self.sql_client.init_prepared_statements(
entity,
inference_helper_columns,
)
self.sql_client.init_async_mysql_connection(options=options)
def setup_rest_client_and_engine(
self,
entity: Union[feature_view.FeatureView, training_dataset.TrainingDataset],
config_rest_client: Optional[Dict[str, Any]] = None,
reset_rest_client: bool = False,
):
# naming is off here, but it avoids confusion with the argument init_rest_client
_logger.debug("Initialising Online Store REST client")
self._rest_client_engine = (
online_store_rest_client_engine.OnlineStoreRestClientEngine(
feature_store_name=self._feature_store_name,
feature_view_name=entity.name,
feature_view_version=entity.version,
features=entity.features,
)
)
# This logic needs to move to the above engine init
online_store_rest_client.init_or_reset_online_store_rest_client(
optional_config=config_rest_client,
reset_client=reset_rest_client,
)
def check_missing_request_parameters(
self, features: Dict[str, Any], request_parameters: Dict[str, Any]
):
"""
Check if any request parameters required for computing on-demand features are missing.
# Arguments
feature_vector: `Dict[str, Any]`. The feature vector used to compute on-demand features.
request_parameters: Request parameters required by on-demand transformation functions to compute on-demand features present in the feature view.
"""
request_parameters = {} if not request_parameters else request_parameters
available_parameters = set((features | request_parameters).keys())
missing_request_parameters_features = {}
for on_demand_feature, on_demand_transformation in zip(
self._on_demand_feature_names, self._on_demand_transformation_functions
):
missing_request_parameter = (
set(on_demand_transformation.hopsworks_udf.transformation_features)
- available_parameters
)
if missing_request_parameter:
missing_request_parameters_features[on_demand_feature] = sorted(
list(
set(
on_demand_transformation.hopsworks_udf.transformation_features
)
- available_parameters
)
)
if missing_request_parameters_features:
error = "Missing Request parameters to compute the following the on-demand Features:\n"
for (
feature,
missing_request_parameter,
) in missing_request_parameters_features.items():
missing_request_parameter = "', '".join(missing_request_parameter)
error += f"On-Demand Feature '{feature}' requires features '{missing_request_parameter}'\n"
error += (
"Possible reasons: "
"1. There is no match in the given entry."
" Please check if the entry exists in the online feature store"
" or provide the feature as passed_feature. "
f"2. Required entries [{', '.join(self.required_serving_keys)}] or "
f"[{', '.join(set(sk.feature_name for sk in self._serving_keys))}] are not provided."
)
raise exceptions.FeatureStoreException(error)
def get_feature_vector(
self,
entry: Dict[str, Any],
return_type: Union[Literal["list", "numpy", "pandas", "polars"]],
passed_features: Optional[Dict[str, Any]] = None,
vector_db_features: Optional[Dict[str, Any]] = None,
allow_missing: bool = False,
force_rest_client: bool = False,
force_sql_client: bool = False,
transform: bool = True,
request_parameters: Optional[Dict[str, Any]] = None,
) -> Union[pd.DataFrame, pl.DataFrame, np.ndarray, List[Any], Dict[str, Any]]:
"""Assembles serving vector from online feature store."""
online_client_choice = self.which_client_and_ensure_initialised(
force_rest_client=force_rest_client, force_sql_client=force_sql_client
)
rondb_entry = self.validate_entry(
entry=entry,
allow_missing=allow_missing,
passed_features=passed_features,
vector_db_features=vector_db_features,
)
if len(rondb_entry) == 0:
_logger.debug("Empty entry for rondb, skipping fetching.")
serving_vector = {} # updated below with vector_db_features and passed_features
elif online_client_choice == self.DEFAULT_REST_CLIENT:
_logger.debug("get_feature_vector Online REST client")
serving_vector = self.rest_client_engine.get_single_feature_vector(
rondb_entry,
drop_missing=not allow_missing,
return_type=self.rest_client_engine.RETURN_TYPE_FEATURE_VALUE_DICT,
)
else:
_logger.debug("get_feature_vector Online SQL client")
serving_vector = self.sql_client.get_single_feature_vector(rondb_entry)
vector = self.assemble_feature_vector(
result_dict=serving_vector,
passed_values=passed_features or {},
vector_db_result=vector_db_features or {},
allow_missing=allow_missing,
client=online_client_choice,
transform=transform,
request_parameters=request_parameters,
)
return self.handle_feature_vector_return_type(
vector,
batch=False,
inference_helper=False,
return_type=return_type,
transform=transform,
on_demand_feature=transform,
)
def get_feature_vectors(
self,
entries: List[Dict[str, Any]],
return_type: Optional[
Union[Literal["list", "numpy", "pandas", "polars"]]
] = None,
passed_features: Optional[List[Dict[str, Any]]] = None,
vector_db_features: Optional[List[Dict[str, Any]]] = None,
request_parameters: Optional[List[Dict[str, Any]]] = None,
allow_missing: bool = False,
force_rest_client: bool = False,
force_sql_client: bool = False,
transform: bool = True,
) -> Union[pd.DataFrame, pl.DataFrame, np.ndarray, List[Any], List[Dict[str, Any]]]:
"""Assembles serving vector from online feature store."""
if passed_features is None:
passed_features = []
# Assertions on passed_features and vector_db_features
assert (
passed_features is None
or len(passed_features) == 0
or len(passed_features) == len(entries)
), "Passed features should be None, empty or have the same length as the entries"
assert (
vector_db_features is None
or len(vector_db_features) == 0
or len(vector_db_features) == len(entries)
), "Vector DB features should be None, empty or have the same length as the entries"
assert (
request_parameters is None
or len(request_parameters) == 0
or isinstance(request_parameters, dict)
or len(request_parameters) == len(entries)
), "Request Parameters should be a Dictionary, None, empty or have the same length as the entries"
online_client_choice = self.which_client_and_ensure_initialised(
force_rest_client=force_rest_client, force_sql_client=force_sql_client
)
rondb_entries = []
skipped_empty_entries = []
for (idx, entry), passed, vector_features in itertools.zip_longest(
enumerate(entries),
passed_features,
vector_db_features,
):
rondb_entry = self.validate_entry(
entry=entry,
allow_missing=allow_missing,
passed_features=passed,
vector_db_features=vector_features,
)
if len(rondb_entry) != 0:
rondb_entries.append(rondb_entry)
else:
skipped_empty_entries.append(idx)
if online_client_choice == self.DEFAULT_REST_CLIENT and len(rondb_entries) > 0:
_logger.debug("get_batch_feature_vector Online REST client")
batch_results = self.rest_client_engine.get_batch_feature_vectors(
entries=rondb_entries,
drop_missing=not allow_missing,
return_type=self.rest_client_engine.RETURN_TYPE_FEATURE_VALUE_DICT,
)
elif len(rondb_entries) > 0:
# get result row
_logger.debug("get_batch_feature_vectors through SQL client")
batch_results, _ = self.sql_client.get_batch_feature_vectors(rondb_entries)
else:
_logger.debug("Empty entries for rondb, skipping fetching.")
batch_results = []
_logger.debug("Assembling feature vectors from batch results")
next_skipped = (
skipped_empty_entries.pop(0) if len(skipped_empty_entries) > 0 else None
)
vectors = []
# If request parameter is a dictionary then copy it to list with the same length as that of entires
request_parameters = (
[request_parameters] * len(entries)
if isinstance(request_parameters, dict)
else request_parameters
)
for (
idx,
passed_values,
vector_db_result,
request_parameter,
) in itertools.zip_longest(
range(len(entries)),
passed_features or [],
vector_db_features or [],
request_parameters or [],
fillvalue=None,
):
if next_skipped == idx:
_logger.debug("Entry %d was skipped, setting to empty dict.", idx)
next_skipped = (
skipped_empty_entries.pop(0)
if len(skipped_empty_entries) > 0
else None
)
result_dict = {}
else:
result_dict = batch_results.pop(0)
vector = self.assemble_feature_vector(
result_dict=result_dict,
passed_values=passed_values,
vector_db_result=vector_db_result,
allow_missing=allow_missing,
client=online_client_choice,
transform=transform,
request_parameters=request_parameter,
)
if vector is not None:
vectors.append(vector)
return self.handle_feature_vector_return_type(
vectors,
batch=True,
inference_helper=False,
return_type=return_type,
transform=transform,
on_demand_feature=transform,
)
def assemble_feature_vector(
self,
result_dict: Dict[str, Any],
passed_values: Optional[Dict[str, Any]],
vector_db_result: Optional[Dict[str, Any]],
allow_missing: bool,
client: Literal["rest", "sql"],
transform: bool,
request_parameters: Optional[Dict[str, Any]] = None,
) -> Optional[List[Any]]:
"""Assembles serving vector from online feature store."""
# Errors in batch requests are returned as None values
_logger.debug("Assembling serving vector: %s", result_dict)
if result_dict is None:
_logger.debug("Found null result, setting to empty dict.")
result_dict = {}
if vector_db_result is not None and len(vector_db_result) > 0:
_logger.debug("Updating with vector_db features: %s", vector_db_result)
result_dict.update(vector_db_result)
if passed_values is not None and len(passed_values) > 0:
_logger.debug("Updating with passed features: %s", passed_values)
result_dict.update(passed_values)
missing_features = (
set(self.feature_vector_col_name)
.difference(result_dict.keys())
.difference(self._on_demand_feature_names)
)
self.check_missing_request_parameters(
features=result_dict, request_parameters=request_parameters
)
# for backward compatibility, before 3.4, if result is empty,
# instead of throwing error, it skips the result
# Maybe we drop this behaviour for 4.0
if len(result_dict) == 0 and not allow_missing:
return None
if not allow_missing and len(missing_features) > 0:
raise exceptions.FeatureStoreException(
f"Feature(s) {str(missing_features)} is missing from vector."
"Possible reasons: "
"1. There is no match in the given entry."
" Please check if the entry exists in the online feature store"
" or provide the feature as passed_feature. "
f"2. Required entries [{', '.join(self.required_serving_keys)}] are not provided."
)
if len(self.return_feature_value_handlers) > 0:
self.apply_return_value_handlers(result_dict, client=client)
if (
len(self.model_dependent_transformation_functions) > 0
or len(self.on_demand_transformation_functions) > 0
) and transform:
self.apply_transformation(result_dict, request_parameters or {})
_logger.debug("Assembled and transformed dict feature vector: %s", result_dict)
if transform:
return [
result_dict.get(fname, None)
for fname in self.transformed_feature_vector_col_name
]
else:
return [
result_dict.get(fname, None)
for fname in self._untransformed_feature_vector_col_name
]
def _check_feature_vectors_type_and_convert_to_dict(
self,
feature_vectors: Union[List[Any], List[List[Any]], pd.DataFrame, pl.DataFrame],
on_demand_features: bool = False,
) -> Tuple[Dict[str, Any], Literal["pandas", "polars", "list"]]:
"""
Function that converts an input feature vector into a list of dictionaries.
# Arguments
feature_vectors: `Union[List[Any], List[List[Any]], pd.DataFrame, pl.DataFrame]`. The feature vectors to be converted.
on_demand_features : `bool`. Specify if on-demand features provided in the input feature vector.
# Returns
`Tuple[Dict[str, Any], Literal["pandas", "polars", "list"]]`: A tuple that contains the feature vector as a dictionary and a string denoting the data type of the input feature vector.
"""
if isinstance(feature_vectors, pd.DataFrame):
return_type = "pandas"
feature_vectors = feature_vectors.to_dict(orient="records")
elif HAS_POLARS and isinstance(feature_vectors, pl.DataFrame):
return_type = "polars"
feature_vectors = feature_vectors.to_pandas()
feature_vectors = feature_vectors.to_dict(orient="records")
elif isinstance(feature_vectors, list) and feature_vectors:
if all(
isinstance(feature_vector, list) for feature_vector in feature_vectors
):
return_type = "list"
feature_vectors = [
self.get_untransformed_features_map(
feature_vector, on_demand_features=on_demand_features
)
for feature_vector in feature_vectors
]
else:
return_type = "list"
feature_vectors = [
self.get_untransformed_features_map(
feature_vectors, on_demand_features=on_demand_features
)
]
else:
raise exceptions.FeatureStoreException(
"Unsupported input type for feature vector. Supported types are `List`, `pandas.DataFrame`, `polars.DataFrame`"
)
return feature_vectors, return_type
def transform(
self,
feature_vectors: Union[List[Any], List[List[Any]], pd.DataFrame, pl.DataFrame],
) -> Union[List[Any], List[List[Any]], pd.DataFrame, pl.DataFrame]:
"""
Applies model dependent transformation on the provided feature vector.
# Arguments
feature_vectors: `Union[List[Any], List[List[Any]], pd.DataFrame, pl.DataFrame]`. The feature vectors to be transformed using attached model-dependent transformations.
# Returns
`Union[List[Any], List[List[Any]], pd.DataFrame, pl.DataFrame]`: The transformed feature vector.
"""
if not self._model_dependent_transformation_functions:
warnings.warn(
"Feature view does not have any attached model-dependent transformations. Returning input feature vectors.",
stacklevel=0,
)
return feature_vectors
feature_vectors, return_type = (
self._check_feature_vectors_type_and_convert_to_dict(
feature_vectors, on_demand_features=True
)
)
transformed_feature_vectors = []
for feature_vector in feature_vectors:
transformed_feature_vector = self.apply_model_dependent_transformations(
feature_vector
)
transformed_feature_vectors.append(
[
transformed_feature_vector.get(fname, None)
for fname in self.transformed_feature_vector_col_name
]
)
if len(transformed_feature_vectors) == 1:
batch = False
transformed_feature_vectors = transformed_feature_vectors[0]
else:
batch = True
return self.handle_feature_vector_return_type(
transformed_feature_vectors,
batch=batch,
inference_helper=False,
return_type=return_type,
transform=True,
)
def compute_on_demand_features(
self,
feature_vectors: Union[List[Any], List[List[Any]], pd.DataFrame, pl.DataFrame],
request_parameters: Union[List[Dict[str, Any]], Dict[str, Any]],
):
"""
Function computes on-demand features present in the feature view.
# Arguments
feature_vector: `Union[List[Any], List[List[Any]], pd.DataFrame, pl.DataFrame]`. The feature vector to be transformed.
request_parameters: Request parameters required by on-demand transformation functions to compute on-demand features present in the feature view.
# Returns
`Union[List[Any], List[List[Any]], pd.DataFrame, pl.DataFrame]`: The feature vector that contains all on-demand features in the feature view.
"""
if not self._on_demand_transformation_functions:
warnings.warn(
"Feature view does not have any on-demand features. Returning input feature vectors.",
stacklevel=1,
)
return feature_vectors
request_parameters = {} if not request_parameters else request_parameters
# Convert feature vectors to dictionary
feature_vectors, return_type = (
self._check_feature_vectors_type_and_convert_to_dict(feature_vectors)
)
# Check if all request parameters are provided
# If request parameter is a dictionary then copy it to list with the same length as that of entires
request_parameters = (
[request_parameters] * len(feature_vectors)
if isinstance(request_parameters, dict)
else request_parameters
)
self.check_missing_request_parameters(
features=feature_vectors[0], request_parameters=request_parameters[0]
)
on_demand_feature_vectors = []
for feature_vector, request_parameter in zip(
feature_vectors, request_parameters
):
on_demand_feature_vector = self.apply_on_demand_transformations(
feature_vector, request_parameter
)
on_demand_feature_vectors.append(
[
on_demand_feature_vector.get(fname, None)
for fname in self._on_demand_feature_vector_col_name
]
)
if len(on_demand_feature_vectors) == 1:
batch = False
on_demand_feature_vectors = on_demand_feature_vectors[0]
else:
batch = True
return self.handle_feature_vector_return_type(
on_demand_feature_vectors,
batch=batch,
inference_helper=False,
return_type=return_type,
transform=False,
on_demand_feature=True,
)
def get_untransformed_features_map(
self, features: List[Any], on_demand_features: bool = False
) -> Dict[str, Any]:
"""
Function that accepts a feature vectors as a list and returns the untransformed features as a dict that maps
feature names to their values
# Arguments
features : `List[Any]`. List of feature vectors.
on_demand_features : `bool`. Specify if on-demand features provided in the input feature vector.
# Returns
`Dict[str, Any]` : Dictionary mapping features name to values.
"""
if on_demand_features:
return dict(
[
(fname, fvalue)
for fname, fvalue in zip(
self._on_demand_feature_vector_col_name, features
)
]
)
else:
return dict(
[
(fname, fvalue)
for fname, fvalue in zip(
self._untransformed_feature_vector_col_name, features
)
]
)
def handle_feature_vector_return_type(
self,
feature_vectorz: Union[
List[Any], List[List[Any]], Dict[str, Any], List[Dict[str, Any]]
],
batch: bool,
inference_helper: bool,
return_type: Union[Literal["list", "dict", "numpy", "pandas", "polars"]],
transform: bool = False,
on_demand_feature: bool = False,
) -> Union[
pd.DataFrame,
pl.DataFrame,
np.ndarray,
List[Any],
List[List[Any]],
Dict[str, Any],
List[Dict[str, Any]],
]:
if transform:
column_names = self.transformed_feature_vector_col_name
else:
if on_demand_feature:
column_names = self._on_demand_feature_vector_col_name
else:
column_names = self._untransformed_feature_vector_col_name
# Only get-feature-vector and get-feature-vectors can return list or numpy
if return_type.lower() == "list" and not inference_helper:
_logger.debug("Returning feature vector as value list")
return feature_vectorz
elif return_type.lower() == "numpy" and not inference_helper:
_logger.debug("Returning feature vector as numpy array")
return np.array(feature_vectorz)
# Only inference helper can return dict
elif return_type.lower() == "dict" and inference_helper:
_logger.debug("Returning feature vector as dictionary")
return feature_vectorz
# Both can return pandas and polars
elif return_type.lower() == "pandas":
_logger.debug("Returning feature vector as pandas dataframe")
if batch and inference_helper:
return pd.DataFrame(feature_vectorz)
elif inference_helper:
return pd.DataFrame([feature_vectorz])
elif batch:
return pd.DataFrame(feature_vectorz, columns=column_names)
else:
pandas_df = pd.DataFrame(feature_vectorz).transpose()
pandas_df.columns = column_names
return pandas_df
elif return_type.lower() == "polars":
_logger.debug("Returning feature vector as polars dataframe")
if not HAS_POLARS:
raise ModuleNotFoundError(polars_not_installed_message)
return pl.DataFrame(
feature_vectorz if batch else [feature_vectorz],
schema=column_names if not inference_helper else None,
orient="row",
)
else:
raise ValueError(
f"""Unknown return type. Supported return types are {"'list', 'numpy'" if not inference_helper else "'dict'"}, 'polars' and 'pandas''"""
)
def get_inference_helper(
self,
entry: Dict[str, Any],
return_type: Union[Literal["dict", "pandas", "polars"]],
force_rest_client: bool,
force_sql_client: bool,
) -> Union[pd.DataFrame, pl.DataFrame, Dict[str, Any]]:
"""Assembles serving vector from online feature store."""
default_client = self.which_client_and_ensure_initialised(
force_rest_client, force_sql_client
)
_logger.debug(
f"Retrieve inference helper values for single entry via {default_client.upper()} client."
)
_logger.debug(f"entry: {entry} as return type: {return_type}")
if default_client == self.DEFAULT_REST_CLIENT:
return self.handle_feature_vector_return_type(
self.rest_client_engine.get_single_feature_vector(
entry,
return_type=self.rest_client_engine.RETURN_TYPE_FEATURE_VALUE_DICT,
inference_helpers_only=True,
),
batch=False,
inference_helper=True,
return_type=return_type,
transform=False,
on_demand_feature=False,
)
return self.handle_feature_vector_return_type(
self.sql_client.get_inference_helper_vector(entry),
batch=False,
inference_helper=True,
return_type=return_type,
transform=False,
on_demand_feature=False,
)
def get_inference_helpers(
self,
feature_view_object: feature_view.FeatureView,
entries: List[Dict[str, Any]],
return_type: Union[Literal["dict", "pandas", "polars"]],
force_rest_client: bool,
force_sql_client: bool,
) -> Union[pd.DataFrame, pl.DataFrame, List[Dict[str, Any]]]:
"""Assembles serving vector from online feature store."""
default_client = self.which_client_and_ensure_initialised(
force_rest_client, force_sql_client
)
_logger.debug(
f"Retrieve inference helper values for batch entries via {default_client.upper()} client."
)
_logger.debug(f"entries: {entries} as return type: {return_type}")
if default_client == self.DEFAULT_REST_CLIENT:
batch_results = self.rest_client_engine.get_batch_feature_vectors(
entries,
return_type=self.rest_client_engine.RETURN_TYPE_FEATURE_VALUE_DICT,
inference_helpers_only=True,
)
else:
batch_results, serving_keys = (
self.sql_client.get_batch_inference_helper_vectors(entries)
)
# drop serving and primary key names from the result dict
drop_list = serving_keys + list(feature_view_object.primary_keys)
_ = list(
map(
lambda results_dict: [
results_dict.pop(x, None)
for x in drop_list
if x not in feature_view_object.inference_helper_columns
],
batch_results,
)
)
return self.handle_feature_vector_return_type(
batch_results,
batch=True,
inference_helper=True,
return_type=return_type,
transform=False,
on_demand_feature=False,
)
def which_client_and_ensure_initialised(
self, force_rest_client: bool, force_sql_client: bool
) -> str:
"""Check if the requested client is initialised as well as deciding which client to use based on default.
# Arguments:
force_rest_client: bool. user specified override to use rest_client.
force_sql_client: bool. user specified override to use sql_client.
# Returns:
An enum specifying the client to be used.
"""
if force_rest_client and force_sql_client:
raise ValueError(
"force_rest_client and force_sql_client cannot be used at the same time."
)
# No override, use default client
if not force_rest_client and not force_sql_client:
return self.default_client
if self._init_rest_client is False and self._init_sql_client is False:
raise ValueError(
"No client is initialised. Call `init_serving` with initsql_client or init_rest_client set to True before using it."
)
if force_sql_client and (self._init_sql_client is False):
raise ValueError(
"SQL Client is not initialised. Call `init_serving` with init_sql_client set to True before using it."
)
elif force_sql_client:
return self.DEFAULT_SQL_CLIENT
if force_rest_client and (self._init_rest_client is False):
raise ValueError(
"RonDB Rest Client is not initialised. Call `init_serving` with init_rest_client set to True before using it."
)
elif force_rest_client:
return self.DEFAULT_REST_CLIENT
def _set_default_client(
self,
init_rest_client: bool,
init_sql_client: bool,
default_client: Optional[str] = None,
):
if init_rest_client is False and init_sql_client is False:
raise ValueError(
"At least one of the clients should be initialised. Set init_sql_client or init_rest_client to True."
)
self._init_rest_client = init_rest_client
self._init_sql_client = init_sql_client
if init_rest_client is True and init_sql_client is True:
self.default_client = default_client
elif init_rest_client is True:
self.default_client = self.DEFAULT_REST_CLIENT
else:
self.default_client = self.DEFAULT_SQL_CLIENT
self._init_sql_client = True
def apply_on_demand_transformations(
self, rows: Union[dict, pd.DataFrame], request_parameter: Dict[str, Any]
) -> dict:
_logger.debug("Applying On-Demand transformation functions.")
for tf in self._on_demand_transformation_functions:
# Check if feature provided as request parameter if not get it from retrieved feature vector.
features = [
pd.Series(request_parameter[feature])
if feature in request_parameter.keys()
else (
pd.Series(
rows[feature]