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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0e74ad29eb515f38a9735a8d719adc6fb38d8d7cbb7719ca5cf69b43ae4b32de
4
- data.tar.gz: f9006bc6e7f05631175457fe4d8219f023456d544ff9d1d377ac918dcc4ad9af
3
+ metadata.gz: 88b02353f4f80bc95bf47558d9979c33bc61756d984f2eae1be8ffbe5a8c1090
4
+ data.tar.gz: 17f91f10e70691cc81d3de35569aaa1eef0339e679aa14ee18ce20d631604031
5
5
  SHA512:
6
- metadata.gz: 975ca916148a4005eddfe9db971746f0128b5190251dde7dcc8e287cae267df8169d3446136c195fc4e2298945e5ad1a6a1c70754c2ca12ae95b00b29eb3ceb2
7
- data.tar.gz: 9df3247554b07123aedfc0cbc5c790f5cda158fe328ff3d8145f311ab9ac36acf35ad3d0489939b6ea68853fdaf736a66b791652f42ef612222f27596f6b556c
6
+ metadata.gz: 93d7bb9c61c0fdacaa74c143f37f0ac39685d1be87cfe0ed65faf70eb3119513b59c9815886490a145dacee2d04f31de11030dbd155c553e7a9beadef074414f
7
+ data.tar.gz: c2ff36eebcd7318b424f13d802b1166db359a84f733f3b5e1dd68f98ea64100cb1a770b83e91bc139429ceb7ebd9f3e6d19e5b13172092fc19fb63ee70112f21
data/CHANGELOG.md CHANGED
@@ -7,6 +7,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.5.0] - 2026-11-17
11
+
12
+ ### Added
13
+
14
+ - **Spark ML over Spark Connect** (`SparkConnect::ML`), mirroring `pyspark.ml`.
15
+ Needs a Spark 4.0 server; the cache administration commands need 4.1.
16
+ - Params with Spark's defaults, typed setters and getters, `copy`,
17
+ `extract_param_map`, `explain_params`, and `ParamGridBuilder`.
18
+ - Base classes `Estimator`, `Transformer`, `Model`, `Evaluator`, `Pipeline`
19
+ and `PipelineModel`.
20
+ - Every operator the Spark 4.3 Connect server allows: 42 estimators, 61
21
+ transformers (models included) and 6 evaluators, under `ML::Classification`,
22
+ `ML::Regression`, `ML::Clustering`, `ML::Recommendation`, `ML::FPM`,
23
+ `ML::Feature`, `ML::FeatureTransformers` and `ML::Evaluation`.
24
+ - Model attributes, methods and training summaries through `MlCommand.Fetch`,
25
+ limited to the members the server allows.
26
+ - Save and load (with overwrite) for operators, models, pipelines and
27
+ validators through `MlCommand.Write`/`Read`.
28
+ - `CrossValidator`, `TrainValidationSplit` and their models, orchestrated on the
29
+ client as PySpark's Connect client does.
30
+ - `DenseVector`, `SparseVector`, `DenseMatrix` and `SparseMatrix`, decoded from
31
+ `VectorUDT`/`MatrixUDT` columns and accepted as params.
32
+ - `ML::Stat` (Correlation, ChiSquareTest, KolmogorovSmirnovTest, Summarizer)
33
+ and `ML::Functions` (`vector_to_array`, `array_to_vector`).
34
+ - Server ML cache lifetime: models release their server object when released
35
+ or collected, and `ML.clean_cache` / `ML.cache_info` on Spark 4.1+.
36
+ - `ML::Classification::OneVsRest` and `OneVsRestModel`, run on the client as
37
+ PySpark does.
38
+ - Save and load write and read Spark's standard ML persistence format for
39
+ pipelines, validators and one-vs-rest models, so models move between Ruby,
40
+ PySpark and Scala Spark in both directions.
41
+ - `DistributedLDAModel#to_local` and the no-argument `describe_topics`.
42
+ - Every `seed` param defaults to Spark's class-derived seed, and
43
+ CrossValidator and TrainValidationSplit split with it, so fits are repeatable.
44
+ Validator fits cache their splits, use population standard deviations, and
45
+ run `parallelism` fits on threads.
46
+
10
47
  ## [0.4.0] - 2026-11-04
