spark-connect 0.4.0 → 0.5.0
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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +39 -1
- data/README.md +5 -3
- data/lib/spark_connect/arrow.rb +5 -1
- data/lib/spark_connect/client.rb +3 -1
- data/lib/spark_connect/data_frame.rb +2 -1
- data/lib/spark_connect/ml/base.rb +433 -0
- data/lib/spark_connect/ml/classification.rb +444 -0
- data/lib/spark_connect/ml/clustering.rb +296 -0
- data/lib/spark_connect/ml/evaluation.rb +120 -0
- data/lib/spark_connect/ml/feature.rb +563 -0
- data/lib/spark_connect/ml/feature_transformers.rb +200 -0
- data/lib/spark_connect/ml/fpm.rb +58 -0
- data/lib/spark_connect/ml/functions.rb +47 -0
- data/lib/spark_connect/ml/linalg.rb +336 -0
- data/lib/spark_connect/ml/one_vs_rest.rb +157 -0
- data/lib/spark_connect/ml/params.rb +378 -0
- data/lib/spark_connect/ml/persistence.rb +247 -0
- data/lib/spark_connect/ml/pipeline.rb +115 -0
- data/lib/spark_connect/ml/recommendation.rb +56 -0
- data/lib/spark_connect/ml/regression.rb +289 -0
- data/lib/spark_connect/ml/rpc.rb +244 -0
- data/lib/spark_connect/ml/serialize.rb +211 -0
- data/lib/spark_connect/ml/stat.rb +127 -0
- data/lib/spark_connect/ml/tuning.rb +501 -0
- data/lib/spark_connect/ml.rb +62 -0
- data/lib/spark_connect/version.rb +1 -1
- data/lib/spark_connect.rb +1 -0
- metadata +22 -2
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module SparkConnect
|
|
4
|
+
module ML
|
|
5
|
+
# Regression operators (`org.apache.spark.ml.regression`). The shared predictor bases
|
|
6
|
+
# ({Predictor}, {PredictionModel}) and the tree mixins live in classification.rb, which loads first.
|
|
7
|
+
module Regression
|
|
8
|
+
# Summary of a linear regression evaluation.
|
|
9
|
+
class LinearRegressionSummary < Summary
|
|
10
|
+
attribute :predictions, :dataframe
|
|
11
|
+
attribute :prediction_col, :string, spark_name: "predictionCol"
|
|
12
|
+
attribute :label_col, :string, spark_name: "labelCol"
|
|
13
|
+
attribute :features_col, :string, spark_name: "featuresCol"
|
|
14
|
+
attribute :explained_variance, :double, spark_name: "explainedVariance"
|
|
15
|
+
attribute :mean_absolute_error, :double, spark_name: "meanAbsoluteError"
|
|
16
|
+
attribute :mean_squared_error, :double, spark_name: "meanSquaredError"
|
|
17
|
+
attribute :root_mean_squared_error, :double, spark_name: "rootMeanSquaredError"
|
|
18
|
+
attribute :r2, :double
|
|
19
|
+
attribute :r2adj, :double
|
|
20
|
+
attribute :residuals, :dataframe
|
|
21
|
+
attribute :num_instances, :long, spark_name: "numInstances"
|
|
22
|
+
attribute :degrees_of_freedom, :long, spark_name: "degreesOfFreedom"
|
|
23
|
+
attribute :deviance_residuals, :double_array, spark_name: "devianceResiduals"
|
|
24
|
+
attribute :coefficient_standard_errors, :double_array, spark_name: "coefficientStandardErrors"
|
|
25
|
+
attribute :t_values, :double_array, spark_name: "tValues"
|
|
26
|
+
attribute :p_values, :double_array, spark_name: "pValues"
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Summary of a linear regression training run.
|
|
30
|
+
class LinearRegressionTrainingSummary < LinearRegressionSummary
|
|
31
|
+
include TrainingSummaryMembers
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# Summary of a generalized linear regression evaluation.
|
|
35
|
+
class GeneralizedLinearRegressionSummary < Summary
|
|
36
|
+
attribute :aic, :double
|
|
37
|
+
attribute :degrees_of_freedom, :long, spark_name: "degreesOfFreedom"
|
|
38
|
+
attribute :deviance, :double
|
|
39
|
+
attribute :dispersion, :double
|
|
40
|
+
attribute :null_deviance, :double, spark_name: "nullDeviance"
|
|
41
|
+
attribute :num_instances, :long, spark_name: "numInstances"
|
|
42
|
+
attribute :prediction_col, :string, spark_name: "predictionCol"
|
|
43
|
+
attribute :predictions, :dataframe
|
|
44
|
+
attribute :rank, :long
|
|
45
|
+
attribute :residual_degree_of_freedom, :long, spark_name: "residualDegreeOfFreedom"
|
|
46
|
+
attribute :residual_degree_of_freedom_null, :long, spark_name: "residualDegreeOfFreedomNull"
|
|
47
|
+
attribute :residuals, :dataframe
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Summary of a generalized linear regression training run.
|
|
51
|
+
class GeneralizedLinearRegressionTrainingSummary < GeneralizedLinearRegressionSummary
|
|
52
|
+
attribute :num_iterations, :int, spark_name: "numIterations"
|
|
53
|
+
attribute :solver, :string
|
|
54
|
+
attribute :t_values, :double_array, spark_name: "tValues"
|
|
55
|
+
attribute :p_values, :double_array, spark_name: "pValues"
|
|
56
|
+
attribute :coefficient_standard_errors, :double_array, spark_name: "coefficientStandardErrors"
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# Accelerated failure time (survival) regression.
|
|
60
|
+
class AFTSurvivalRegression < Predictor
|
|
61
|
+
operator "org.apache.spark.ml.regression.AFTSurvivalRegression"
|
|
62
|
+
model -> { AFTSurvivalRegressionModel }
|
|
63
|
+
|
|
64
|
+
param :fit_intercept, :boolean, default: true, doc: "whether to fit an intercept term"
|
|
65
|
+
param :max_iter, :int, default: 100, doc: "max number of iterations (>= 0)"
|
|
66
|
+
param :tol, :double, default: 1e-6, doc: "convergence tolerance for iterative algorithms (>= 0)"
|
|
67
|
+
param :censor_col, :string, default: "censor", doc: "censor column name; the value 1 means the event occurred"
|
|
68
|
+
param :quantile_probabilities, :double_array, default: [0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99],
|
|
69
|
+
doc: "quantile probabilities of the predicted quantiles, in (0, 1)"
|
|
70
|
+
param :quantiles_col, :string, doc: "quantiles column name; unset disables the column"
|
|
71
|
+
param :aggregation_depth, :int, default: 2, doc: "suggested depth for treeAggregate (>= 2)"
|
|
72
|
+
param :max_block_size_in_mb, :double, default: 0.0, spark_name: "maxBlockSizeInMB",
|
|
73
|
+
doc: "maximum memory in MB for stacking input data into blocks"
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
# A fitted {AFTSurvivalRegression}.
|
|
77
|
+
class AFTSurvivalRegressionModel < PredictionModel
|
|
78
|
+
operator "org.apache.spark.ml.regression.AFTSurvivalRegressionModel"
|
|
79
|
+
|
|
80
|
+
param :quantile_probabilities, :double_array, default: [0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99],
|
|
81
|
+
doc: "quantile probabilities of the predicted quantiles, in (0, 1)"
|
|
82
|
+
param :quantiles_col, :string, doc: "quantiles column name; unset disables the column"
|
|
83
|
+
|
|
84
|
+
attribute :intercept, :double
|
|
85
|
+
attribute :coefficients, :vector
|
|
86
|
+
attribute :scale, :double
|
|
87
|
+
method_call :predict_quantiles, arg_count: 1, returns: :vector, spark_name: "predictQuantiles"
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# Isotonic (monotonic) regression.
|
|
91
|
+
class IsotonicRegression < Estimator
|
|
92
|
+
operator "org.apache.spark.ml.regression.IsotonicRegression"
|
|
93
|
+
model -> { IsotonicRegressionModel }
|
|
94
|
+
|
|
95
|
+
param :features_col, :string, default: "features", doc: "features column name"
|
|
96
|
+
param :label_col, :string, default: "label", doc: "label column name"
|
|
97
|
+
param :prediction_col, :string, default: "prediction", doc: "prediction column name"
|
|
98
|
+
param :weight_col, :string, doc: "weight column name; unset means every instance has weight 1.0"
|
|
99
|
+
param :isotonic, :boolean, default: true, doc: "whether the output sequence should be isotonic (increasing) or antitonic"
|
|
100
|
+
param :feature_index, :int, default: 0, doc: "index of the feature if the features column is a vector"
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# A fitted {IsotonicRegression}.
|
|
104
|
+
class IsotonicRegressionModel < Model
|
|
105
|
+
operator "org.apache.spark.ml.regression.IsotonicRegressionModel"
|
|
106
|
+
|
|
107
|
+
param :features_col, :string, default: "features", doc: "features column name"
|
|
108
|
+
param :label_col, :string, default: "label", doc: "label column name"
|
|
109
|
+
param :prediction_col, :string, default: "prediction", doc: "prediction column name"
|
|
110
|
+
param :isotonic, :boolean, default: true, doc: "whether the output sequence should be isotonic (increasing) or antitonic"
|
|
111
|
+
param :feature_index, :int, default: 0, doc: "index of the feature if the features column is a vector"
|
|
112
|
+
|
|
113
|
+
attribute :boundaries, :vector
|
|
114
|
+
attribute :predictions, :vector
|
|
115
|
+
attribute :num_features, :int, spark_name: "numFeatures"
|
|
116
|
+
method_call :predict, arg_count: 1, returns: :double
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
# Linear regression with elastic net, ridge, lasso or no regularization.
|
|
120
|
+
class LinearRegression < Predictor
|
|
121
|
+
operator "org.apache.spark.ml.regression.LinearRegression"
|
|
122
|
+
model -> { LinearRegressionModel }
|
|
123
|
+
|
|
124
|
+
param :reg_param, :double, default: 0.0, doc: "regularization parameter (>= 0)"
|
|
125
|
+
param :elastic_net_param, :double, default: 0.0, spark_name: "elasticNetParam",
|
|
126
|
+
doc: "the ElasticNet mixing parameter, in [0, 1]"
|
|
127
|
+
param :max_iter, :int, default: 100, doc: "max number of iterations (>= 0)"
|
|
128
|
+
param :tol, :double, default: 1e-6, doc: "convergence tolerance for iterative algorithms (>= 0)"
|
|
129
|
+
param :fit_intercept, :boolean, default: true, doc: "whether to fit an intercept term"
|
|
130
|
+
param :standardization, :boolean, default: true, doc: "whether to standardize the training features"
|
|
131
|
+
param :solver, :string, default: "auto", doc: "the solver algorithm: auto, normal or l-bfgs"
|
|
132
|
+
param :weight_col, :string, doc: "weight column name; unset means every instance has weight 1.0"
|
|
133
|
+
param :aggregation_depth, :int, default: 2, doc: "suggested depth for treeAggregate (>= 2)"
|
|
134
|
+
param :loss, :string, default: "squaredError", doc: "the loss function: squaredError or huber"
|
|
135
|
+
param :epsilon, :double, default: 1.35, doc: "the shape parameter of the huber loss, controlling outliers"
|
|
136
|
+
param :max_block_size_in_mb, :double, default: 0.0, spark_name: "maxBlockSizeInMB",
|
|
137
|
+
doc: "maximum memory in MB for stacking input data into blocks"
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
# A fitted {LinearRegression}.
|
|
141
|
+
class LinearRegressionModel < PredictionModel
|
|
142
|
+
operator "org.apache.spark.ml.regression.LinearRegressionModel"
|
|
143
|
+
summary_class -> { LinearRegressionTrainingSummary }
|
|
144
|
+
|
|
145
|
+
attribute :intercept, :double
|
|
146
|
+
attribute :coefficients, :vector
|
|
147
|
+
attribute :scale, :double
|
|
148
|
+
method_call :evaluate, arg_count: 1, returns: LinearRegressionSummary
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
# Generalized linear regression (Gaussian, binomial, poisson, gamma or tweedie families).
|
|
152
|
+
class GeneralizedLinearRegression < Predictor
|
|
153
|
+
operator "org.apache.spark.ml.regression.GeneralizedLinearRegression"
|
|
154
|
+
model -> { GeneralizedLinearRegressionModel }
|
|
155
|
+
|
|
156
|
+
param :family, :string, default: "gaussian", doc: "the error distribution family"
|
|
157
|
+
param :link, :string, doc: "the link function; unset uses the canonical link of the family"
|
|
158
|
+
param :fit_intercept, :boolean, default: true, doc: "whether to fit an intercept term"
|
|
159
|
+
param :max_iter, :int, default: 25, doc: "max number of iterations (>= 0)"
|
|
160
|
+
param :tol, :double, default: 1e-6, doc: "convergence tolerance for iterative algorithms (>= 0)"
|
|
161
|
+
param :reg_param, :double, default: 0.0, doc: "regularization parameter (>= 0)"
|
|
162
|
+
param :weight_col, :string, doc: "weight column name; unset means every instance has weight 1.0"
|
|
163
|
+
param :solver, :string, default: "irls", doc: "the solver algorithm: irls"
|
|
164
|
+
param :link_prediction_col, :string, doc: "link prediction (linear predictor) column name"
|
|
165
|
+
param :variance_power, :double, default: 0.0, doc: "the power in the variance function of the tweedie family"
|
|
166
|
+
param :link_power, :double, doc: "the index in the power link function of the tweedie family"
|
|
167
|
+
param :offset_col, :string, doc: "the offset column name; unset means no offset"
|
|
168
|
+
param :aggregation_depth, :int, default: 2, doc: "suggested depth for treeAggregate (>= 2)"
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
# A fitted {GeneralizedLinearRegression}.
|
|
172
|
+
class GeneralizedLinearRegressionModel < PredictionModel
|
|
173
|
+
operator "org.apache.spark.ml.regression.GeneralizedLinearRegressionModel"
|
|
174
|
+
summary_class -> { GeneralizedLinearRegressionTrainingSummary }
|
|
175
|
+
|
|
176
|
+
param :family, :string, default: "gaussian", doc: "the error distribution family"
|
|
177
|
+
param :link, :string, doc: "the link function; unset uses the canonical link of the family"
|
|
178
|
+
param :link_prediction_col, :string, doc: "link prediction (linear predictor) column name"
|
|
179
|
+
param :variance_power, :double, default: 0.0, doc: "the power in the variance function of the tweedie family"
|
|
180
|
+
param :link_power, :double, doc: "the index in the power link function of the tweedie family"
|
|
181
|
+
param :offset_col, :string, doc: "the offset column name; unset means no offset"
|
|
182
|
+
|
|
183
|
+
attribute :intercept, :double
|
|
184
|
+
attribute :coefficients, :vector
|
|
185
|
+
method_call :evaluate, arg_count: 1, returns: GeneralizedLinearRegressionSummary
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
# Factorization machines regressor.
|
|
189
|
+
class FMRegressor < Predictor
|
|
190
|
+
operator "org.apache.spark.ml.regression.FMRegressor"
|
|
191
|
+
model -> { FMRegressionModel }
|
|
192
|
+
|
|
193
|
+
param :factor_size, :int, default: 8, doc: "dimensionality of the factors (> 0)"
|
|
194
|
+
param :fit_intercept, :boolean, default: true, doc: "whether to fit an intercept term"
|
|
195
|
+
param :fit_linear, :boolean, default: true, doc: "whether to fit the linear term (1-way interactions)"
|
|
196
|
+
param :reg_param, :double, default: 0.0, doc: "regularization parameter (>= 0)"
|
|
197
|
+
param :mini_batch_fraction, :double, default: 1.0, doc: "fraction of the input data used for each mini-batch, in (0, 1]"
|
|
198
|
+
param :init_std, :double, default: 0.01, doc: "standard deviation of the initial coefficients"
|
|
199
|
+
param :max_iter, :int, default: 100, doc: "max number of iterations (>= 0)"
|
|
200
|
+
param :step_size, :double, default: 1.0, doc: "step size for each iteration (> 0)"
|
|
201
|
+
param :tol, :double, default: 1e-6, doc: "convergence tolerance for iterative algorithms (>= 0)"
|
|
202
|
+
param :solver, :string, default: "adamW", doc: "the optimization solver: adamW or gd"
|
|
203
|
+
param :seed, :long, default: SEED_DEFAULT, doc: "random seed; unset uses a class-derived default on the server"
|
|
204
|
+
param :weight_col, :string, doc: "weight column name; unset means every instance has weight 1.0"
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
# A fitted {FMRegressor}.
|
|
208
|
+
class FMRegressionModel < PredictionModel
|
|
209
|
+
operator "org.apache.spark.ml.regression.FMRegressionModel"
|
|
210
|
+
|
|
211
|
+
attribute :intercept, :double
|
|
212
|
+
attribute :linear, :vector
|
|
213
|
+
attribute :factors, :matrix
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
# Decision tree regressor.
|
|
217
|
+
class DecisionTreeRegressor < Predictor
|
|
218
|
+
include DecisionTreeParams
|
|
219
|
+
|
|
220
|
+
operator "org.apache.spark.ml.regression.DecisionTreeRegressor"
|
|
221
|
+
model -> { DecisionTreeRegressionModel }
|
|
222
|
+
|
|
223
|
+
param :impurity, :string, default: "variance", doc: "criterion used for information gain calculation (variance)"
|
|
224
|
+
param :variance_col, :string, doc: "column name for the biased sample variance of the prediction"
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
# A fitted {DecisionTreeRegressor}.
|
|
228
|
+
class DecisionTreeRegressionModel < PredictionModel
|
|
229
|
+
include DecisionTreeModelMembers
|
|
230
|
+
|
|
231
|
+
operator "org.apache.spark.ml.regression.DecisionTreeRegressionModel"
|
|
232
|
+
|
|
233
|
+
param :leaf_col, :string, default: "", doc: "leaf indices column name; empty disables the column"
|
|
234
|
+
param :variance_col, :string, doc: "column name for the biased sample variance of the prediction"
|
|
235
|
+
end
|
|
236
|
+
|
|
237
|
+
# Random forest regressor.
|
|
238
|
+
class RandomForestRegressor < Predictor
|
|
239
|
+
include TreeEnsembleParams
|
|
240
|
+
include DecisionTreeParams
|
|
241
|
+
|
|
242
|
+
operator "org.apache.spark.ml.regression.RandomForestRegressor"
|
|
243
|
+
model -> { RandomForestRegressionModel }
|
|
244
|
+
|
|
245
|
+
param :impurity, :string, default: "variance", doc: "criterion used for information gain calculation (variance)"
|
|
246
|
+
param :num_trees, :int, default: 20, doc: "number of trees to train (>= 1)"
|
|
247
|
+
param :bootstrap, :boolean, default: true, doc: "whether bootstrap samples are used when building trees"
|
|
248
|
+
end
|
|
249
|
+
|
|
250
|
+
# A fitted {RandomForestRegressor}.
|
|
251
|
+
class RandomForestRegressionModel < PredictionModel
|
|
252
|
+
include TreeEnsembleModelMembers
|
|
253
|
+
|
|
254
|
+
operator "org.apache.spark.ml.regression.RandomForestRegressionModel"
|
|
255
|
+
|
|
256
|
+
param :leaf_col, :string, default: "", doc: "leaf indices column name; empty disables the column"
|
|
257
|
+
end
|
|
258
|
+
|
|
259
|
+
# Gradient-boosted trees regressor (squared or absolute loss).
|
|
260
|
+
class GBTRegressor < Predictor
|
|
261
|
+
include TreeEnsembleParams
|
|
262
|
+
include DecisionTreeParams
|
|
263
|
+
|
|
264
|
+
operator "org.apache.spark.ml.regression.GBTRegressor"
|
|
265
|
+
model -> { GBTRegressionModel }
|
|
266
|
+
|
|
267
|
+
param :feature_subset_strategy, :string, default: "all",
|
|
268
|
+
doc: "number of features to consider for splits at each tree node"
|
|
269
|
+
param :impurity, :string, default: "variance", doc: "criterion used for information gain calculation (variance)"
|
|
270
|
+
param :loss_type, :string, default: "squared", doc: "loss function to be optimized: squared or absolute"
|
|
271
|
+
param :max_iter, :int, default: 20, doc: "max number of iterations (>= 0), i.e. the number of trees"
|
|
272
|
+
param :step_size, :double, default: 0.1, doc: "step size (learning rate) for each iteration (> 0)"
|
|
273
|
+
param :validation_tol, :double, default: 0.01, doc: "threshold for stopping early when fit with validation is used"
|
|
274
|
+
param :validation_indicator_col, :string, doc: "name of the column that marks each row as training (false) or validation (true)"
|
|
275
|
+
end
|
|
276
|
+
|
|
277
|
+
# A fitted {GBTRegressor}.
|
|
278
|
+
class GBTRegressionModel < PredictionModel
|
|
279
|
+
include TreeEnsembleModelMembers
|
|
280
|
+
|
|
281
|
+
operator "org.apache.spark.ml.regression.GBTRegressionModel"
|
|
282
|
+
|
|
283
|
+
param :leaf_col, :string, default: "", doc: "leaf indices column name; empty disables the column"
|
|
284
|
+
|
|
285
|
+
method_call :evaluate_each_iteration, arg_count: 2, returns: :double_array
|
|
286
|
+
end
|
|
287
|
+
end
|
|
288
|
+
end
|
|
289
|
+
end
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module SparkConnect
|
|
4
|
+
module ML
|
|
5
|
+
# Raised when the connected server is too old for an ML feature (for example
|
|
6
|
+
# `CleanCache` on Spark 4.0, which predates the ML cache admin commands).
|
|
7
|
+
class UnsupportedServerError < SparkConnect::Error; end
|
|
8
|
+
|
|
9
|
+
# Server-side model cache handle. Every fitted model (and every summary
|
|
10
|
+
# cached by the server) is referenced by an id in the server's ML cache. The
|
|
11
|
+
# handle is reference counted: copies of a model share it, and when the
|
|
12
|
+
# last reference goes away the id is queued for deletion. The queue is
|
|
13
|
+
# drained on the next ML call, or by {Rpc.flush_pending}, so no RPC ever runs
|
|
14
|
+
# from a finalizer.
|
|
15
|
+
class ModelRef
|
|
16
|
+
# @return [String] the server-side object id.
|
|
17
|
+
attr_reader :id
|
|
18
|
+
|
|
19
|
+
# @param id [String]
|
|
20
|
+
# @param session [SparkSession]
|
|
21
|
+
def initialize(id, session)
|
|
22
|
+
@id = id
|
|
23
|
+
@session = session
|
|
24
|
+
@count = 1
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# @return [void]
|
|
28
|
+
def add_ref
|
|
29
|
+
@count += 1
|
|
30
|
+
nil
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# Drop one reference; the id is queued for deletion when none remain.
|
|
34
|
+
# Takes no lock, so it is safe to call from a finalizer (a Mutex cannot
|
|
35
|
+
# be taken there); the GVL keeps the integer update consistent.
|
|
36
|
+
# @return [void]
|
|
37
|
+
def release_ref
|
|
38
|
+
return nil if @count <= 0
|
|
39
|
+
|
|
40
|
+
@count -= 1
|
|
41
|
+
Rpc.enqueue_delete(@session, @id) if @count.zero?
|
|
42
|
+
nil
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# @return [Boolean]
|
|
46
|
+
def released? = @count <= 0
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# Plumbing for ML commands: builds the protos, sends them through the
|
|
50
|
+
# session's client, and decodes the `MlCommandResult`.
|
|
51
|
+
module Rpc
|
|
52
|
+
HELPER_ID = "______ML_CONNECT_HELPER______"
|
|
53
|
+
SUMMARY_LOST = "CONNECT_ML.MODEL_SUMMARY_LOST"
|
|
54
|
+
|
|
55
|
+
# Spark version (as "major.minor.patch") at which each ML feature appeared.
|
|
56
|
+
FEATURES = {
|
|
57
|
+
basic: "4.0.0",
|
|
58
|
+
cache_admin: "4.1.0", # CleanCache, GetCacheInfo, GetModelSize, CreateSummary, Delete.evict_only
|
|
59
|
+
model_summary_dataset: "4.1.0", # MlRelation.model_summary_dataset (restoring offloaded summaries)
|
|
60
|
+
warning_message: "4.1.0",
|
|
61
|
+
}.freeze
|
|
62
|
+
|
|
63
|
+
# How {UnsupportedServerError} names a feature; the others go by their key.
|
|
64
|
+
FEATURE_NAMES = { basic: "Spark ML over Spark Connect" }.freeze
|
|
65
|
+
|
|
66
|
+
PENDING = Queue.new
|
|
67
|
+
|
|
68
|
+
@versions = ObjectSpace::WeakMap.new
|
|
69
|
+
@versions_lock = Mutex.new
|
|
70
|
+
|
|
71
|
+
module_function
|
|
72
|
+
|
|
73
|
+
# @return [String] the server's Spark version, cached per session.
|
|
74
|
+
def server_version(session)
|
|
75
|
+
@versions_lock.synchronize { @versions[session] } || begin
|
|
76
|
+
version = session.version
|
|
77
|
+
@versions_lock.synchronize { @versions[session] = version }
|
|
78
|
+
version
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# @return [Boolean] whether the server supports the named ML feature.
|
|
83
|
+
def supports?(session, feature)
|
|
84
|
+
wanted = FEATURES.fetch(feature).split(".").map(&:to_i)
|
|
85
|
+
have = server_version(session).to_s.split(/[.-]/).first(3).map(&:to_i)
|
|
86
|
+
(have.fill(0, have.size...3) <=> wanted) >= 0
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# Raise {UnsupportedServerError} unless the server supports `feature`.
|
|
90
|
+
# @return [void]
|
|
91
|
+
def require_feature!(session, feature)
|
|
92
|
+
return if supports?(session, feature)
|
|
93
|
+
|
|
94
|
+
raise UnsupportedServerError,
|
|
95
|
+
"#{FEATURE_NAMES.fetch(feature, feature)} needs a Spark Connect server of at least " \
|
|
96
|
+
"#{FEATURES.fetch(feature)}, but the server is #{server_version(session)}"
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# The `MlOperator` proto for an operator instance.
|
|
100
|
+
# @param operator [Params]
|
|
101
|
+
# @param type [Symbol] `:estimator`, `:transformer`, `:model` or `:evaluator`.
|
|
102
|
+
# @return [Proto::MlOperator]
|
|
103
|
+
def operator_proto(operator, type = operator_type(operator))
|
|
104
|
+
Proto::MlOperator.new(name: operator.class.operator, uid: operator.uid, type: OPERATOR_TYPES.fetch(type))
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# @return [Symbol] the operator type of an instance.
|
|
108
|
+
def operator_type(operator)
|
|
109
|
+
case operator
|
|
110
|
+
when Estimator then :estimator
|
|
111
|
+
when Evaluator then :evaluator
|
|
112
|
+
when Model then :model
|
|
113
|
+
else :transformer
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
OPERATOR_TYPES = {
|
|
118
|
+
estimator: :OPERATOR_TYPE_ESTIMATOR,
|
|
119
|
+
transformer: :OPERATOR_TYPE_TRANSFORMER,
|
|
120
|
+
evaluator: :OPERATOR_TYPE_EVALUATOR,
|
|
121
|
+
model: :OPERATOR_TYPE_MODEL,
|
|
122
|
+
}.freeze
|
|
123
|
+
|
|
124
|
+
# Send one `MlCommand` and return its `MlCommandResult`.
|
|
125
|
+
#
|
|
126
|
+
# @param session [SparkSession]
|
|
127
|
+
# @param ml [Proto::MlCommand]
|
|
128
|
+
# @return [Proto::MlCommandResult, nil]
|
|
129
|
+
def run(session, ml)
|
|
130
|
+
# Spark 3.5 servers have no ML commands; fail clearly instead of with the
|
|
131
|
+
# server's error for an unknown command type.
|
|
132
|
+
require_feature!(session, :basic)
|
|
133
|
+
flush_pending(session)
|
|
134
|
+
command = Proto::Command.new(ml_command: ml)
|
|
135
|
+
session.client.execute_command(command).ml_command_result
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
# Ask the server to drop `ids` from its ML cache.
|
|
139
|
+
# @return [void]
|
|
140
|
+
def delete(session, ids)
|
|
141
|
+
return if ids.empty?
|
|
142
|
+
|
|
143
|
+
run(session, Proto::MlCommand.new(delete: Proto::MlCommand::Delete.new(obj_refs: ids.map { |i| Proto::ObjectRef.new(id: i) })))
|
|
144
|
+
nil
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
# Queue an id for deletion (safe to call from a finalizer).
|
|
148
|
+
# @api private
|
|
149
|
+
def enqueue_delete(session, id)
|
|
150
|
+
PENDING << [session, id]
|
|
151
|
+
nil
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
# Delete every model id queued by garbage-collected handles that belong
|
|
155
|
+
# to `session`; the others stay queued.
|
|
156
|
+
# @return [void]
|
|
157
|
+
def flush_pending(session)
|
|
158
|
+
pending = []
|
|
159
|
+
pending << PENDING.pop until PENDING.empty?
|
|
160
|
+
mine, others = pending.partition { |owner, _| owner.equal?(session) }
|
|
161
|
+
others.each { |entry| PENDING << entry }
|
|
162
|
+
mine.map(&:last).each do |id|
|
|
163
|
+
delete(session, [id])
|
|
164
|
+
rescue StandardError
|
|
165
|
+
nil
|
|
166
|
+
end
|
|
167
|
+
nil
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
# @return [Hash] the decoded `operator_info` of a result: `:obj_ref`,
|
|
171
|
+
# `:name`, `:uid`, `:params` (a `{spark_name => value}` hash) and `:warning_message`.
|
|
172
|
+
def operator_info(result)
|
|
173
|
+
info = result.operator_info
|
|
174
|
+
{
|
|
175
|
+
obj_ref: info.obj_ref && !info.obj_ref.id.empty? ? info.obj_ref.id : nil,
|
|
176
|
+
name: info.name,
|
|
177
|
+
uid: info.uid,
|
|
178
|
+
params: info.params ? info.params.params.each_with_object({}) { |(k, v), acc| acc[k] = Serialize.decode(v) } : {},
|
|
179
|
+
warning_message: info.warning_message.empty? ? nil : info.warning_message,
|
|
180
|
+
}
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
# Decode a `MlCommandResult` into a Ruby value: the operator info, the
|
|
184
|
+
# summary id, or the decoded param.
|
|
185
|
+
#
|
|
186
|
+
# @return [Object]
|
|
187
|
+
def decode_result(result)
|
|
188
|
+
case result.result_type
|
|
189
|
+
when :operator_info then operator_info(result)
|
|
190
|
+
when :summary then result.summary
|
|
191
|
+
when :param then Serialize.decode(result.param)
|
|
192
|
+
end
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
# Run a `Fetch` against an object (a model, a summary, or the helper).
|
|
196
|
+
#
|
|
197
|
+
# @param session [SparkSession]
|
|
198
|
+
# @param obj_ref [String] the root object id.
|
|
199
|
+
# @param methods [Array<Proto::Fetch::Method>] the method chain.
|
|
200
|
+
# @return [Object] the decoded result (see {decode_result})
|
|
201
|
+
def fetch(session, obj_ref, methods)
|
|
202
|
+
ml = Proto::MlCommand.new(fetch: Proto::Fetch.new(obj_ref: Proto::ObjectRef.new(id: obj_ref), methods: methods))
|
|
203
|
+
decode_result(run(session, ml))
|
|
204
|
+
end
|
|
205
|
+
|
|
206
|
+
# Ask the server to rebuild an offloaded summary from `dataset`.
|
|
207
|
+
# @return [void]
|
|
208
|
+
def create_summary(session, model_ref, dataset_relation)
|
|
209
|
+
require_feature!(session, :cache_admin)
|
|
210
|
+
ml = Proto::MlCommand.new(create_summary: Proto::MlCommand::CreateSummary.new(
|
|
211
|
+
model_ref: Proto::ObjectRef.new(id: model_ref), dataset: dataset_relation
|
|
212
|
+
))
|
|
213
|
+
run(session, ml)
|
|
214
|
+
nil
|
|
215
|
+
end
|
|
216
|
+
|
|
217
|
+
# Evict every ML object of the session from the server cache.
|
|
218
|
+
# @return [Integer] the number of objects removed (Spark 4.1+).
|
|
219
|
+
def clean_cache(session)
|
|
220
|
+
require_feature!(session, :cache_admin)
|
|
221
|
+
decode_result(run(session, Proto::MlCommand.new(clean_cache: Proto::MlCommand::CleanCache.new)))
|
|
222
|
+
end
|
|
223
|
+
|
|
224
|
+
# @return [Hash] the server's ML cache information (Spark 4.1+).
|
|
225
|
+
def cache_info(session)
|
|
226
|
+
require_feature!(session, :cache_admin)
|
|
227
|
+
decode_result(run(session, Proto::MlCommand.new(get_cache_info: Proto::MlCommand::GetCacheInfo.new)))
|
|
228
|
+
end
|
|
229
|
+
|
|
230
|
+
# Overwrite handling for a write target, the way PySpark's connect writer
|
|
231
|
+
# does it: the server's ML helper deletes `path` first.
|
|
232
|
+
# @return [void]
|
|
233
|
+
def handle_overwrite(session, path, overwrite)
|
|
234
|
+
return unless overwrite
|
|
235
|
+
|
|
236
|
+
fetch(session, HELPER_ID, [Proto::Fetch::Method.new(method: "handleOverwrite", args: [
|
|
237
|
+
Proto::Fetch::Method::Args.new(param: Serialize.literal(path)),
|
|
238
|
+
Proto::Fetch::Method::Args.new(param: Serialize.literal(true)),
|
|
239
|
+
])])
|
|
240
|
+
nil
|
|
241
|
+
end
|
|
242
|
+
end
|
|
243
|
+
end
|
|
244
|
+
end
|