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.
@@ -0,0 +1,247 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module SparkConnect
6
+ module ML
7
+ # Save and load in Spark's standard ML persistence format (the one PySpark's
8
+ # Connect client and Spark Classic both read and write).
9
+ #
10
+ # - Operators and fitted models are written by the server (`MlCommand.Write`)
11
+ # and read back with `MlCommand.Read`, so their directories are exactly what
12
+ # Spark writes.
13
+ # - Pipelines, cross-validators, train-validation splits and one-vs-rest
14
+ # models are orchestrated here, the way PySpark's connect client does it:
15
+ # `metadata` is a one-line JSON document (class, timestamp, sparkVersion,
16
+ # uid, paramMap, defaultParamMap, plus extra keys), written with the
17
+ # DataFrame text writer, and children go into the subdirectories PySpark
18
+ # uses (`stages/<index>_<uid>`, `estimator`, `evaluator`, `bestModel`,
19
+ # `subModels/fold<i>/<j>`, `classifier`, `model_<i>`, `epm_<name><n>`).
20
+ module Persistence
21
+ module_function
22
+
23
+ # ---- operators and models: the server writes and reads them ------------
24
+
25
+ # Write an estimator or transformer (or a composite that writes itself).
26
+ # @return [void]
27
+ def save_operator(operator, path, overwrite:, session:)
28
+ if operator.respond_to?(:save_meta, true)
29
+ operator.send(:save_meta, path, overwrite: overwrite, session: session)
30
+ return nil
31
+ end
32
+
33
+ Rpc.run(session, Proto::MlCommand.new(write: Proto::MlCommand::Write.new(
34
+ operator: Rpc.operator_proto(operator),
35
+ params: Serialize.ml_params(operator.explicit_param_map),
36
+ path: path,
37
+ should_overwrite: overwrite,
38
+ options: {}
39
+ )))
40
+ nil
41
+ end
42
+
43
+ # Write a fitted model through the server's object reference.
44
+ # @return [void]
45
+ def save_model(model, path, overwrite:, session:)
46
+ Rpc.run(session, Proto::MlCommand.new(write: Proto::MlCommand::Write.new(
47
+ obj_ref: Proto::ObjectRef.new(id: model.ref_id),
48
+ params: Serialize.ml_params(model.explicit_param_map),
49
+ path: path,
50
+ should_overwrite: overwrite,
51
+ options: {}
52
+ )))
53
+ nil
54
+ end
55
+
56
+ # Read an estimator, transformer or evaluator class `klass` from `path`.
57
+ # @return [Params]
58
+ def load_operator(klass, path, session:)
59
+ return klass.load_meta(path, session: session) if klass.respond_to?(:load_meta)
60
+
61
+ type = if klass <= Estimator then :estimator
62
+ elsif klass <= Evaluator then :evaluator
63
+ else :transformer
64
+ end
65
+ info = read_info(session, klass.operator, type, path)
66
+ instance = klass.new(uid: info[:uid])
67
+ apply_params(instance, info[:params])
68
+ instance
69
+ end
70
+
71
+ # Read a model class `klass` (a {Model} subclass) from `path`.
72
+ # @return [Model]
73
+ def load_model(klass, path, session:)
74
+ info = read_info(session, klass.operator, :model, path)
75
+ model = klass.new(uid: info[:uid])
76
+ model.attach(session, info[:obj_ref])
77
+ apply_params(model, info[:params])
78
+ model
79
+ end
80
+
81
+ # Load any saved ML instance, choosing the class from the `class` in its metadata.
82
+ # @return [Params]
83
+ def load_any(session, path)
84
+ klass = class_for(read_metadata(session, path).fetch("class"))
85
+ if klass <= Model && !klass.respond_to?(:load_meta)
86
+ load_model(klass, path, session: session)
87
+ else
88
+ load_operator(klass, path, session: session)
89
+ end
90
+ end
91
+
92
+ # @api private
93
+ def read_info(session, operator_name, type, path)
94
+ result = Rpc.run(session, Proto::MlCommand.new(read: Proto::MlCommand::Read.new(
95
+ operator: Proto::MlOperator.new(name: operator_name, type: Rpc::OPERATOR_TYPES.fetch(type)),
96
+ path: path
97
+ )))
98
+ Rpc.operator_info(result)
99
+ end
100
+
101
+ # Set loaded param values (keyed by Spark name) on `instance`. Names the
102
+ # class does not declare (such as `stageUids`) are ignored.
103
+ # @api private
104
+ def apply_params(instance, spark_values)
105
+ spark_values.each do |spark_name, value|
106
+ declared = instance.class.params.values.find { |p| p.spark_name == spark_name }
107
+ instance.set(declared, value) if declared && !value.nil?
108
+ end
109
+ end
110
+
111
+ # ---- the metadata document ----------------------------------------------
112
+
113
+ # Write the `metadata` document of `instance` under `path`, like
114
+ # `DefaultParamsWriter.saveMetadata`.
115
+ #
116
+ # @param session [SparkSession]
117
+ # @param path [String]
118
+ # @param instance [Params]
119
+ # @param param_map [Hash{String => Object}] the `paramMap` section (Spark names).
120
+ # @param extra [Hash] keys added to the document (for example `avgMetrics`).
121
+ # @return [void]
122
+ def write_metadata(session, path, instance, param_map:, extra: {}, exclude: [])
123
+ document = {
124
+ "class" => scala_class_name(instance.class),
125
+ "timestamp" => (Time.now.to_f * 1000).round,
126
+ "sparkVersion" => Rpc.server_version(session).to_s,
127
+ "uid" => instance.uid,
128
+ "paramMap" => param_map.except(*exclude),
129
+ "defaultParamMap" => default_json(instance, exclude: exclude),
130
+ }.merge(extra)
131
+ write_text(session, File.join(path, "metadata"), JSON.generate(document))
132
+ end
133
+
134
+ # @return [Hash] the parsed `metadata` document under `path`.
135
+ def read_metadata(session, path)
136
+ JSON.parse(read_text(session, File.join(path, "metadata")))
137
+ end
138
+
139
+ # The class name written to metadata: the Spark (Scala) class name.
140
+ # @api private
141
+ def scala_class_name(klass)
142
+ klass.operator || klass.name
143
+ end
144
+
145
+ # The `paramMap` section of an instance: every param value (defaults
146
+ # included, as `extractParamMap` does), except the names in `skip` and
147
+ # operator-valued params (those are written as children).
148
+ # @return [Hash{String => Object}]
149
+ def extract_json_params(instance, skip: [])
150
+ instance.extract_param_map.each_with_object({}) do |(declared, value), acc|
151
+ next if skip.include?(declared.spark_name) || object_value?(value)
152
+
153
+ acc[declared.spark_name] = json_value(value)
154
+ end
155
+ end
156
+
157
+ # The `defaultParamMap` section: the defaults of the instance's class.
158
+ # @api private
159
+ def default_json(instance, exclude: [])
160
+ instance.class.params.values.select(&:default?).each_with_object({}) do |declared, acc|
161
+ next if exclude.include?(declared.spark_name)
162
+
163
+ value = declared.default_for(instance.class)
164
+ acc[declared.spark_name] = json_value(value) unless object_value?(value)
165
+ end
166
+ end
167
+
168
+ # Params holding operators (estimators, stages) are children, not JSON.
169
+ # @api private
170
+ def object_value?(value)
171
+ value.is_a?(Params) || (value.is_a?(Array) && value.any? { |v| v.is_a?(Params) || v.is_a?(Hash) })
172
+ end
173
+
174
+ # @api private
175
+ def json_value(value)
176
+ case value
177
+ when Linalg::Vector, Linalg::Matrix
178
+ raise IllegalArgumentError, "#{value.class.name.split('::').last} values cannot be written to metadata"
179
+ when Array then value.map { |v| json_value(v) }
180
+ else value
181
+ end
182
+ end
183
+
184
+ # The directory name of stage `index` of `count` with `uid`: the index is
185
+ # zero-padded to the width of `count`, as `PipelineSharedReadWrite.getStagePath`.
186
+ # @api private
187
+ def stage_dir_name(index, uid, count)
188
+ "#{index.to_s.rjust(count.to_s.length, '0')}_#{uid}"
189
+ end
190
+
191
+ # Overwrite handling for a write target (deletes `path` first when asked).
192
+ # @return [void]
193
+ def handle_overwrite(session, path, overwrite)
194
+ Rpc.handle_overwrite(session, path, overwrite)
195
+ end
196
+
197
+ # @api private
198
+ def write_text(session, path, text)
199
+ df = session.create_data_frame([{ "value" => text }], Types.struct(Types.field("value", Types.string)))
200
+ df.coalesce(1).write.text(path)
201
+ nil
202
+ end
203
+
204
+ # @api private
205
+ def read_text(session, path)
206
+ row = session.read.text(path).collect.first
207
+ row["value"] || row.values.first
208
+ end
209
+
210
+ # Save pipeline stages to `path/stages/<index>_<uid>`.
211
+ # @return [void]
212
+ def save_stages(path, stages, session:)
213
+ dir = File.join(path, "stages")
214
+ stages.each_with_index do |stage, i|
215
+ stage.save(File.join(dir, stage_dir_name(i, stage.uid, stages.size)), overwrite: false, session: session)
216
+ end
217
+ nil
218
+ end
219
+
220
+ # Load the stages listed in `meta["paramMap"]["stageUids"]`, in order.
221
+ # @return [Array<Params>]
222
+ def load_stages(path, meta, session:)
223
+ uids = meta.fetch("paramMap").fetch("stageUids")
224
+ uids.each_with_index.map do |uid, i|
225
+ load_any(session, File.join(path, "stages", stage_dir_name(i, uid, uids.size)))
226
+ end
227
+ end
228
+
229
+ # Find the Ruby class for a metadata `class` value: the Spark class name
230
+ # (`org.apache.spark.ml.classification.LogisticRegression`), or a PySpark
231
+ # one (`pyspark.ml.pipeline.PipelineModel`), matched by simple name.
232
+ #
233
+ # @param name [String]
234
+ # @return [Class]
235
+ # @raise [IllegalArgumentError] when no operator matches
236
+ def class_for(name)
237
+ classes = ML.operator_classes
238
+ found = classes.find { |klass| klass.operator == name }
239
+ if found.nil? && name.start_with?("pyspark.")
240
+ simple = name.split(".").last
241
+ found = classes.find { |klass| klass.name.split("::").last == simple }
242
+ end
243
+ found or raise IllegalArgumentError, "unsupported ML class #{name}"
244
+ end
245
+ end
246
+ end
247
+ end
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SparkConnect
4
+ module ML
5
+ # A pipeline of stages (estimators and transformers), like `pyspark.ml.Pipeline`.
6
+ #
7
+ # `fit` runs client-side, the way PySpark's Connect client does: each
8
+ # estimator stage is fit on the output of the stages before it, and the
9
+ # result is a {PipelineModel}. Every stage is a real server operator, so the
10
+ # whole graph runs on the server when the final DataFrame is executed.
11
+ #
12
+ # @example
13
+ # scaler = SparkConnect::ML::Feature::StandardScaler.new(input_col: "features", output_col: "scaled")
14
+ # lr = SparkConnect::ML::Classification::LogisticRegression.new(features_col: "scaled")
15
+ # model = SparkConnect::ML::Pipeline.new(stages: [scaler, lr]).fit(train)
16
+ class Pipeline < Estimator
17
+ operator "org.apache.spark.ml.Pipeline"
18
+
19
+ param :stages, :any, doc: "a list of pipeline stages"
20
+
21
+ # @return [Array<Params>] the stages.
22
+ def stages_list
23
+ get(:stages) || []
24
+ end
25
+
26
+ # @param value [Array<Params>]
27
+ # @return [self]
28
+ def set_stages(value)
29
+ set(:stages, value.to_a)
30
+ end
31
+
32
+ # Fit the pipeline on `dataset`.
33
+ #
34
+ # @param dataset [DataFrame]
35
+ # @param params [Hash, nil]
36
+ # @return [PipelineModel]
37
+ def fit(dataset, params = nil)
38
+ return copy(params).fit(dataset) if params && !params.empty?
39
+
40
+ stages = stages_list
41
+ stages.each do |stage|
42
+ next if stage.is_a?(Estimator) || stage.is_a?(Transformer)
43
+
44
+ raise IllegalArgumentError, "Cannot recognize a pipeline stage of type #{stage.class}."
45
+ end
46
+ last_estimator = stages.rindex { |s| s.is_a?(Estimator) } || -1
47
+ fitted = []
48
+ stages.each_with_index do |stage, i|
49
+ if i <= last_estimator
50
+ if stage.is_a?(Transformer)
51
+ fitted << stage
52
+ dataset = stage.transform(dataset)
53
+ else
54
+ model = stage.fit(dataset)
55
+ fitted << model
56
+ dataset = model.transform(dataset) if i < last_estimator
57
+ end
58
+ else
59
+ fitted << stage
60
+ end
61
+ end
62
+ PipelineModel.new(uid: uid, stages: fitted)
63
+ end
64
+
65
+ # Write the pipeline in Spark's format: `metadata` plus `stages/<i>_<uid>`.
66
+ # @api private
67
+ def save_meta(path, overwrite:, session:)
68
+ Persistence.handle_overwrite(session, path, overwrite)
69
+ Persistence.write_metadata(session, path, self, param_map: { "stageUids" => stages_list.map(&:uid) })
70
+ Persistence.save_stages(path, stages_list, session: session)
71
+ end
72
+
73
+ # @api private
74
+ def self.load_meta(path, session:)
75
+ meta = Persistence.read_metadata(session, path)
76
+ new(uid: meta.fetch("uid"), stages: Persistence.load_stages(path, meta, session: session))
77
+ end
78
+ end
79
+
80
+ # The fitted {Pipeline}: a list of fitted stages applied in order.
81
+ class PipelineModel < Transformer
82
+ operator "org.apache.spark.ml.PipelineModel"
83
+
84
+ param :stages, :any, doc: "a list of fitted stages"
85
+
86
+ # @return [Array<Transformer>] the fitted stages.
87
+ def stages_list
88
+ get(:stages) || []
89
+ end
90
+
91
+ # Apply every stage in order.
92
+ # @param dataset [DataFrame]
93
+ # @param params [Hash, nil]
94
+ # @return [DataFrame]
95
+ def transform(dataset, params = nil)
96
+ return copy(params).transform(dataset) if params && !params.empty?
97
+
98
+ stages_list.inject(dataset) { |df, stage| stage.transform(df) }
99
+ end
100
+
101
+ # @api private
102
+ def save_meta(path, overwrite:, session:)
103
+ Persistence.handle_overwrite(session, path, overwrite)
104
+ Persistence.write_metadata(session, path, self, param_map: { "stageUids" => stages_list.map(&:uid) })
105
+ Persistence.save_stages(path, stages_list, session: session)
106
+ end
107
+
108
+ # @api private
109
+ def self.load_meta(path, session:)
110
+ meta = Persistence.read_metadata(session, path)
111
+ new(uid: meta.fetch("uid"), stages: Persistence.load_stages(path, meta, session: session))
112
+ end
113
+ end
114
+ end
115
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SparkConnect
4
+ module ML
5
+ # Recommendation operators (`org.apache.spark.ml.recommendation`).
6
+ module Recommendation
7
+ # Alternating least squares matrix factorization.
8
+ class ALS < Estimator
9
+ operator "org.apache.spark.ml.recommendation.ALS"
10
+ model -> { ALSModel }
11
+
12
+ param :rank, :int, default: 10, doc: "rank of the factorization (>= 1)"
13
+ param :max_iter, :int, default: 10, doc: "maximum number of iterations (>= 0)"
14
+ param :reg_param, :double, default: 0.1, doc: "regularization parameter (>= 0)"
15
+ param :num_user_blocks, :int, default: 10, doc: "number of user blocks (>= 1)"
16
+ param :num_item_blocks, :int, default: 10, doc: "number of item blocks (>= 1)"
17
+ param :implicit_prefs, :boolean, default: false, doc: "whether to use implicit preference"
18
+ param :alpha, :double, default: 1.0, doc: "alpha for implicit preference (>= 0)"
19
+ param :user_col, :string, default: "user", doc: "column name for user ids"
20
+ param :item_col, :string, default: "item", doc: "column name for item ids"
21
+ param :seed, :long, default: SEED_DEFAULT, doc: "random seed"
22
+ param :rating_col, :string, default: "rating", doc: "column name for ratings"
23
+ param :nonnegative, :boolean, default: false, doc: "whether to use nonnegative constraint for least squares"
24
+ param :checkpoint_interval, :int, default: 10,
25
+ doc: "checkpoint interval (>= 1), or -1 to disable checkpointing"
26
+ param :intermediate_storage_level, :string, default: "MEMORY_AND_DISK",
27
+ doc: "StorageLevel for intermediate datasets"
28
+ param :final_storage_level, :string, default: "MEMORY_AND_DISK", doc: "StorageLevel for ALS model factors"
29
+ param :cold_start_strategy, :string, default: "nan", doc: "strategy for unknown users or items: nan or drop"
30
+ param :block_size, :int, default: 4096, doc: "block size for stacking input data in matrices (> 0)"
31
+ param :prediction_col, :string, default: "prediction", doc: "prediction column name"
32
+ end
33
+
34
+ # A fitted {ALS} model: the factors and the recommendation methods.
35
+ class ALSModel < Model
36
+ operator "org.apache.spark.ml.recommendation.ALSModel"
37
+
38
+ param :prediction_col, :string, default: "prediction", doc: "prediction column name"
39
+ param :block_size, :int, default: 4096, doc: "block size for stacking input data in matrices (> 0)"
40
+ param :user_col, :string, default: "user", doc: "column name for user ids"
41
+ param :item_col, :string, default: "item", doc: "column name for item ids"
42
+ param :cold_start_strategy, :string, default: "nan", doc: "strategy for unknown users or items: nan or drop"
43
+
44
+ attribute :rank, :int
45
+ attribute :item_factors, :dataframe, spark_name: "itemFactors"
46
+ attribute :user_factors, :dataframe, spark_name: "userFactors"
47
+ method_call :recommend_for_all_users, arg_count: 1, returns: :dataframe, spark_name: "recommendForAllUsers"
48
+ method_call :recommend_for_all_items, arg_count: 1, returns: :dataframe, spark_name: "recommendForAllItems"
49
+ method_call :recommend_for_user_subset, arg_count: 2, returns: :dataframe,
50
+ spark_name: "recommendForUserSubset"
51
+ method_call :recommend_for_item_subset, arg_count: 2, returns: :dataframe,
52
+ spark_name: "recommendForItemSubset"
53
+ end
54
+ end
55
+ end
56
+ end