11
48
 
12
49
  Feature parity with the PySpark 4.3.0 Spark Connect client. Items marked with a
@@ -247,7 +284,8 @@ Initial release.
247
284
  - Vendored Spark Connect 4.1 protobuf/gRPC definitions and a regeneration script
248
285
  (`bin/generate-protos`).
249
286
 
250
- [Unreleased]: https://github.com/HyukjinKwon/spark-connect-ruby/compare/v0.4.0...HEAD
287
+ [Unreleased]: https://github.com/HyukjinKwon/spark-connect-ruby/compare/v0.5.0...HEAD
288
+ [0.5.0]: https://github.com/HyukjinKwon/spark-connect-ruby/compare/v0.4.0...v0.5.0
251
289
  [0.4.0]: https://github.com/HyukjinKwon/spark-connect-ruby/compare/v0.3.0...v0.4.0
252
290
  [0.3.0]: https://github.com/HyukjinKwon/spark-connect-ruby/compare/v0.2.0...v0.3.0
253
291
  [0.2.0]: https://github.com/HyukjinKwon/spark-connect-ruby/compare/v0.1.0...v0.2.0
data/README.md CHANGED
@@ -47,7 +47,10 @@ PySpark 4.3: subqueries, lateral and nearest-by joins, `zip`, `merge_into`,
47
47
  table-valued functions, `as_table` table arguments, caching with storage
48
48
  levels, session cloning, progress handlers, operation status, the TIME,
49
49
  spatial, and nanosecond timestamp types, and every built-in SQL function in
