snowflake-ml-python 1.1.0__py3-none-any.whl → 1.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- snowflake/cortex/_complete.py +1 -1
- snowflake/cortex/_extract_answer.py +1 -1
- snowflake/cortex/_sentiment.py +1 -1
- snowflake/cortex/_summarize.py +1 -1
- snowflake/cortex/_translate.py +1 -1
- snowflake/ml/_internal/env_utils.py +68 -6
- snowflake/ml/_internal/file_utils.py +34 -4
- snowflake/ml/_internal/telemetry.py +79 -91
- snowflake/ml/_internal/utils/identifier.py +78 -72
- snowflake/ml/_internal/utils/retryable_http.py +16 -4
- snowflake/ml/_internal/utils/spcs_attribution_utils.py +122 -0
- snowflake/ml/dataset/dataset.py +1 -1
- snowflake/ml/model/_api.py +21 -14
- snowflake/ml/model/_client/model/model_impl.py +176 -0
- snowflake/ml/model/_client/model/model_method_info.py +19 -0
- snowflake/ml/model/_client/model/model_version_impl.py +291 -0
- snowflake/ml/model/_client/ops/metadata_ops.py +107 -0
- snowflake/ml/model/_client/ops/model_ops.py +308 -0
- snowflake/ml/model/_client/sql/model.py +75 -0
- snowflake/ml/model/_client/sql/model_version.py +213 -0
- snowflake/ml/model/_client/sql/stage.py +40 -0
- snowflake/ml/model/_deploy_client/image_builds/server_image_builder.py +3 -4
- snowflake/ml/model/_deploy_client/image_builds/templates/image_build_job_spec_template +24 -8
- snowflake/ml/model/_deploy_client/image_builds/templates/kaniko_shell_script_template +23 -0
- snowflake/ml/model/_deploy_client/snowservice/deploy.py +14 -2
- snowflake/ml/model/_deploy_client/utils/constants.py +1 -0
- snowflake/ml/model/_deploy_client/warehouse/deploy.py +2 -2
- snowflake/ml/model/_model_composer/model_composer.py +31 -9
- snowflake/ml/model/_model_composer/model_manifest/model_manifest.py +25 -10
- snowflake/ml/model/_model_composer/model_manifest/model_manifest_schema.py +2 -2
- snowflake/ml/model/_model_composer/model_method/infer_function.py_template +2 -1
- snowflake/ml/model/_model_composer/model_method/model_method.py +34 -3
- snowflake/ml/model/_model_composer/model_runtime/model_runtime.py +1 -1
- snowflake/ml/model/_packager/model_handlers/huggingface_pipeline.py +3 -1
- snowflake/ml/model/_packager/model_handlers/snowmlmodel.py +10 -28
- snowflake/ml/model/_packager/model_meta/model_meta.py +18 -16
- snowflake/ml/model/_signatures/snowpark_handler.py +1 -1
- snowflake/ml/model/model_signature.py +108 -53
- snowflake/ml/model/type_hints.py +1 -0
- snowflake/ml/modeling/_internal/distributed_hpo_trainer.py +554 -0
- snowflake/ml/modeling/_internal/estimator_protocols.py +1 -60
- snowflake/ml/modeling/_internal/model_specifications.py +146 -0
- snowflake/ml/modeling/_internal/model_trainer.py +13 -0
- snowflake/ml/modeling/_internal/model_trainer_builder.py +78 -0
- snowflake/ml/modeling/_internal/pandas_trainer.py +54 -0
- snowflake/ml/modeling/_internal/snowpark_handlers.py +6 -760
- snowflake/ml/modeling/_internal/snowpark_trainer.py +331 -0
- snowflake/ml/modeling/calibration/calibrated_classifier_cv.py +108 -135
- snowflake/ml/modeling/cluster/affinity_propagation.py +106 -135
- snowflake/ml/modeling/cluster/agglomerative_clustering.py +106 -135
- snowflake/ml/modeling/cluster/birch.py +106 -135
- snowflake/ml/modeling/cluster/bisecting_k_means.py +106 -135
- snowflake/ml/modeling/cluster/dbscan.py +106 -135
- snowflake/ml/modeling/cluster/feature_agglomeration.py +106 -135
- snowflake/ml/modeling/cluster/k_means.py +105 -135
- snowflake/ml/modeling/cluster/mean_shift.py +106 -135
- snowflake/ml/modeling/cluster/mini_batch_k_means.py +105 -135
- snowflake/ml/modeling/cluster/optics.py +106 -135
- snowflake/ml/modeling/cluster/spectral_biclustering.py +106 -135
- snowflake/ml/modeling/cluster/spectral_clustering.py +106 -135
- snowflake/ml/modeling/cluster/spectral_coclustering.py +106 -135
- snowflake/ml/modeling/compose/column_transformer.py +106 -135
- snowflake/ml/modeling/compose/transformed_target_regressor.py +108 -135
- snowflake/ml/modeling/covariance/elliptic_envelope.py +106 -135
- snowflake/ml/modeling/covariance/empirical_covariance.py +99 -128
- snowflake/ml/modeling/covariance/graphical_lasso.py +106 -135
- snowflake/ml/modeling/covariance/graphical_lasso_cv.py +106 -135
- snowflake/ml/modeling/covariance/ledoit_wolf.py +104 -133
- snowflake/ml/modeling/covariance/min_cov_det.py +106 -135
- snowflake/ml/modeling/covariance/oas.py +99 -128
- snowflake/ml/modeling/covariance/shrunk_covariance.py +103 -132
- snowflake/ml/modeling/decomposition/dictionary_learning.py +106 -135
- snowflake/ml/modeling/decomposition/factor_analysis.py +106 -135
- snowflake/ml/modeling/decomposition/fast_ica.py +106 -135
- snowflake/ml/modeling/decomposition/incremental_pca.py +106 -135
- snowflake/ml/modeling/decomposition/kernel_pca.py +106 -135
- snowflake/ml/modeling/decomposition/mini_batch_dictionary_learning.py +106 -135
- snowflake/ml/modeling/decomposition/mini_batch_sparse_pca.py +106 -135
- snowflake/ml/modeling/decomposition/pca.py +106 -135
- snowflake/ml/modeling/decomposition/sparse_pca.py +106 -135
- snowflake/ml/modeling/decomposition/truncated_svd.py +106 -135
- snowflake/ml/modeling/discriminant_analysis/linear_discriminant_analysis.py +108 -135
- snowflake/ml/modeling/discriminant_analysis/quadratic_discriminant_analysis.py +108 -135
- snowflake/ml/modeling/ensemble/ada_boost_classifier.py +108 -135
- snowflake/ml/modeling/ensemble/ada_boost_regressor.py +108 -135
- snowflake/ml/modeling/ensemble/bagging_classifier.py +108 -135
- snowflake/ml/modeling/ensemble/bagging_regressor.py +108 -135
- snowflake/ml/modeling/ensemble/extra_trees_classifier.py +108 -135
- snowflake/ml/modeling/ensemble/extra_trees_regressor.py +108 -135
- snowflake/ml/modeling/ensemble/gradient_boosting_classifier.py +108 -135
- snowflake/ml/modeling/ensemble/gradient_boosting_regressor.py +108 -135
- snowflake/ml/modeling/ensemble/hist_gradient_boosting_classifier.py +108 -135
- snowflake/ml/modeling/ensemble/hist_gradient_boosting_regressor.py +108 -135
- snowflake/ml/modeling/ensemble/isolation_forest.py +106 -135
- snowflake/ml/modeling/ensemble/random_forest_classifier.py +108 -135
- snowflake/ml/modeling/ensemble/random_forest_regressor.py +108 -135
- snowflake/ml/modeling/ensemble/stacking_regressor.py +108 -135
- snowflake/ml/modeling/ensemble/voting_classifier.py +108 -135
- snowflake/ml/modeling/ensemble/voting_regressor.py +108 -135
- snowflake/ml/modeling/feature_selection/generic_univariate_select.py +101 -128
- snowflake/ml/modeling/feature_selection/select_fdr.py +99 -126
- snowflake/ml/modeling/feature_selection/select_fpr.py +99 -126
- snowflake/ml/modeling/feature_selection/select_fwe.py +99 -126
- snowflake/ml/modeling/feature_selection/select_k_best.py +100 -127
- snowflake/ml/modeling/feature_selection/select_percentile.py +99 -126
- snowflake/ml/modeling/feature_selection/sequential_feature_selector.py +106 -135
- snowflake/ml/modeling/feature_selection/variance_threshold.py +95 -124
- snowflake/ml/modeling/framework/base.py +83 -1
- snowflake/ml/modeling/gaussian_process/gaussian_process_classifier.py +108 -135
- snowflake/ml/modeling/gaussian_process/gaussian_process_regressor.py +108 -135
- snowflake/ml/modeling/impute/iterative_imputer.py +106 -135
- snowflake/ml/modeling/impute/knn_imputer.py +106 -135
- snowflake/ml/modeling/impute/missing_indicator.py +106 -135
- snowflake/ml/modeling/impute/simple_imputer.py +9 -1
- snowflake/ml/modeling/kernel_approximation/additive_chi2_sampler.py +96 -125
- snowflake/ml/modeling/kernel_approximation/nystroem.py +106 -135
- snowflake/ml/modeling/kernel_approximation/polynomial_count_sketch.py +106 -135
- snowflake/ml/modeling/kernel_approximation/rbf_sampler.py +105 -134
- snowflake/ml/modeling/kernel_approximation/skewed_chi2_sampler.py +103 -132
- snowflake/ml/modeling/kernel_ridge/kernel_ridge.py +108 -135
- snowflake/ml/modeling/lightgbm/lgbm_classifier.py +90 -118
- snowflake/ml/modeling/lightgbm/lgbm_regressor.py +90 -118
- snowflake/ml/modeling/linear_model/ard_regression.py +108 -135
- snowflake/ml/modeling/linear_model/bayesian_ridge.py +108 -135
- snowflake/ml/modeling/linear_model/elastic_net.py +108 -135
- snowflake/ml/modeling/linear_model/elastic_net_cv.py +108 -135
- snowflake/ml/modeling/linear_model/gamma_regressor.py +108 -135
- snowflake/ml/modeling/linear_model/huber_regressor.py +108 -135
- snowflake/ml/modeling/linear_model/lars.py +108 -135
- snowflake/ml/modeling/linear_model/lars_cv.py +108 -135
- snowflake/ml/modeling/linear_model/lasso.py +108 -135
- snowflake/ml/modeling/linear_model/lasso_cv.py +108 -135
- snowflake/ml/modeling/linear_model/lasso_lars.py +108 -135
- snowflake/ml/modeling/linear_model/lasso_lars_cv.py +108 -135
- snowflake/ml/modeling/linear_model/lasso_lars_ic.py +108 -135
- snowflake/ml/modeling/linear_model/linear_regression.py +108 -135
- snowflake/ml/modeling/linear_model/logistic_regression.py +108 -135
- snowflake/ml/modeling/linear_model/logistic_regression_cv.py +108 -135
- snowflake/ml/modeling/linear_model/multi_task_elastic_net.py +108 -135
- snowflake/ml/modeling/linear_model/multi_task_elastic_net_cv.py +108 -135
- snowflake/ml/modeling/linear_model/multi_task_lasso.py +108 -135
- snowflake/ml/modeling/linear_model/multi_task_lasso_cv.py +108 -135
- snowflake/ml/modeling/linear_model/orthogonal_matching_pursuit.py +108 -135
- snowflake/ml/modeling/linear_model/passive_aggressive_classifier.py +108 -135
- snowflake/ml/modeling/linear_model/passive_aggressive_regressor.py +107 -135
- snowflake/ml/modeling/linear_model/perceptron.py +107 -135
- snowflake/ml/modeling/linear_model/poisson_regressor.py +108 -135
- snowflake/ml/modeling/linear_model/ransac_regressor.py +108 -135
- snowflake/ml/modeling/linear_model/ridge.py +108 -135
- snowflake/ml/modeling/linear_model/ridge_classifier.py +108 -135
- snowflake/ml/modeling/linear_model/ridge_classifier_cv.py +108 -135
- snowflake/ml/modeling/linear_model/ridge_cv.py +108 -135
- snowflake/ml/modeling/linear_model/sgd_classifier.py +108 -135
- snowflake/ml/modeling/linear_model/sgd_one_class_svm.py +106 -135
- snowflake/ml/modeling/linear_model/sgd_regressor.py +108 -135
- snowflake/ml/modeling/linear_model/theil_sen_regressor.py +108 -135
- snowflake/ml/modeling/linear_model/tweedie_regressor.py +108 -135
- snowflake/ml/modeling/manifold/isomap.py +106 -135
- snowflake/ml/modeling/manifold/mds.py +106 -135
- snowflake/ml/modeling/manifold/spectral_embedding.py +106 -135
- snowflake/ml/modeling/manifold/tsne.py +106 -135
- snowflake/ml/modeling/metrics/classification.py +196 -55
- snowflake/ml/modeling/metrics/correlation.py +4 -2
- snowflake/ml/modeling/metrics/covariance.py +7 -4
- snowflake/ml/modeling/metrics/ranking.py +32 -16
- snowflake/ml/modeling/metrics/regression.py +60 -32
- snowflake/ml/modeling/mixture/bayesian_gaussian_mixture.py +106 -135
- snowflake/ml/modeling/mixture/gaussian_mixture.py +106 -135
- snowflake/ml/modeling/model_selection/grid_search_cv.py +91 -148
- snowflake/ml/modeling/model_selection/randomized_search_cv.py +93 -154
- snowflake/ml/modeling/multiclass/one_vs_one_classifier.py +105 -132
- snowflake/ml/modeling/multiclass/one_vs_rest_classifier.py +108 -135
- snowflake/ml/modeling/multiclass/output_code_classifier.py +108 -135
- snowflake/ml/modeling/naive_bayes/bernoulli_nb.py +108 -135
- snowflake/ml/modeling/naive_bayes/categorical_nb.py +108 -135
- snowflake/ml/modeling/naive_bayes/complement_nb.py +108 -135
- snowflake/ml/modeling/naive_bayes/gaussian_nb.py +98 -125
- snowflake/ml/modeling/naive_bayes/multinomial_nb.py +107 -134
- snowflake/ml/modeling/neighbors/k_neighbors_classifier.py +108 -135
- snowflake/ml/modeling/neighbors/k_neighbors_regressor.py +108 -135
- snowflake/ml/modeling/neighbors/kernel_density.py +106 -135
- snowflake/ml/modeling/neighbors/local_outlier_factor.py +106 -135
- snowflake/ml/modeling/neighbors/nearest_centroid.py +108 -135
- snowflake/ml/modeling/neighbors/nearest_neighbors.py +106 -135
- snowflake/ml/modeling/neighbors/neighborhood_components_analysis.py +108 -135
- snowflake/ml/modeling/neighbors/radius_neighbors_classifier.py +108 -135
- snowflake/ml/modeling/neighbors/radius_neighbors_regressor.py +108 -135
- snowflake/ml/modeling/neural_network/bernoulli_rbm.py +106 -135
- snowflake/ml/modeling/neural_network/mlp_classifier.py +108 -135
- snowflake/ml/modeling/neural_network/mlp_regressor.py +108 -135
- snowflake/ml/modeling/parameters/disable_distributed_hpo.py +2 -6
- snowflake/ml/modeling/preprocessing/binarizer.py +25 -8
- snowflake/ml/modeling/preprocessing/k_bins_discretizer.py +9 -4
- snowflake/ml/modeling/preprocessing/label_encoder.py +31 -11
- snowflake/ml/modeling/preprocessing/max_abs_scaler.py +27 -9
- snowflake/ml/modeling/preprocessing/min_max_scaler.py +42 -14
- snowflake/ml/modeling/preprocessing/normalizer.py +9 -4
- snowflake/ml/modeling/preprocessing/one_hot_encoder.py +26 -10
- snowflake/ml/modeling/preprocessing/ordinal_encoder.py +37 -13
- snowflake/ml/modeling/preprocessing/polynomial_features.py +106 -135
- snowflake/ml/modeling/preprocessing/robust_scaler.py +39 -13
- snowflake/ml/modeling/preprocessing/standard_scaler.py +36 -12
- snowflake/ml/modeling/semi_supervised/label_propagation.py +108 -135
- snowflake/ml/modeling/semi_supervised/label_spreading.py +108 -135
- snowflake/ml/modeling/svm/linear_svc.py +108 -135
- snowflake/ml/modeling/svm/linear_svr.py +108 -135
- snowflake/ml/modeling/svm/nu_svc.py +108 -135
- snowflake/ml/modeling/svm/nu_svr.py +108 -135
- snowflake/ml/modeling/svm/svc.py +108 -135
- snowflake/ml/modeling/svm/svr.py +108 -135
- snowflake/ml/modeling/tree/decision_tree_classifier.py +108 -135
- snowflake/ml/modeling/tree/decision_tree_regressor.py +108 -135
- snowflake/ml/modeling/tree/extra_tree_classifier.py +108 -135
- snowflake/ml/modeling/tree/extra_tree_regressor.py +108 -135
- snowflake/ml/modeling/xgboost/xgb_classifier.py +108 -136
- snowflake/ml/modeling/xgboost/xgb_regressor.py +108 -136
- snowflake/ml/modeling/xgboost/xgbrf_classifier.py +108 -136
- snowflake/ml/modeling/xgboost/xgbrf_regressor.py +108 -136
- snowflake/ml/registry/model_registry.py +2 -0
- snowflake/ml/registry/registry.py +215 -0
- snowflake/ml/version.py +1 -1
- {snowflake_ml_python-1.1.0.dist-info → snowflake_ml_python-1.1.2.dist-info}/METADATA +34 -1
- snowflake_ml_python-1.1.2.dist-info/RECORD +347 -0
- snowflake_ml_python-1.1.0.dist-info/RECORD +0 -331
- {snowflake_ml_python-1.1.0.dist-info → snowflake_ml_python-1.1.2.dist-info}/WHEEL +0 -0
@@ -0,0 +1,331 @@
|
|
1
|
+
import importlib
|
2
|
+
import inspect
|
3
|
+
import os
|
4
|
+
import posixpath
|
5
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple
|
6
|
+
|
7
|
+
import cloudpickle as cp
|
8
|
+
|
9
|
+
from snowflake.ml._internal import telemetry
|
10
|
+
from snowflake.ml._internal.exceptions import (
|
11
|
+
error_codes,
|
12
|
+
exceptions,
|
13
|
+
modeling_error_messages,
|
14
|
+
)
|
15
|
+
from snowflake.ml._internal.utils import identifier, snowpark_dataframe_utils
|
16
|
+
from snowflake.ml._internal.utils.query_result_checker import SqlResultValidator
|
17
|
+
from snowflake.ml._internal.utils.temp_file_utils import (
|
18
|
+
cleanup_temp_files,
|
19
|
+
get_temp_file_path,
|
20
|
+
)
|
21
|
+
from snowflake.ml.modeling._internal.model_specifications import (
|
22
|
+
ModelSpecifications,
|
23
|
+
ModelSpecificationsBuilder,
|
24
|
+
)
|
25
|
+
from snowflake.snowpark import DataFrame, Session, exceptions as snowpark_exceptions
|
26
|
+
from snowflake.snowpark._internal.utils import (
|
27
|
+
TempObjectType,
|
28
|
+
random_name_for_temp_object,
|
29
|
+
)
|
30
|
+
from snowflake.snowpark.functions import sproc
|
31
|
+
from snowflake.snowpark.stored_procedure import StoredProcedure
|
32
|
+
|
33
|
+
cp.register_pickle_by_value(inspect.getmodule(get_temp_file_path))
|
34
|
+
cp.register_pickle_by_value(inspect.getmodule(identifier.get_inferred_name))
|
35
|
+
|
36
|
+
_PROJECT = "ModelDevelopment"
|
37
|
+
|
38
|
+
|
39
|
+
class SnowparkModelTrainer:
|
40
|
+
"""
|
41
|
+
A class for training models on Snowflake data using the Sproc.
|
42
|
+
|
43
|
+
TODO (snandamuri): Introduce the concept of executor that would take the training function
|
44
|
+
and execute it on the target environments like, local, Snowflake warehouse, or SPCS, etc.
|
45
|
+
"""
|
46
|
+
|
47
|
+
def __init__(
|
48
|
+
self,
|
49
|
+
estimator: object,
|
50
|
+
dataset: DataFrame,
|
51
|
+
session: Session,
|
52
|
+
input_cols: List[str],
|
53
|
+
label_cols: Optional[List[str]],
|
54
|
+
sample_weight_col: Optional[str],
|
55
|
+
autogenerated: bool = False,
|
56
|
+
subproject: str = "",
|
57
|
+
) -> None:
|
58
|
+
"""
|
59
|
+
Initializes the SnowparkModelTrainer with a model, a Snowpark DataFrame, feature, and label column names.
|
60
|
+
|
61
|
+
Args:
|
62
|
+
estimator: SKLearn compatible estimator or transformer object.
|
63
|
+
dataset: The dataset used for training the model.
|
64
|
+
session: Snowflake session object to be used for training.
|
65
|
+
input_cols: The name(s) of one or more columns in a DataFrame containing a feature to be used for training.
|
66
|
+
label_cols: The name(s) of one or more columns in a DataFrame representing the target variable(s) to learn.
|
67
|
+
sample_weight_col: The column name representing the weight of training examples.
|
68
|
+
autogenerated: A boolean denoting if the trainer is being used by autogenerated code or not.
|
69
|
+
subproject: subproject name to be used in telemetry.
|
70
|
+
"""
|
71
|
+
self.estimator = estimator
|
72
|
+
self.dataset = dataset
|
73
|
+
self.session = session
|
74
|
+
self.input_cols = input_cols
|
75
|
+
self.label_cols = label_cols
|
76
|
+
self.sample_weight_col = sample_weight_col
|
77
|
+
self._autogenerated = autogenerated
|
78
|
+
self._subproject = subproject
|
79
|
+
self._class_name = estimator.__class__.__name__
|
80
|
+
|
81
|
+
def _create_temp_stage(self) -> str:
|
82
|
+
"""
|
83
|
+
Creates temporary stage.
|
84
|
+
|
85
|
+
Returns:
|
86
|
+
Temp stage name.
|
87
|
+
"""
|
88
|
+
# Create temp stage to upload pickled model file.
|
89
|
+
transform_stage_name = random_name_for_temp_object(TempObjectType.STAGE)
|
90
|
+
stage_creation_query = f"CREATE OR REPLACE TEMPORARY STAGE {transform_stage_name};"
|
91
|
+
SqlResultValidator(session=self.session, query=stage_creation_query).has_dimensions(
|
92
|
+
expected_rows=1, expected_cols=1
|
93
|
+
).validate()
|
94
|
+
return transform_stage_name
|
95
|
+
|
96
|
+
def _upload_model_to_stage(self, stage_name: str) -> Tuple[str, str]:
|
97
|
+
"""
|
98
|
+
Util method to pickle and upload the model to a temp Snowflake stage.
|
99
|
+
|
100
|
+
Args:
|
101
|
+
stage_name: Stage name to save model.
|
102
|
+
|
103
|
+
Returns:
|
104
|
+
a tuple containing stage file paths for pickled input model for training and location to store trained
|
105
|
+
models(response from training sproc).
|
106
|
+
"""
|
107
|
+
# Create a temp file and dump the transform to that file.
|
108
|
+
local_transform_file_name = get_temp_file_path()
|
109
|
+
with open(local_transform_file_name, mode="w+b") as local_transform_file:
|
110
|
+
cp.dump(self.estimator, local_transform_file)
|
111
|
+
|
112
|
+
# Use posixpath to construct stage paths
|
113
|
+
stage_transform_file_name = posixpath.join(stage_name, os.path.basename(local_transform_file_name))
|
114
|
+
stage_result_file_name = posixpath.join(stage_name, os.path.basename(local_transform_file_name))
|
115
|
+
|
116
|
+
statement_params = telemetry.get_function_usage_statement_params(
|
117
|
+
project=_PROJECT,
|
118
|
+
subproject=self._subproject,
|
119
|
+
function_name=telemetry.get_statement_params_full_func_name(inspect.currentframe(), self._class_name),
|
120
|
+
api_calls=[sproc],
|
121
|
+
custom_tags=dict([("autogen", True)]) if self._autogenerated else None,
|
122
|
+
)
|
123
|
+
# Put locally serialized transform on stage.
|
124
|
+
self.session.file.put(
|
125
|
+
local_transform_file_name,
|
126
|
+
stage_transform_file_name,
|
127
|
+
auto_compress=False,
|
128
|
+
overwrite=True,
|
129
|
+
statement_params=statement_params,
|
130
|
+
)
|
131
|
+
|
132
|
+
cleanup_temp_files([local_transform_file_name])
|
133
|
+
return (stage_transform_file_name, stage_result_file_name)
|
134
|
+
|
135
|
+
def _fetch_model_from_stage(self, dir_path: str, file_name: str, statement_params: Dict[str, str]) -> object:
|
136
|
+
"""
|
137
|
+
Downloads the serialized model from a stage location and unpickels it.
|
138
|
+
|
139
|
+
Args:
|
140
|
+
dir_path: Stage directory path where results are stored.
|
141
|
+
file_name: File name with in the directory where results are stored.
|
142
|
+
statement_params: Statement params to be attached to the SQL queries issue form this method.
|
143
|
+
|
144
|
+
Returns:
|
145
|
+
Deserialized model object.
|
146
|
+
"""
|
147
|
+
local_result_file_name = get_temp_file_path()
|
148
|
+
self.session.file.get(
|
149
|
+
posixpath.join(dir_path, file_name),
|
150
|
+
local_result_file_name,
|
151
|
+
statement_params=statement_params,
|
152
|
+
)
|
153
|
+
|
154
|
+
with open(os.path.join(local_result_file_name, file_name), mode="r+b") as result_file_obj:
|
155
|
+
fit_estimator = cp.load(result_file_obj)
|
156
|
+
|
157
|
+
cleanup_temp_files([local_result_file_name])
|
158
|
+
return fit_estimator
|
159
|
+
|
160
|
+
def _build_fit_wrapper_sproc(
|
161
|
+
self,
|
162
|
+
model_spec: ModelSpecifications,
|
163
|
+
) -> Callable[[Any, List[str], str, str, List[str], List[str], Optional[str], Dict[str, str]], str]:
|
164
|
+
"""
|
165
|
+
Constructs and returns a python stored procedure function to be used for training model.
|
166
|
+
|
167
|
+
Args:
|
168
|
+
model_spec: ModelSpecifications object that contains model specific information
|
169
|
+
like required imports, package dependencies, etc.
|
170
|
+
|
171
|
+
Returns:
|
172
|
+
A callable that can be registered as a stored procedure.
|
173
|
+
"""
|
174
|
+
imports = model_spec.imports # In order for the sproc to not resolve this reference in snowflake.ml
|
175
|
+
|
176
|
+
def fit_wrapper_function(
|
177
|
+
session: Session,
|
178
|
+
sql_queries: List[str],
|
179
|
+
stage_transform_file_name: str,
|
180
|
+
stage_result_file_name: str,
|
181
|
+
input_cols: List[str],
|
182
|
+
label_cols: List[str],
|
183
|
+
sample_weight_col: Optional[str],
|
184
|
+
statement_params: Dict[str, str],
|
185
|
+
) -> str:
|
186
|
+
import inspect
|
187
|
+
import os
|
188
|
+
|
189
|
+
import cloudpickle as cp
|
190
|
+
import pandas as pd
|
191
|
+
|
192
|
+
for import_name in imports:
|
193
|
+
importlib.import_module(import_name)
|
194
|
+
|
195
|
+
# Execute snowpark queries and obtain the results as pandas dataframe
|
196
|
+
# NB: this implies that the result data must fit into memory.
|
197
|
+
for query in sql_queries[:-1]:
|
198
|
+
_ = session.sql(query).collect(statement_params=statement_params)
|
199
|
+
sp_df = session.sql(sql_queries[-1])
|
200
|
+
df: pd.DataFrame = sp_df.to_pandas(statement_params=statement_params)
|
201
|
+
df.columns = sp_df.columns
|
202
|
+
|
203
|
+
local_transform_file_name = get_temp_file_path()
|
204
|
+
|
205
|
+
session.file.get(stage_transform_file_name, local_transform_file_name, statement_params=statement_params)
|
206
|
+
|
207
|
+
local_transform_file_path = os.path.join(
|
208
|
+
local_transform_file_name, os.listdir(local_transform_file_name)[0]
|
209
|
+
)
|
210
|
+
with open(local_transform_file_path, mode="r+b") as local_transform_file_obj:
|
211
|
+
estimator = cp.load(local_transform_file_obj)
|
212
|
+
|
213
|
+
argspec = inspect.getfullargspec(estimator.fit)
|
214
|
+
args = {"X": df[input_cols]}
|
215
|
+
if label_cols:
|
216
|
+
label_arg_name = "Y" if "Y" in argspec.args else "y"
|
217
|
+
args[label_arg_name] = df[label_cols].squeeze()
|
218
|
+
|
219
|
+
if sample_weight_col is not None and "sample_weight" in argspec.args:
|
220
|
+
args["sample_weight"] = df[sample_weight_col].squeeze()
|
221
|
+
|
222
|
+
estimator.fit(**args)
|
223
|
+
|
224
|
+
local_result_file_name = get_temp_file_path()
|
225
|
+
|
226
|
+
with open(local_result_file_name, mode="w+b") as local_result_file_obj:
|
227
|
+
cp.dump(estimator, local_result_file_obj)
|
228
|
+
|
229
|
+
session.file.put(
|
230
|
+
local_result_file_name,
|
231
|
+
stage_result_file_name,
|
232
|
+
auto_compress=False,
|
233
|
+
overwrite=True,
|
234
|
+
statement_params=statement_params,
|
235
|
+
)
|
236
|
+
|
237
|
+
# Note: you can add something like + "|" + str(df) to the return string
|
238
|
+
# to pass debug information to the caller.
|
239
|
+
return str(os.path.basename(local_result_file_name))
|
240
|
+
|
241
|
+
return fit_wrapper_function
|
242
|
+
|
243
|
+
def _get_fit_wrapper_sproc(self, statement_params: Dict[str, str]) -> StoredProcedure:
|
244
|
+
# If the sproc already exists, don't register.
|
245
|
+
if not hasattr(self.session, "_FIT_WRAPPER_SPROCS"):
|
246
|
+
self.session._FIT_WRAPPER_SPROCS: Dict[str, StoredProcedure] = {} # type: ignore[attr-defined, misc]
|
247
|
+
|
248
|
+
model_spec = ModelSpecificationsBuilder.build(model=self.estimator)
|
249
|
+
fit_sproc_key = model_spec.__class__.__name__
|
250
|
+
if fit_sproc_key in self.session._FIT_WRAPPER_SPROCS: # type: ignore[attr-defined]
|
251
|
+
fit_sproc: StoredProcedure = self.session._FIT_WRAPPER_SPROCS[fit_sproc_key] # type: ignore[attr-defined]
|
252
|
+
return fit_sproc
|
253
|
+
|
254
|
+
fit_sproc_name = random_name_for_temp_object(TempObjectType.PROCEDURE)
|
255
|
+
|
256
|
+
fit_wrapper_sproc = self.session.sproc.register(
|
257
|
+
func=self._build_fit_wrapper_sproc(model_spec=model_spec),
|
258
|
+
is_permanent=False,
|
259
|
+
name=fit_sproc_name,
|
260
|
+
packages=["snowflake-snowpark-python"] + model_spec.pkgDependencies, # type: ignore[arg-type]
|
261
|
+
replace=True,
|
262
|
+
session=self.session,
|
263
|
+
statement_params=statement_params,
|
264
|
+
)
|
265
|
+
|
266
|
+
self.session._FIT_WRAPPER_SPROCS[fit_sproc_key] = fit_wrapper_sproc # type: ignore[attr-defined]
|
267
|
+
|
268
|
+
return fit_wrapper_sproc
|
269
|
+
|
270
|
+
def train(self) -> object:
|
271
|
+
"""
|
272
|
+
Trains the model by pushing down the compute into Snowflake using stored procedures.
|
273
|
+
|
274
|
+
Returns:
|
275
|
+
Trained model
|
276
|
+
|
277
|
+
Raises:
|
278
|
+
e: Raises an exception if any of Snowflake operations fail because of any reason.
|
279
|
+
SnowflakeMLException: Know exception are caught and rethrow with more detailed error message.
|
280
|
+
"""
|
281
|
+
dataset = snowpark_dataframe_utils.cast_snowpark_dataframe_column_types(self.dataset)
|
282
|
+
|
283
|
+
# TODO(snandamuri) : Handle the already in a stored procedure case in the in builder.
|
284
|
+
|
285
|
+
# Extract query that generated the dataframe. We will need to pass it to the fit procedure.
|
286
|
+
queries = dataset.queries["queries"]
|
287
|
+
|
288
|
+
transform_stage_name = self._create_temp_stage()
|
289
|
+
(stage_transform_file_name, stage_result_file_name) = self._upload_model_to_stage(
|
290
|
+
stage_name=transform_stage_name
|
291
|
+
)
|
292
|
+
|
293
|
+
# Call fit sproc
|
294
|
+
statement_params = telemetry.get_function_usage_statement_params(
|
295
|
+
project=_PROJECT,
|
296
|
+
subproject=self._subproject,
|
297
|
+
function_name=telemetry.get_statement_params_full_func_name(inspect.currentframe(), self._class_name),
|
298
|
+
api_calls=[Session.call],
|
299
|
+
custom_tags=dict([("autogen", True)]) if self._autogenerated else None,
|
300
|
+
)
|
301
|
+
|
302
|
+
fit_wrapper_sproc = self._get_fit_wrapper_sproc(statement_params=statement_params)
|
303
|
+
|
304
|
+
try:
|
305
|
+
sproc_export_file_name: str = fit_wrapper_sproc(
|
306
|
+
self.session,
|
307
|
+
queries,
|
308
|
+
stage_transform_file_name,
|
309
|
+
stage_result_file_name,
|
310
|
+
self.input_cols,
|
311
|
+
self.label_cols,
|
312
|
+
self.sample_weight_col,
|
313
|
+
statement_params,
|
314
|
+
)
|
315
|
+
except snowpark_exceptions.SnowparkClientException as e:
|
316
|
+
if "fit() missing 1 required positional argument: 'y'" in str(e):
|
317
|
+
raise exceptions.SnowflakeMLException(
|
318
|
+
error_code=error_codes.NOT_FOUND,
|
319
|
+
original_exception=RuntimeError(modeling_error_messages.ATTRIBUTE_NOT_SET.format("label_cols")),
|
320
|
+
) from e
|
321
|
+
raise e
|
322
|
+
|
323
|
+
if "|" in sproc_export_file_name:
|
324
|
+
fields = sproc_export_file_name.strip().split("|")
|
325
|
+
sproc_export_file_name = fields[0]
|
326
|
+
|
327
|
+
return self._fetch_model_from_stage(
|
328
|
+
dir_path=stage_result_file_name,
|
329
|
+
file_name=sproc_export_file_name,
|
330
|
+
statement_params=statement_params,
|
331
|
+
)
|