50
- `pyspark.sql.functions`.
50
+ `pyspark.sql.functions`. It also runs **Spark ML** over Connect
51
+ (`SparkConnect::ML`): every estimator, transformer and evaluator the server
52
+ allows, models with their attributes and summaries, pipelines, cross-validation,
53
+ save/load, and linear algebra. See the [Machine Learning guide](https://hyukjinkwon.github.io/spark-connect-ruby/ml.html).
51
54
 
52
55
  **Out of scope** are the parts of PySpark that run client-side code on the
53
56
  server or depend on Python libraries, because Spark executes such code only in
@@ -62,7 +65,6 @@ Python (or JVM) workers and has no Ruby worker:
62
65
  columnar `Arrow::Table`;
63
66
  - the UDF profiler (`spark.profile`) and artifact upload (`addArtifacts`,
64
67
  `copyFromLocalToFs`), which exist to serve UDF code;
65
- - the separate, experimental MLlib-over-Connect surface.
66
68
 
67
69
  Results decode through Apache Arrow into ordered, name-addressable `Row`s.
68
70
  Method names are snake_case (idiomatic Ruby) with camelCase aliases for the
@@ -163,7 +165,7 @@ spark.sql("SELECT * FROM VALUES (1), (2), (3) AS t(x) WHERE x > :min", { min: 1
163
165
  Full documentation, including guides for every part of the API, lives at
164
166
  **<https://hyukjinkwon.github.io/spark-connect-ruby/>**.
165
167
 
166
- Runnable [`examples/`](examples/) cover quickstart, transformations, aggregations, joins, window functions, SQL, reading/writing, local data, and NA/stat helpers.
168
+ Runnable [`examples/`](examples/) cover quickstart, transformations, aggregations, joins, window functions, SQL, reading/writing, local data, NA/stat helpers, and Spark ML.
167
169
 
168
170
  ## Compatibility
169
171
 
@@ -23,7 +23,11 @@ module SparkConnect
23
23
  batches.each do |data|
24
24
  next if data.nil? || data.empty?
25
25
 
26
- reader = ::Arrow::RecordBatchStreamReader.new(::Arrow::BufferInputStream.new(::Arrow::Buffer.new(data)))
26
+ # Keep the buffer and stream referenced until the reader is drained: the
27
+ # reader holds only C-side references to them.
28
+ buffer = ::Arrow::Buffer.new(data)
29
+ input = ::Arrow::BufferInputStream.new(buffer)
30
+ reader = ::Arrow::RecordBatchStreamReader.new(input)
27
31
  reader.each do |record_batch|
28
32
  field_names ||= record_batch.schema.fields.map(&:name)
29
33
  record_batch.raw_records.each do |values|
@@ -64,7 +64,7 @@ module SparkConnect
64
64
  ExecuteResult = Struct.new(
65
65
  :arrow_batches, :schema, :metrics, :observed_metrics, :sql_command_result, :row_count,
66
66
  :write_stream_result, :streaming_query_result, :streaming_manager_result, :checkpoint_relation,
67
- :pipeline_command_result, :pipeline_events, :operation_id
67
+ :pipeline_command_result, :pipeline_events, :operation_id, :ml_command_result
68
68
  )
69
69
 
70
70
  # @return [String] the client-side session id (UUID v4).
@@ -386,6 +386,8 @@ module SparkConnect
386
386
  result.pipeline_command_result = resp.pipeline_command_result
387
387
  when :pipeline_event_result
388
388
  result.pipeline_events << resp.pipeline_event_result.event
389
+ when :ml_command_result
390
+ result.ml_command_result = resp.ml_command_result
389
391
  end
390
392
  end
391
393
 
@@ -955,7 +955,8 @@ module SparkConnect
955
955
  # @return [Array<Row>]
956
956
  def collect
957
957
  result = @session.client.execute_plan(@relation)
958
- ArrowConverter.to_rows(result.arrow_batches)
958
+ rows = ArrowConverter.to_rows(result.arrow_batches)
959
+ ML::Linalg.convert_rows(rows, result.schema)
959
960
  end
960
961
  alias to_a collect
961
962
 
@@ -0,0 +1,433 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SparkConnect
4
+ module ML
5
+ # Shared behaviour of the operator base classes: the server-side operator
6
+ # name (`operator`) and the session an operator instance talks through.
7
+ # Estimators and transformers are client-side objects; only fitted models
8
+ # hold a server-side reference (see {Model}).
9
+ class Estimator < Params
10
+ # Fit on `dataset`. Returns a fitted {Model} of the class declared with
11
+ # {Estimator.model}; the model is backed by an object in the server's ML cache.
12
+ #
13
+ # @param dataset [DataFrame]
14
+ # @param params [Hash{Param, Symbol => Object}, Array<Hash>, nil] overrides; an
15
+ # array of param maps fits once per map and returns an Array of models.
16
+ # @return [Model, Array<Model>]
17
+ def fit(dataset, params = nil)
18
+ return params.map { |map| fit(dataset, map) } if params.is_a?(Array)
19
+ return copy(params).fit(dataset) if params && !params.empty?
20
+
21
+ session = dataset.session
22
+ result = Rpc.run(session, Proto::MlCommand.new(fit: Proto::MlCommand::Fit.new(
23
+ estimator: Rpc.operator_proto(self, :estimator),
24
+ params: Serialize.ml_params(explicit_param_map),
25
+ dataset: dataset.relation
26
+ )))
27
+ info = Rpc.operator_info(result)
28
+ warn("spark-connect: #{info[:warning_message]}") if info[:warning_message]
29
+ build_model(session, info[:obj_ref], dataset.relation)
30
+ end
31
+
32
+ # @return [Class<Model>, nil] the model class this estimator produces.
33
+ def model_class
34
+ self.class.model_class
35
+ end
36
+
37
+ # Declare the model class produced by `fit`. Pass a class, or a lambda
38
+ # returning one so the model can be declared later in the file.
39
+ # @return [Class, nil]
40
+ def self.model(klass = nil)
41
+ return @model = klass if klass
42
+
43
+ resolved = @model
44
+ resolved = resolved.call if resolved.respond_to?(:call)
45
+ resolved || (superclass.respond_to?(:model) ? superclass.model : nil)
46
+ end
47
+
48
+ # @api private
49
+ def self.model_class = model
50
+
51
+ # Write this estimator to `path`.
52
+ # @param path [String]
53
+ # @param overwrite [Boolean]
54
+ # @param session [SparkSession]
55
+ # @return [void]
56
+ def save(path, overwrite: false, session: nil)
57
+ session = ML.session_or_active(session)
58
+ Persistence.save_operator(self, path, overwrite: overwrite, session: session)
59
+ end
60
+
61
+ # Read an estimator written by {#save}.
62
+ # @param path [String]
63
+ # @param session [SparkSession]
64
+ # @return [Estimator]
65
+ def self.load(path, session: nil)
66
+ session = ML.session_or_active(session)
67
+ Persistence.load_operator(self, path, session: session)
68
+ end
69
+
70
+ private
71
+
72
+ def build_model(session, obj_ref, dataset_relation)
73
+ model = model_class.new(uid: uid)
74
+ model.attach(session, obj_ref, training_relation: dataset_relation)
75
+ model.copy_values_from(self)
76
+ model.send(:build_training_summary, dataset_relation) if model.class.summary_class
77
+ model
78
+ end
79
+ end
80
+
81
+ # Base class of the non-model transformers (VectorAssembler, Tokenizer, ...),
82
+ # and of {Model}.
83
+ class Transformer < Params
84
+ # Apply the transformer to `dataset`, returning a lazy {DataFrame} (the
85
+ # server runs it when the DataFrame is executed).
86
+ #
87
+ # @param dataset [DataFrame]
88
+ # @param params [Hash, nil] overrides for this call only.
89
+ # @return [DataFrame]
90
+ def transform(dataset, params = nil)
91
+ return copy(params).transform(dataset) if params && !params.empty?
92
+
93
+ session = dataset.session
94
+ relation = PlanBuilder.relation(session, ml_relation: transform_relation(dataset.relation))
95
+ DataFrame.new(session, relation)
96
+ end
97
+
98
+ # @api private
99
+ def transform_relation(input)
100
+ Proto::MlRelation.new(transform: Proto::MlRelation::Transform.new(
101
+ input: input,
102
+ transformer: Rpc.operator_proto(self, :transformer),
103
+ params: Serialize.ml_params(explicit_param_map)
104
+ ))
105
+ end
106
+
107
+ # Write this transformer to `path`.
108
+ # @return [void]
109
+ def save(path, overwrite: false, session: nil)
110
+ session = ML.session_or_active(session)
111
+ Persistence.save_operator(self, path, overwrite: overwrite, session: session)
112
+ end
113
+
114
+ # Read a transformer written by {#save}.
115
+ # @return [Transformer]
116
+ def self.load(path, session: nil)
117
+ session = ML.session_or_active(session)
118
+ Persistence.load_operator(self, path, session: session)
119
+ end
120
+ end
121
+
122
+ # Base class of evaluators (metrics over a predictions DataFrame).
123
+ class Evaluator < Params
124
+ # Compute the metric over `dataset`.
125
+ #
126
+ # @param dataset [DataFrame]
127
+ # @param params [Hash, nil]
128
+ # @return [Float]
129
+ def evaluate(dataset, params = nil)
130
+ return copy(params).evaluate(dataset) if params && !params.empty?
131
+
132
+ result = Rpc.run(dataset.session, Proto::MlCommand.new(evaluate: Proto::MlCommand::Evaluate.new(
133
+ evaluator: Rpc.operator_proto(self, :evaluator),
134
+ params: Serialize.ml_params(explicit_param_map),
135
+ dataset: dataset.relation
136
+ )))
137
+ Rpc.decode_result(result)
138
+ end
139
+
140
+ # Whether a larger metric value is better (PySpark's `isLargerBetter`).
141
+ # @return [Boolean]
142
+ def larger_better? = true
143
+
144
+ # @return [Boolean] alias of {#larger_better?}.
145
+ def is_larger_better? = larger_better?
146
+
147
+ # Write this evaluator to `path`.
148
+ def save(path, overwrite: false, session: nil)
149
+ session = ML.session_or_active(session)
150
+ Persistence.save_operator(self, path, overwrite: overwrite, session: session)
151
+ end
152
+
153
+ # @return [Evaluator]
154
+ def self.load(path, session: nil)
155
+ session = ML.session_or_active(session)
156
+ Persistence.load_operator(self, path, session: session)
157
+ end
158
+ end
159
+
160
+ # Class-level DSL for the accessors of models and summaries: {AttributeDSL.attribute},
161
+ # {AttributeDSL.method_call} and (models only) {AttributeDSL.summary_class}.
162
+ module AttributeDSL
163
+ # Declare an attribute read from the server: `model.coefficients`.
164
+ #
165
+ # @param name [Symbol] Ruby name.
166
+ # @param type [Symbol] `:vector`, `:matrix`, `:double`, `:int`, `:long`, `:string`,
167
+ # `:boolean`, `:double_array`, `:int_array`, `:string_array`, `:dataframe`, or `:any`.
168
+ # @param spark_name [String, nil] the Scala method name when it differs (`getSplits`).
169
+ # @return [void]
170
+ def attribute(name, type = :any, spark_name: nil)
171
+ method_name = spark_name || ML.camelize(name)
172
+ define_method(name) do
173
+ AttributeSupport.invoke(self, [AttributeSupport.method_proto(method_name, [])], type)
174
+ end
175
+ nil
176
+ end
177
+
178
+ # Declare a server method with arguments: `model.predict(vector)`.
179
+ #
180
+ # @param name [Symbol]
181
+ # @param arg_count [Integer] the number of positional arguments.
182
+ # @param returns [Symbol, Class] a result type (see {attribute}), or a
183
+ # {Summary} subclass when the method returns a summary.
184
+ # @param spark_name [String, nil]
185
+ # @return [void]
186
+ def method_call(name, arg_count: 0, returns: :any, spark_name: nil)
187
+ method_name = spark_name || ML.camelize(name)
188
+ define_method(name) do |*args|
189
+ raise IllegalArgumentError, "#{name} takes #{arg_count} argument(s)" unless args.size == arg_count
190
+
191
+ if returns.is_a?(Class) && returns <= Summary
192
+ obj_ref, base = AttributeSupport.owner_chain(self)
193
+ summary_id = Rpc.fetch(session, obj_ref, base + [AttributeSupport.method_proto(method_name, args)])
194
+ return returns.new(session, summary_id, [])
195
+ end
196
+ AttributeSupport.invoke(self, [AttributeSupport.method_proto(method_name, args)], returns)
197
+ end
198
+ nil
199
+ end
200
+
201
+ # Declare the training summary class. The summary is available as
202
+ # `model.summary` after `fit`; it is absent on models loaded from disk
203
+ # (unless the server still caches it).
204
+ # @param klass [Class<Summary>, Proc]
205
+ # @return [Class, nil]
206
+ def summary_class(klass = nil)
207
+ return @summary_class = klass if klass
208
+
209
+ resolved = @summary_class
210
+ resolved = resolved.call if resolved.respond_to?(:call)
211
+ resolved || (superclass.respond_to?(:summary_class) ? superclass.summary_class : nil)
212
+ end
213
+ end
214
+
215
+ # A training summary (or evaluation summary) cached by the server. A
216
+ # training summary is addressed as a method chain on its model: the summary
217
+ # of model `m` is the owner `(m.ref_id, [summary])`, and `m.summary.roc` is
218
+ # the fetch `[summary, roc]` on the model id. The result of
219
+ # `model.evaluate(df)` is a summary with its own cache id and no chain.
220
+ class Summary
221
+ extend AttributeDSL
222
+
223
+ # @return [SparkSession]
224
+ attr_reader :session
225
+
226
+ # @api private
227
+ # @return [String] the server object the chain starts from.
228
+ attr_reader :obj_ref
229
+
230
+ # @api private
231
+ # @return [Array<Proto::Fetch::Method>] the chain of methods from `obj_ref`.
232
+ attr_reader :chain
233
+
234
+ # @api private
235
+ # @return [Proto::Relation, nil] the dataset the summary was built on.
236
+ attr_reader :dataset_relation
237
+
238
+ # @api private
239
+ def initialize(session, obj_ref, chain, dataset_relation: nil)
240
+ @session = session
241
+ @obj_ref = obj_ref
242
+ @chain = chain
243
+ @dataset_relation = dataset_relation
244
+ end
245
+ end
246
+
247
+ # Plumbing for the accessors declared on models and summaries. Each accessor
248
+ # becomes one `Fetch` (or, for DataFrame results, an `MlRelation.fetch`).
249
+ module AttributeSupport
250
+ module_function
251
+
252
+ # @return [Proto::Fetch::Method]
253
+ def method_proto(name, args)
254
+ Proto::Fetch::Method.new(
255
+ method: name,
256
+ args: args.map do |arg|
257
+ case arg
258
+ when DataFrame then Proto::Fetch::Method::Args.new(input: arg.relation)
259
+ else Proto::Fetch::Method::Args.new(param: Serialize.literal(arg))
260
+ end
261
+ end
262
+ )
263
+ end
264
+
265
+ # @api private
266
+ # @return [Array(String, Array<Proto::Fetch::Method>)] the root object id and its chain.
267
+ def owner_chain(owner)
268
+ owner.is_a?(Model) ? [owner.ref_id, []] : [owner.obj_ref, owner.chain]
269
+ end
270
+
271
+ # @api private
272
+ def owner_dataset(owner)
273
+ owner.is_a?(Model) ? owner.training_relation : owner.dataset_relation
274
+ end
275
+
276
+ # Call `chain` (one method, usually) on `owner` and convert the result.
277
+ #
278
+ # @param owner [Model, Summary]
279
+ # @param chain [Array<Proto::Fetch::Method>] the methods to call after the owner's chain.
280
+ # @param type [Symbol] the result type (see {Model::ClassMethods#attribute}).
281
+ # @return [Object]
282
+ def invoke(owner, chain, type)
283
+ obj_ref, base = owner_chain(owner)
284
+ methods = base + chain
285
+ return relation_result(owner, methods) if type == :dataframe
286
+
287
+ fetch_restoring_summary(owner, obj_ref, methods)
288
+ end
289
+
290
+ # @api private
291
+ def relation_result(owner, methods)
292
+ session = owner.session
293
+ obj_ref = owner_chain(owner).first
294
+ ml_rel = Proto::MlRelation.new(fetch: Proto::Fetch.new(obj_ref: Proto::ObjectRef.new(id: obj_ref), methods: methods))
295
+ dataset = owner_dataset(owner)
296
+ ml_rel.model_summary_dataset = dataset if summary_chain?(methods) && dataset && Rpc.supports?(session, :model_summary_dataset)
297
+ DataFrame.new(session, PlanBuilder.relation(session, ml_relation: ml_rel))
298
+ end
299
+
300
+ # @api private
301
+ def summary_chain?(methods)
302
+ methods.first && methods.first["method"] == "summary"
303
+ end
304
+
305
+ # Fetch, rebuilding an offloaded training summary once when the server
306
+ # lost it (Spark 4.1+ keeps the training dataset around for that).
307
+ # @api private
308
+ def fetch_restoring_summary(owner, obj_ref, methods)
309
+ Rpc.fetch(owner.session, obj_ref, methods)
310
+ rescue SparkConnectError => e
311
+ raise unless e.error_class == Rpc::SUMMARY_LOST && summary_chain?(methods) && owner_dataset(owner)
312
+
313
+ Rpc.create_summary(owner.session, obj_ref, owner_dataset(owner))
314
+ Rpc.fetch(owner.session, obj_ref, methods)
315
+ end
316
+ end
317
+
318
+ # A fitted model: a server-side object referenced by id, plus the
319
+ # client-side decorations PySpark adds (uid, summary, copied params).
320
+ #
321
+ # Attributes are declared with {ClassMethods#attribute}, methods with
322
+ # {ClassMethods#method_call}, and the training summary with
323
+ # {ClassMethods#summary_class}.
324
+ class Model < Transformer
325
+ extend AttributeDSL
326
+
327
+ # @return [SparkSession, nil]
328
+ attr_reader :session
329
+
330
+ # @return [ModelRef, nil] the server-side handle.
331
+ attr_reader :model_ref
332
+
333
+ # @return [Summary, nil] the training summary, when `fit` produced one.
334
+ attr_reader :summary_object
335
+
336
+ # @api private
337
+ # @return [Proto::Relation, nil] the training dataset (summary restore).
338
+ attr_reader :training_relation
339
+
340
+ # Attach this model to a server object.
341
+ #
342
+ # @api private
343
+ def attach(session, obj_ref, training_relation: nil)
344
+ @session = session
345
+ @model_ref = ModelRef.new(obj_ref, session)
346
+ @training_relation = training_relation
347
+ ObjectSpace.define_finalizer(self, Model.finalizer_for(@model_ref))
348
+ self
349
+ end
350
+
351
+ # The server-side object id of this model.
352
+ # @return [String]
353
+ def ref_id = model_ref.id
354
+
355
+ # @api private
356
+ def self.finalizer_for(ref)
357
+ proc { ref.release_ref }
358
+ end
359
+
360
+ # @return [Boolean] whether a training summary exists.
361
+ def has_summary?
362
+ !@summary_object.nil?
363
+ end
364
+
365
+ # The training summary.
366
+ # @return [Summary]
367
+ # @raise [IllegalArgumentError] when there is no summary (models loaded from disk)
368
+ def summary
369
+ return @summary_object if @summary_object
370
+
371
+ raise IllegalArgumentError, "No training summary available for this #{self.class.name.split('::').last}"
372
+ end
373
+
374
+ # @return [self]
375
+ def copy(extra = {})
376
+ that = super
377
+ ref = that.model_ref
378
+ if ref
379
+ ref.add_ref
380
+ ObjectSpace.define_finalizer(that, Model.finalizer_for(ref))
381
+ end
382
+ that
383
+ end
384
+
385
+ # Release this model's server-side object (when no other copy holds it).
386
+ # @return [void]
387
+ def release
388
+ @model_ref&.release_ref
389
+ nil
390
+ end
391
+
392
+ # @api private
393
+ def transform_relation(input)
394
+ Proto::MlRelation.new(transform: Proto::MlRelation::Transform.new(
395
+ input: input,
396
+ obj_ref: Proto::ObjectRef.new(id: ref_id),
397
+ params: Serialize.ml_params(explicit_param_map)
398
+ ))
399
+ end
400
+
401
+ # Write this model to `path` (overwrites when `overwrite:`).
402
+ # @return [void]
403
+ def save(path, overwrite: false, session: nil)
404
+ resolved = ML.session_or_active(session, @session)
405
+ if respond_to?(:save_meta, true)
406
+ Persistence.save_operator(self, path, overwrite: overwrite, session: resolved)
407
+ else
408
+ Persistence.save_model(self, path, overwrite: overwrite, session: resolved)
409
+ end
410
+ end
411
+
412
+ # Read a model written by {#save}.
413
+ # @return [Model]
414
+ def self.load(path, session: nil)
415
+ session = ML.session_or_active(session)
416
+ return load_meta(path, session: session) if respond_to?(:load_meta)
417
+
418
+ Persistence.load_model(self, path, session: session)
419
+ end
420
+
421
+ private
422
+
423
+ def build_training_summary(dataset_relation)
424
+ klass = self.class.summary_class
425
+ return unless klass
426
+
427
+ @training_relation = dataset_relation
428
+ @summary_object = klass.new(session, ref_id, [AttributeSupport.method_proto("summary", [])],
429
+ dataset_relation: dataset_relation)
430
+ end
431
+ end
432
+ end
433
+ end