diff --git a/CHANGELOG.md b/CHANGELOG.md index efa0d36..2dbb064 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,68 +3,58 @@ `latu_ml` follows [Semantic Versioning](https://semver.org). Before 1.0, a minor version may rename or remove; each such change is listed here with the migration in one line. +## Unreleased + +**The `latu` requirement is now `~> 0.4`**, tightened from `~> 0.3`. Nothing here needs a +Latu 0.4 feature; the old constraint resolved any Latu below 1.0, and Latu's own changelog +says a minor version may rename or remove, so it permitted a Latu release that broke this +package silently. Bump `latu` alongside `latu_ml`. + ## 0.1.0 — 2026-09-07 First release, against Spark **4.2.0**, and a companion to `latu ~> 0.3`. Spark MLlib from Elixir over Spark Connect: `fit`, `transform`, `evaluate`, model and summary attributes, `save`/`load` in Spark's own on-disk format, the model cache and its bracket, the -`ConnectHelper` route, pipelines and grid search. The operator surface is **generated** — 111 +`ConnectHelper` route, pipelines and grid search. The operator surface is **generated**: 111 rows carrying 991 params, extracted from PySpark's own classes and the server's own -`ALLOWED_ATTRIBUTES` rather than transcribed — giving 68 constructors and 623 accessors across -64 model and summary modules. All 66 runnable operators have been run against a live server. - -Every place the API departs from `pyspark.ml` is in `docs/deviations.md`, with why. What -follows is what each milestone added, oldest last. - -`Latu.ML.Functions.vector_to_array/2` and `array_to_vector/1`: the way to read a `Vector` -column, which `Latu.collect/2` refuses. Spark keeps both in an *internal* function registry -rather than the builtin one, so they are unreachable from SQL and reachable over Connect — the -wire form is a plain `UnresolvedFunction` with `is_internal` left unset. `docs/deviations.md` -has the whole of it. `Summarizer` uses the same route and is not wrapped yet: reading a metric -out of the struct `aggregate_metrics` answers with needs field access Latu does not build. - -`Latu.ML.evaluate/2` runs an evaluator; `Latu.ML.save/3` and `Latu.ML.load/3` write a model or -an unfitted operator to Spark's own on-disk format and read one back. All six evaluators are -`:probed` as a result, and `dev/README.md` has the interop dance that shows PySpark reading what -this wrote and the reverse. - -The `ConnectHelper` route: `Latu.ML.Stat`'s three statistical tests, `Latu.ML.assign_clusters/2` -and `find_frequent_sequential_patterns/2` for the two operators that are neither fitted nor -applied, `from_labels/3` and its siblings generated onto their model modules, -`Latu.ML.Feature.load_default_stop_words/2`, and `Latu.ML.helper/3` under all of them. The -registry grew a fifth operator kind and a helpers section, both extracted; `Latu.ML.Plan` grew -nested lists, which also closes `Bucketizer.splitsArray`. - -Pipelines: `Latu.ML.pipeline/1` builds one, `Latu.ML.fit/2` folds a frame through its stages, -and `save/3` and `load/3` carry both a fitted and an unfitted one in Spark's own directory -layout. There is no wire form for a pipeline in any client, so the fold is this package's own — -`dev/probe_ml.exs`'s pipelines section checks it lands where fitting the stages by hand does, -and `--interop` has PySpark reading a pipeline Latu wrote and the reverse. The layout is -PySpark's, which Scala cannot read; `docs/deviations.md` says so plainly and `docs/decisions.md` -has the one key it turns on. - -Tuning: `Latu.ML.param_grid/1,2` builds a grid as data, `cross_validator/1` and -`train_validation_split/1` search one, and `fit/2` runs the search — folds cut with -`rand(seed)` and a range as Spark does it, one fit at a time, the winner refit on the whole -frame. A sub-model is released as its metric is read, so a five-by-six search holds one cache -entry rather than thirty; `collect_sub_models: true` keeps them and `delete/1` gives them back. -`larger_better?/1` and `best_index/1` are public, read off the six client-side `isLargerBetter` -overrides the registry now extracts. `dev/pyspark_oracle.py --interop` prints PySpark's metrics -for the same grid, seed and rows, which is the only check either side has. - -`save/3` and `load/4` carry a search too, in Spark's own layout: `metadata` with the -validator's params and its encoded grid, `estimator/` and `evaluator/`, and for a fitted one -`bestModel/` and the metrics. `sub_models: true` writes the fold models and asks for them back -— **a plain load leaves them on disk**, which is where this deviates from PySpark and why is in -`docs/deviations.md`. PySpark reads a search this wrote and the reverse; `dev/README.md` has -the dance. - -Documentation, to Latu's standard: a [quick start](docs/guides/quick-start.md) and a -[cookbook](docs/guides/cookbook.md) — a recipe per model family, plus pipelines, grid search and -cleaning up — both executed by `test/integration/guides_test.exs` like the two "coming from" -guides. `usage-rules.md` ships for agents in the `usage_rules` convention, and -`docs/cheatsheet.cheatmd` puts every hand-written verb on one page with -`test/latu/cheatsheet_test.exs` failing on either kind of drift. The README gained an install -section, a server to point at and links to all of it; `CONTRIBUTING.md` carries the extractors, -the oracle, the probe and the release checklist. +`ALLOWED_ATTRIBUTES` rather than transcribed. That gives 68 constructors and 623 accessors +across 64 model and summary modules. All 66 runnable operators have been run against a +live server. + +Every place the API departs from `pyspark.ml` is in `docs/deviations.md`, with why. + +- **Operators and models.** `Latu.ML.fit/2` and `transform/2`, `attribute/2` and + `attribute_frame/2` for what a fitted model knows, and a generated accessor module per model + and summary class. A model is a handle into a server-side cache, not a value. `with_model/3` + brackets one and `delete/1` gives it back. +- **Reading a `Vector` column.** `Latu.ML.Functions.vector_to_array/2` and `array_to_vector/1`, + which is what `Latu.collect/2` refuses. Spark keeps both in an internal function registry + rather than the builtin one, so they are unreachable from SQL and reachable over Connect. The + wire form is a plain `UnresolvedFunction` with `is_internal` left unset. `Summarizer` takes + the same route and is not wrapped: reading one metric out of the struct it answers with needs + field access Latu does not build. +- **Evaluation and persistence.** `Latu.ML.evaluate/2` runs an evaluator, and `Latu.ML.save/3` + and `Latu.ML.load/3` carry a model or an unfitted operator through Spark's own on-disk + format. All six evaluators are `:probed` as a result. PySpark reads what this writes and the + reverse; `dev/README.md` has the interop dance. +- **The `ConnectHelper` route.** `Latu.ML.Stat`'s three statistical tests, + `Latu.ML.assign_clusters/2` and `find_frequent_sequential_patterns/2` for the two operators + that are neither fitted nor applied, `from_labels/3` and its siblings generated onto their + model modules, `Latu.ML.Feature.load_default_stop_words/2`, and `Latu.ML.helper/3` under all + of them. +- **Pipelines and tuning.** `Latu.ML.pipeline/1` builds a pipeline and `Latu.ML.param_grid/1,2` + builds a grid as data; `cross_validator/1` and `train_validation_split/1` search one. None of + them has a wire form in any client, so the folds are this package's own, cut with `rand(seed)` + and a range as Spark does it. A sub-model is released as its metric is read, so a five-by-six + search holds one cache entry rather than thirty. `collect_sub_models: true` keeps them. + `larger_better?/1` and `best_index/1` are public. A saved search carries its encoded grid, and + `sub_models: true` writes the fold models and asks for them back. **A plain load leaves them + on disk**, which is where this deviates from PySpark. +- **Documentation.** A [quick start](docs/guides/quick-start.md) and a + [cookbook](docs/guides/cookbook.md), a recipe per model family, both executed by + `test/integration/guides_test.exs` like the two "coming from" guides. `usage-rules.md` ships + for agents in the `usage_rules` convention, and `docs/cheatsheet.cheatmd` puts every + hand-written verb on one page with `test/latu/cheatsheet_test.exs` failing on either kind of + drift. `CONTRIBUTING.md` carries the extractors, the oracle, the probe and the release + checklist. diff --git a/CLAUDE.md b/CLAUDE.md index a86d5c8..71160b3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,7 +14,7 @@ load-bearing enough to restate. ## What this package may assume of Latu -Latu **0.3.0** — the pin is `~> 0.3` — exposes exactly five things for this package, and no +Latu **0.4.0**, pinned `~> 0.4`, exposes exactly five things for this package, and no more: - `Latu.Plan.new/1` wraps a `Relation` or a `Command` as a `Plan`. diff --git a/README.md b/README.md index 64f1818..fbfac00 100644 --- a/README.md +++ b/README.md @@ -11,19 +11,21 @@ package to [Latu](https://hexdocs.pm/latu). The algorithms run on the cluster, where the data is. The Elixir side holds plans and handles. +MLlib is DataFrame in, DataFrame out. There is no `fit(x, y)` on tensors: features go into one +`Vector` column, and a fitted model scores a frame. + ## Install ```elixir def deps do [ - {:latu, "~> 0.3"}, + {:latu, "~> 0.4"}, {:latu_ml, "~> 0.1"} ] end ``` -Requires Elixir ~> 1.20 and a Spark **4.2.0** Connect server — the same one Latu targets, and -the only one either package claims. +Requires Elixir ~> 1.20 and a Spark **4.2.0** Connect server, the same one Latu targets. ## A server to talk to @@ -36,8 +38,8 @@ docker run -p 15002:15002 apache/spark:4.2.0 \ ## The lines at the top of your file -`Latu.ML` is called qualified, the way `Latu` is. The operator groups are aliased because you -name one every time you build something, and they are PySpark's own grouping: +`Latu.ML` is called qualified, the way `Latu` is. There are seven operator groups, PySpark's own +grouping, and you name one every time you build something. Alias the ones you need: ```elixir alias Latu.ML @@ -65,34 +67,29 @@ features = ML.transform(assembler, training) end) ``` -Four things are happening there, and three of them are the whole package. `ML.transform/2` is a -**lazy builder** — it hands back a `Latu.DataFrame` and reaches no server. `ML.fit/2`, which -`ML.with_model/3` calls, is an **action**, and what it hands back is a reference into a -server-side cache rather than a value. And `ML.with_model/3` deletes that reference in an -`after`, because the BEAM has no finalizer to do it for you. +Three things there are the whole package. `ML.transform/2` is a **lazy builder**. It hands back a +`Latu.DataFrame` and reaches no server. `ML.fit/2` is an **action**, and what it hands back is a +reference into a server-side cache rather than a value. `ML.with_model/3` deletes that reference +in an `after`, because the BEAM has no finalizer to do it for you. -This page shows the shape of the API. The -[quick start](https://hexdocs.pm/latu_ml/quick-start.html) shows results, and every line of it -is executed by the test suite — which is why the numbers there can be trusted and the ones in a -README cannot. +The [quick start](https://hexdocs.pm/latu_ml/quick-start.html) is the same walk with the results +in it, executed against a live server. ## What is in it -**Every operator the 4.2.0 server exposes**, generated rather than transcribed: 111 rows -carrying 991 params, extracted from PySpark's own classes and the server's own Scala. That is -68 constructors — 42 estimators, 18 transformers, 6 evaluators and the 2 operators that are -neither — and 623 accessors across 64 model and summary modules. +**Every operator the 4.2.0 server exposes**, generated rather than transcribed: 111 rows carrying +991 params, read off PySpark's own classes and the server's own Scala. That is 68 constructors, +and 623 accessors across 64 model and summary modules. **The verbs.** `fit`, `transform`, `evaluate`, `attribute`, `attribute_frame`, `summary`, `save`, `load`, `delete`, `with_model`, `model_size`, `cache_info`, `clean_cache`. Actions return `{:ok, _} | {:error, %Latu.Error{}}` with `!` twins; builders return a struct or a `Latu.DataFrame`. -**Attributes off a fitted model**, as `Nx` tensors, `Latu.ML.SparseVector`s or lazy frames — -`coefficients`, `feature_importances`, cluster centres, a training summary's ROC curve. What -you may ask for is the server's own allowlist, and the generated accessor per class is the -discovery surface: `h Latu.ML.Regression.LinearRegressionTrainingSummary.r2` prints Spark's -own prose. +**Attributes off a fitted model**, as `Nx` tensors, `Latu.ML.SparseVector`s or lazy frames. +`coefficients`, `feature_importances`, cluster centres, a training summary's ROC curve. What you +may ask for is the server's own allowlist, and the generated accessor per class is the discovery +surface: `h Latu.ML.Regression.LinearRegressionTrainingSummary.r2` prints Spark's own prose. **Pipelines and tuning**, client-side on both sides of the wire because Spark exposes no `Fit` for either: `Latu.ML.pipeline/1`, `Latu.ML.param_grid/2`, `Latu.ML.cross_validator/1` and @@ -103,16 +100,12 @@ for either: `Latu.ML.pipeline/1`, `Latu.ML.param_grid/2`, `Latu.ML.cross_validat `Latu.ML.find_frequent_sequential_patterns/2`, and the model constructors that build a `StringIndexerModel` from labels or a `CountVectorizerModel` from a vocabulary. -**Two column functions**, `Latu.ML.Functions.vector_to_array/2` and -`Latu.ML.Functions.array_to_vector/1` — the way to read a `Vector` column, which -`Latu.collect/2` refuses because Spark describes it as a UDT and declines to say what it -serialises as. +**Two column functions**: `Latu.ML.Functions.vector_to_array/2` and +`Latu.ML.Functions.array_to_vector/1`. They are the way to read a `Vector` column, which +`Latu.collect/2` refuses: Spark describes it as a UDT and declines to say what it serialises as. -**Not here.** Anything closure-shaped — `predict_batch_udf`, and `xgboost.spark`, whose -training is Python code shipped to Python workers even on Connect. The RDD-era `spark.mllib`. -Building a model out of parameters you already hold: a model exists only by a fit or a read, -and there is no wire path for the other direction. `OneVsRest`. And the deprecated torch-based -`pyspark.ml.connect` package from 3.4 and 3.5, which is not what any of this mirrors. +**Not here.** Anything closure-shaped, the RDD-era `spark.mllib`, `OneVsRest`, and building a +model out of parameters you already hold. ## What this is @@ -125,47 +118,42 @@ Remote MLlib, not a local one. Two things are load-bearing: 2. **The surface is generated from two extractors and checked by a probe.** Constructors, params, accessors and their docs come from `priv/ml_operators.exs` and - `priv/ml_attributes.exs`, which are read off PySpark's classes and the server's `MLUtils` - rather than typed by hand. Every constructor's `@doc` says whether a live server has - actually run it — `:probed` or `:built` — so `h` tells you what is verified rather than what - is claimed. + `priv/ml_attributes.exs`. Those are read off PySpark's classes and the server's `MLUtils`, + not typed by hand. Every constructor's `@doc` says whether a live server has run it. `Scholar` runs classical ML on one node, in memory, and hands you a model you can inspect and ship. This runs MLlib on a cluster and hands you a reference. Reach for Scholar when the -training set fits a node; reach for this when it does not, or when the features already live in -a lakehouse. [With Nx and Scholar](https://hexdocs.pm/latu_ml/with-scholar-and-nx.html) is -that seam, measured. +training set fits a node; reach for this when it does not, or when the features already live in a +lakehouse. [With Nx and Scholar](https://hexdocs.pm/latu_ml/with-scholar-and-nx.html) is that +seam. ## Status **0.1.0, and pre-1.0 in the way that matters**: a minor version may rename or remove, and `CHANGELOG.md` carries the migration in one line when it does. -All 66 runnable operators are `:probed` — fitted, applied or evaluated against a live 4.2.0 -server, with every allowlisted attribute answered — and so are the eleven `ConnectHelper` -methods. No operator is `:missing`. Six saved directories cross over between PySpark and this -package in both directions. +Every runnable operator has been fitted, applied or evaluated against a live 4.2.0 server, with +every allowlisted attribute answered. ## Where to go next - * [Quick start](https://hexdocs.pm/latu_ml/quick-start.html) - — connect, fit, read, score, release; every line of it executed - * [Cookbook](https://hexdocs.pm/latu_ml/cookbook.html) - — a recipe per model family, and the ones for pipelines, grid search and cleaning up - * [Coming from PySpark ML](https://hexdocs.pm/latu_ml/from-pyspark-ml.html) - — the five differences that matter, and what a model *is* here - * [With Nx and Scholar](https://hexdocs.pm/latu_ml/with-scholar-and-nx.html) - — getting numbers back onto the BEAM, where that is worth it, and where it stops working - * [`docs/cheatsheet.cheatmd`](https://hexdocs.pm/latu_ml/cheatsheet.html) - — every verb on one page - * [`usage-rules.md`](https://hexdocs.pm/latu_ml/usage-rules.html) - — the short set of rules that are not guessable from the function names, in the + * [Quick start](https://hexdocs.pm/latu_ml/quick-start.html). Connect, fit, read, score, + release. Every line of it is executed. + * [Cookbook](https://hexdocs.pm/latu_ml/cookbook.html). A recipe per model family, and the ones + for pipelines, grid search and cleaning up. + * [Coming from PySpark ML](https://hexdocs.pm/latu_ml/from-pyspark-ml.html). The five + differences, and what a model *is* here. + * [With Nx and Scholar](https://hexdocs.pm/latu_ml/with-scholar-and-nx.html). Getting numbers + back onto the BEAM, and where that stops working. + * [Cheatsheet](https://hexdocs.pm/latu_ml/cheatsheet.html). Every verb on one page. + * [`usage-rules.md`](https://hexdocs.pm/latu_ml/usage-rules.html). The short set of rules that + are not guessable from the function names, in the [`usage_rules`](https://github.com/ash-project/usage_rules) convention, so an agent can sync - it into its context - * [`docs/deviations.md`](https://hexdocs.pm/latu_ml/deviations.html) - — every place the API departs from `pyspark.ml`, and why - * [`CONTRIBUTING.md`](https://hexdocs.pm/latu_ml/contributing.html) - — the servers, the two extractors, the oracle and the probe + it into its context. + * [`docs/deviations.md`](https://hexdocs.pm/latu_ml/deviations.html). Every place the API + departs from `pyspark.ml`, and why. + * [`CONTRIBUTING.md`](https://hexdocs.pm/latu_ml/contributing.html). The servers, the two + extractors, the oracle and the probe. Latu's own [docs](https://hexdocs.pm/latu) cover the DataFrame API this is built on; its [usage rules](https://hexdocs.pm/latu/usage-rules.html) are worth having in context alongside @@ -185,12 +173,7 @@ mix check.all # the above plus integration, against sc://localhost:15003 **Claude (Anthropic) wrote the overwhelming majority of the code, the tests and the documentation.** The maintainers set the scope, made the design calls, ran every gate and -reviewed the result — the same division as Latu's, stated for the same reason. - -What holds it up is the apparatus rather than the review: two extractors that reproduce the -committed registries byte for byte, a PySpark oracle that captures the protobuf PySpark *would* -have sent, a live probe that has run every operator, and `docs/decisions.md`, which records the -reasoning behind every non-obvious choice. +reviewed the result. The same division as Latu's, stated for the same reason. ## License diff --git a/docker-compose.yml b/docker-compose.yml index fcc6e9f..8a3213e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -11,7 +11,7 @@ # dev/docker-compose.ext.yml. services: spark-connect: - image: apache/spark:4.2.0 + image: apache/spark:${SPARK_VERSION:-4.2.0} container_name: latu-ml-spark-connect ports: - "15002:15002" @@ -46,7 +46,7 @@ services: # it is worth having: a fit outlives the stream that carries it, so every ML command in the # suite goes through a reattach rather than only the ones a test writes for it. spark-reattach: - image: apache/spark:4.2.0 + image: apache/spark:${SPARK_VERSION:-4.2.0} container_name: latu-ml-spark-reattach ports: - "15003:15002" diff --git a/docs/guides/cookbook.md b/docs/guides/cookbook.md index f0b4d4c..a3ad5af 100644 --- a/docs/guides/cookbook.md +++ b/docs/guides/cookbook.md @@ -5,8 +5,7 @@ the page you come back to. Every `elixir` snippet here is executed by `mix check.all` (`test/integration/guides_test.exs`), in order, sharing one set of bindings and one session. The -pattern matches are the assertions. Every model fitted below is released before the page ends, -which is the point of the last recipe. +pattern matches are the assertions. Every model fitted below is released before the page ends. Where a recipe departs from PySpark, [`docs/deviations.md`](../deviations.md) has the reason. @@ -19,9 +18,9 @@ alias Latu.ML.{Classification, Clustering, Evaluation, Feature, Regression} {:ok, session} = Latu.connect("sc://localhost:15003") ``` -One frame carries the page. It has a binary `label` for the classifiers, a continuous `y` for -the regression, and two features — twelve rows, so that a two-fold search later on has -something to cut: +One frame carries the page. It has a binary `label` for the classifiers, a continuous `y` for the +regression, and two features. Twelve rows, so that a two-fold search later on has something to +cut: ```elixir data = @@ -40,7 +39,7 @@ data = ``` **Every estimator wants one `Vector` column.** `VectorAssembler` builds it, and applying it is a -lazy builder — the frame below has reached no server: +lazy builder. The frame below has reached no server: ```elixir assembler = Feature.vector_assembler(input_cols: [:x1, :x2], output_col: :features) @@ -51,8 +50,8 @@ features = ML.transform(assembler, data) ## A classifier, end to end -The shape every recipe on this page follows: build the estimator, fit it, read something off -it, score with it, release it. +The shape every recipe follows: build the estimator, fit it, read something off it, score with +it, release it. ```elixir alias Latu.ML.Classification.{BinaryLogisticRegressionSummary, LogisticRegressionModel} @@ -79,8 +78,8 @@ true = accuracy >= 0.0 and accuracy <= 1.0 ``` Scoring is a lazy builder too, so a scored frame composes like any other. **Select away the -`Vector` columns before collecting** — `features`, `rawPrediction` and `probability` are UDTs -the decoder refuses: +`Vector` columns before collecting**: `features`, `rawPrediction` and `probability` are UDTs the +decoder refuses: ```elixir scored = ML.transform(model, features) @@ -116,9 +115,9 @@ alias Latu.ML.Regression.{LinearRegressionModel, LinearRegressionTrainingSummary {2} = Nx.shape(weights) ``` -A regression summary is where the diagnostics live, and it is worth knowing which of them are -values and which are frames. `r2` is a number and arrives with `{:ok, _}`; `residuals` is a -`Latu.DataFrame` and has run nothing yet: +A regression summary is where the diagnostics live. Some of it is values and some of it is +frames. `r2` is a number and arrives with `{:ok, _}`; `residuals` is a `Latu.DataFrame` and has +run nothing yet: ```elixir fit_summary = ML.summary(linear) @@ -159,7 +158,7 @@ true = nodes >= 3 `feature_importances` is the one attribute on this page that does **not** come back as a tensor. Spark builds it with `Vectors.sparse`, because a tree usually ignores some of its features, and -this package never densifies for you — a vector that is sparse is generally sparse on purpose: +this package never densifies for you. A vector that is sparse is generally sparse on purpose: ```elixir {:ok, importances} = DecisionTreeClassificationModel.feature_importances(tree) @@ -171,10 +170,10 @@ this package never densifies for you — a vector that is sparse is generally sp `Latu.ML.SparseVector.to_dense/1` is the caller's decision, and `Nx` is where it lands. -**What you cannot get is the tree itself.** The server's allowlist gives a tree its depth, its -node count, its feature importances and the four `predict*` methods — one round trip per row, -so not a scoring path — and `to_debug_string`, which is a text dump with no compatibility -promise. There is no node table and no thresholds as data: +**What you cannot get is the tree itself.** The allowlist gives a tree its depth, its node count, +its feature importances, the four `predict*` methods and `to_debug_string`. The `predict*` methods +are one round trip per row, so not a scoring path. The debug string has no compatibility promise. +There is no node table and no thresholds as data: ```elixir {:ok, dump} = DecisionTreeClassificationModel.to_debug_string(tree) @@ -182,10 +181,9 @@ promise. There is no node table and no thresholds as data: true = is_binary(dump) ``` -So a tree is scored where it lives, with `Latu.ML.transform/2`. That is not a limitation of -this package — it is the same for PySpark, and it is why the -[Nx and Scholar guide](with-scholar-and-nx.md) says the parameters-out seam ends at the model -families whose parameters *are* the model. +So a tree is scored where it lives, with `Latu.ML.transform/2`. The parameters-out seam in +[With Nx and Scholar](with-scholar-and-nx.md) ends at the model families whose parameters *are* +the model. An ensemble adds one shape worth knowing: `trees` answers with a list of **cache entries**, one per tree, and they are yours to give back. @@ -222,8 +220,8 @@ alias Latu.ML.Clustering.{KMeansModel, KMeansSummary} {2, 2} = Nx.shape(centres) ``` -A `Matrix` comes back row-major whatever Spark's `isTransposed` flag says — a storage flag is -not a shape. The summary carries the sizes and the cost: +A `Matrix` comes back row-major whatever Spark's `isTransposed` flag says. A storage flag is not +a shape. The summary carries the sizes and the cost: ```elixir clustering = ML.summary(kmeans) @@ -240,9 +238,8 @@ true = cost >= 0.0 ## A pipeline, saved and read back -`Pipeline` has no `Fit` on the wire — Spark exposes none — so both PySpark and this package -fold over the stages themselves. Which means the thing that has to match between the two is not -the wire but the **on-disk format**. +`Pipeline` has no `Fit` on the wire, so both PySpark and this package fold over the stages +themselves. Which means the thing that has to match is the **on-disk format**, not the wire. ```elixir scaler = Feature.standard_scaler(input_col: :features, output_col: :scaled, with_mean: true) @@ -268,9 +265,9 @@ piped = ML.transform(fitted, data) 12 = length(piped_rows) ``` -Saving writes Spark's own directory layout to a path **on the server** — the write happens -where the session is, so a bare path is the driver's disk and anything a second machine has to -read wants a URL the cluster's filesystem understands: +Saving writes Spark's own directory layout to a path **on the server**. The write happens where +the session is, so a bare path is the driver's disk. Anything a second machine has to read wants a +URL the cluster's filesystem understands: ```elixir path = "/tmp/latu_ml_cookbook/#{System.unique_integer([:positive])}" @@ -281,18 +278,18 @@ path = "/tmp/latu_ml_cookbook/#{System.unique_integer([:positive])}" %Latu.ML.PipelineModel{stages: [_, _, _]} = reloaded ``` -A loaded model holds a **fresh cache reference** — reading one costs a cache entry exactly as -fitting one does — and it carries no training frame, so it has no summary and nothing to -rebuild one from. +A loaded model holds a **fresh cache reference**. Reading one costs a cache entry exactly as +fitting one does. It carries no training frame, so it has no summary and nothing to rebuild one +from. ```elixir :ok = ML.delete([fitted, reloaded]) ``` -Two things about that directory are worth knowing before you rely on it. Each stage underneath -is written by the *server*, so every stage is in Scala's own format and loads anywhere. The -wrapper is not: its metadata says `class: "pyspark.ml.pipeline.Pipeline"`, which Scala's reader -refuses — and refuses for PySpark's own saved pipelines too, for the same one key. +Two things about that directory before you rely on it. Each stage underneath is written by the +*server*, so every stage is in Scala's own format and loads anywhere. The wrapper is not: its +metadata says `class: "pyspark.ml.pipeline.Pipeline"`, which Scala's reader refuses. It refuses +PySpark's own saved pipelines too, for the same one key. ## Searching a grid @@ -306,9 +303,9 @@ grid = ML.param_grid(tuned, reg_param: [0.0, 0.1]) 2 = length(grid) ``` -The search itself is client code on both sides — folds cut with `rand(seed)` and range filters, -exactly as `CrossValidator._kFold` does it. Pass a `seed:`; without one the draw differs -between runs and the search is not repeatable: +The search itself is client code on both sides: folds cut with `rand(seed)` and range filters, +exactly as `CrossValidator._kFold` does it. Pass a `seed:`. Without one the draw differs between +runs and the search is not repeatable: ```elixir search = @@ -335,9 +332,8 @@ as their metrics are read, unless you asked for them with `collect_sub_models: t :ok = ML.delete(best) ``` -`Latu.ML.larger_better?/1` is what decides argmax from argmin, and it is pure: the server's -allowlist has no `isLargerBetter`, so PySpark overrides it client-side too and the extractor -reads those overrides into the registry. +`Latu.ML.larger_better?/1` decides argmax from argmin, and it is pure. The server's allowlist has +no `isLargerBetter`, so the registry carries PySpark's own client-side overrides. ```elixir true = ML.larger_better?(Evaluation.binary_classification_evaluator()) @@ -348,8 +344,8 @@ false = ML.larger_better?(Evaluation.regression_evaluator(metric_name: "rmse")) A model is a server-side resource with no finalizer behind it. Three things help. -`Latu.ML.with_model/3` is the bracket — acquire, use, release in an `after` — and it is the -right shape whenever the handle does not have to outlive the expression: +`Latu.ML.with_model/3` is the bracket: acquire, use, release in an `after`. It is the right shape +whenever the handle does not have to outlive the expression: ```elixir {:ok, bracketed} = @@ -361,8 +357,7 @@ true = is_float(bracketed) ``` `Latu.ML.cache_info/1` says what the session is actually holding, and `Latu.ML.model_size/1` -what one entry costs. Both are the answer to "did I leak something", and every recipe above -deleted what it fitted: +what one entry costs. Every recipe above deleted what it fitted: ```elixir {:ok, entries} = ML.cache_info(session) @@ -370,8 +365,8 @@ deleted what it fitted: [] = entries ``` -`Latu.ML.clean_cache/1` empties the lot, and answers with how many entries it freed rather than -a bare `:ok` — an empty cache is a legitimate zero: +`Latu.ML.clean_cache/1` empties the lot, and answers with how many entries it freed rather than a +bare `:ok`. An empty cache is a legitimate zero: ```elixir {:ok, 0} = ML.clean_cache(session) @@ -385,6 +380,6 @@ Latu.disconnect(session, release: true) ## Where to go next - * [Coming from PySpark ML](from-pyspark-ml.md) — the five differences, and what a model *is* - * [With Nx and Scholar](with-scholar-and-nx.md) — the seam back onto the BEAM, measured - * [`docs/deviations.md`](../deviations.md) — the spelling table, and the reason for each row + * [Coming from PySpark ML](from-pyspark-ml.md). The five differences, and what a model *is*. + * [With Nx and Scholar](with-scholar-and-nx.md). The seam back onto the BEAM, and where it ends. + * [`docs/deviations.md`](../deviations.md). The spelling table, and the reason for each row. diff --git a/docs/guides/from-pyspark-ml.md b/docs/guides/from-pyspark-ml.md index 8b838a1..49e41c1 100644 --- a/docs/guides/from-pyspark-ml.md +++ b/docs/guides/from-pyspark-ml.md @@ -4,9 +4,9 @@ whole: the same operators, the same params, the same on-disk format. What changes is what a *model* is in your program. -Five differences account for nearly everything. The spelling — `maxIter` to `max_iter`, and -twenty-five more rows — is [`docs/deviations.md`](../deviations.md), which also carries the -reason for each. +Five differences account for nearly everything. The spelling is +[`docs/deviations.md`](../deviations.md): `maxIter` to `max_iter`, and twenty-five more rows, each +with its reason. Every `elixir` snippet here is executed by `mix check.all` (`test/integration/guides_test.exs`). @@ -33,13 +33,12 @@ features = ML.transform(assembler, training) ## 1. A model is not a value In PySpark a fitted model is an object in your process. On Connect it holds a reference to a -server-side one, and a refcount frees it in `__del__` when the last name goes out of scope — so -the lifetime is invisible and you never think about it. +server-side one, and a refcount frees it in `__del__` when the last name goes out of scope. The +lifetime is invisible and you never think about it. -Here it is visible on purpose. `ML.fit/2` hands back a `%Latu.ML.Model{}`, which is a reference -into a per-session cache: inert data on the BEAM, and something real on the server that stays -real until you say otherwise. The BEAM has no finalizers, so there is nothing to hook — and -faking one would need a process or a NIF resource, neither of which this package holds. +Here it is visible on purpose. `ML.fit/2` hands back a `%Latu.ML.Model{}`, a reference into a +per-session cache: inert data on the BEAM, something real on the server. It stays real until you +say otherwise, and the BEAM has no finalizers, so there is nothing to hook. So the model has to be released, and the shape for that is a bracket: @@ -53,9 +52,8 @@ true = is_float(bracketed) ``` `with_model/3` deletes in an `after`, so a raise in the body still releases. When the handle has -to outlive the expression, `fit/2` and `delete/1` are the pair — and `delete/1` on a -`PipelineModel` or a search result empties the whole tree, because those own the models inside -them: +to outlive the expression, `fit/2` and `delete/1` are the pair. `delete/1` on a `PipelineModel` or +a search result empties the whole tree, because those own the models inside them: ```elixir {:ok, model} = ML.fit(Classification.logistic_regression(max_iter: 10), features) @@ -64,14 +62,10 @@ them: {2} = Nx.shape(coefficients) ``` -What you do *not* have to worry about is eviction. A model is offloaded to disk under memory -pressure and comes back transparently; over budget it is the **fit** that is refused rather than -something already held being dropped. A `%Latu.ML.Model{}` does not go stale underneath you. - ## 2. An attribute is an action, and the server has an allowlist `model.coefficients` is a property in PySpark that raises on failure. It is a round trip either -way — but here it is spelled as one: +way. Here it is spelled as one: ```elixir {:ok, intercept} = ML.attribute(model, :intercept) @@ -79,9 +73,9 @@ true = is_float(intercept) ``` The `{:ok, _}` is Latu's convention for anything that reaches the server, and there is a `!` -twin. What is new is that **the server decides what you may ask for**. `MLUtils` holds an -allowlist per class, and anything outside it is `CONNECT_ML.ATTRIBUTE_NOT_ALLOWED` — so the set -is not "whatever PySpark exposes": +twin. **The server decides what you may ask for.** `MLUtils` holds an +allowlist per class, and anything outside it is `CONNECT_ML.ATTRIBUTE_NOT_ALLOWED`. The set is +not "whatever PySpark exposes": ```elixir allowed = ML.attributes(Classification.LogisticRegressionModel) @@ -90,11 +84,11 @@ true = :coefficients in Enum.map(allowed, & &1.name) true = length(allowed) > 5 ``` -**Reach for the generated accessor first.** There is one function per allowlisted attribute, on -a module per model class, carrying the class and the wire name and Spark's own docs — so -`h LogisticRegressionModel.coefficients` tells you what Spark says, and tab completion is the -discovery surface. `ML.attribute/2` underneath takes the **wire** name, which is why -`:coefficients` works and `:area_under_roc` would not; the accessor is what translates. +**Reach for the generated accessor first.** There is one function per allowlisted attribute, on a +module per model class, carrying the class, the wire name and Spark's own docs. So +`h LogisticRegressionModel.coefficients` tells you what Spark says. `ML.attribute/2` underneath +takes the **wire** name, which is why +`:coefficients` works and `:area_under_roc` would not. ## 3. A Vector column does not come back as a vector @@ -132,13 +126,13 @@ server so the column arrives as an ordinary `array` any reader takes: [_, _] = hd(rows).v ``` -`select` or `drop` the Vector columns is the third way, and often the right one — a prediction +`select` or `drop` the Vector columns is the third way, and often the right one. A prediction column is a double and was never the problem. ## 4. A summary is a second object, and the cache drops it -`model.summary` is a property in PySpark. Here it is a lazy handle to another server-side -object, reached by asking the model — Spark has no separate cache key for one: +`model.summary` is a property in PySpark. Here it is a lazy handle to another server-side object, +reached by asking the model. Spark has no separate cache key for one: ```elixir summary = ML.summary(model) @@ -148,12 +142,12 @@ true = is_float(area) and area >= 0.0 and area <= 1.0 ``` The part worth knowing: a model is *offloaded* under memory pressure, but a summary is -**dropped** — a model's save format does not carry one, so the model that comes back from disk -has none. The fetch then throws `CONNECT_ML.MODEL_SUMMARY_LOST`, and this package does what -PySpark does: rebuilds the summary from the training frame and asks again, once. +**dropped**. A model's save format does not carry one, so the model that comes back from disk has +none. The fetch then throws `CONNECT_ML.MODEL_SUMMARY_LOST`, and this package does what PySpark +does: rebuilds the summary from the training frame and asks again, once. Except where there is no frame. A model from `load/3` never saw the data, so nothing can be -rebuilt and the server's refusal stands — which is the one case the recovery must not fire on. +rebuilt and the server's refusal stands. That is the one case the recovery must not fire on. ```elixir :ok = ML.delete(model) @@ -163,7 +157,7 @@ rebuilt and the server's refusal stands — which is the one case the recovery m `Pipeline`, `CrossValidator` and `TrainValidationSplit` have no `Fit` on the wire. PySpark loops over the stages itself, cuts folds with `rand(seed)` and range filters, and writes the layout by -hand — and so does this. The two are the same shape: +hand. So does this. The two are the same shape: ```elixir %Latu.ML.Pipeline{stages: [_assembler, _lr]} = @@ -173,10 +167,9 @@ grid = ML.param_grid(Classification.logistic_regression(), reg_param: [0.0, 0.1] 2 = length(grid) ``` -Because both sides are client code, **the wire is not what has to match — the format is**. A -grid entry here carries the uid of the operator it sets, since the thing searched is usually a -pipeline and a param belongs to one stage of it. `dev/README.md` has the interop dance: PySpark -reads what this wrote, and the reverse, for six different directories. +Because both sides are client code, **the wire is not what has to match; the format is**. A grid +entry here carries the uid of the operator it sets, since the thing searched is usually a pipeline +and a param belongs to one stage of it. `dev/README.md` has the interop dance. ## Discovery: the registry, not the docs @@ -189,25 +182,21 @@ true = length(ML.operators()) > 100 [_ | _] = ML.params(:logistic_regression) ``` -Every constructor's `@doc` opens with whether a live server has actually run it — `:probed`, -`:built` or `:missing` — so `h Classification.logistic_regression` tells you what is verified -rather than what is claimed. - ## Things deliberately not here Anything closure-shaped, because there is no way to ship an Elixir function to a Python worker: `predict_batch_udf`, and `xgboost.spark`, whose training is Python code even on Connect. The -RDD-era `spark.mllib`. Building a model from parameters you hold — a model exists only by a fit -or a read, and there is no wire path for the other direction. `OneVsRest`, which shares nothing -with the validators but the word *meta-algorithm*. And the deprecated torch-based -`pyspark.ml.connect` package from 3.4 and 3.5, which is not what any of this mirrors. +RDD-era `spark.mllib`. Building a model from parameters you hold: a model exists only by a fit or +a read, and there is no wire path for the other direction. `OneVsRest`, which shares nothing with +the validators but the word *meta-algorithm*. And the deprecated torch-based `pyspark.ml.connect` +package from 3.4 and 3.5. `Summarizer` is reachable but not wrapped: its `aggregate_metrics` resolves, and reading one metric out of the struct it answers with needs field access Latu does not build yet. ## Where to go next -[With Nx and Scholar](with-scholar-and-nx.md) is the other direction — getting numbers back onto +[With Nx and Scholar](with-scholar-and-nx.md) is the other direction: getting numbers back onto the BEAM, and where that stops working. [`docs/deviations.md`](../deviations.md) is the spelling table and the reasons. diff --git a/docs/guides/quick-start.md b/docs/guides/quick-start.md index 5ec672d..f7bb35b 100644 --- a/docs/guides/quick-start.md +++ b/docs/guides/quick-start.md @@ -5,7 +5,7 @@ files on disk. Every `elixir` snippet on this page is executed by `mix check.all` (`test/integration/guides_test.exs`), in order, sharing one set of bindings. The pattern matches -are the assertions — `{2} = Nx.shape(coefficients)` is documentation and a test at once. +are the assertions. `{2} = Nx.shape(coefficients)` is documentation and a test at once. This assumes Latu itself is familiar; if it is not, [Latu's quick start](https://hexdocs.pm/latu/quick-start.html) comes first. @@ -44,9 +44,8 @@ training = ## Assembling features -Every MLlib estimator wants its features in **one** column, of Spark's `Vector` type. -`VectorAssembler` is the transformer that builds one, and applying it is a lazy builder: -nothing has reached the server yet. +Every MLlib estimator wants its features in **one** `Vector` column. `VectorAssembler` builds +one, and applying it is a lazy builder: nothing has reached the server yet. ```elixir assembler = Feature.vector_assembler(input_cols: [:x1, :x2], output_col: :features) @@ -55,7 +54,7 @@ features = ML.transform(assembler, training) ["label", "x1", "x2", "features"] = Latu.columns!(features) ``` -`Latu.columns!/1` answered without running anything — a `Transform` is a relation, so the schema +`Latu.columns!/1` answered without running anything. A `Transform` is a relation, so the schema comes back from an analyse rather than an execution. ## Fitting @@ -70,16 +69,15 @@ lr = Classification.logistic_regression(max_iter: 10, reg_param: 0.01) %Latu.ML.Model{class: "org.apache.spark.ml.classification.LogisticRegressionModel"} = model ``` -Params are Elixir-spelled and only what you set is sent — `max_iter:` is `maxIter` on the wire, +Params are Elixir-spelled, and only what you set is sent. `max_iter:` is `maxIter` on the wire, and the server fills in every default you left alone. A value of the wrong **kind** is refused -here; a value out of **range** is Spark's own `ParamValidators` to refuse, with a better message -than this package could write. +here. A value out of **range** is Spark's own `ParamValidators` to refuse. ## Reading the model -What you may ask a model for is the server's own allowlist, and there is a generated accessor -per allowlisted attribute on a module per class. Reach for the accessor: it carries the class, -the wire name and Spark's own docs, so tab completion is the discovery surface. +What you may ask a model for is the server's own allowlist. There is a generated accessor per +allowlisted attribute, on a module per class. Reach for the accessor: it carries the class, the +wire name and Spark's own docs, so tab completion is the discovery surface. ```elixir alias Latu.ML.Classification.LogisticRegressionModel @@ -93,8 +91,7 @@ true = is_float(intercept) A `Vector` comes back as an `Nx.Tensor`; a sparse one comes back as a `Latu.ML.SparseVector`, never silently densified. `ML.attribute/2` is the generic verb underneath, and it takes either -spelling — the snake_case name the registry advertises, or the camelCase one the allowlist -holds: +spelling: the snake_case name the registry advertises, or the camelCase one the allowlist holds: ```elixir {:ok, ^intercept} = ML.attribute(model, :intercept) @@ -103,9 +100,8 @@ holds: ## The training summary -Ten of the 43 model classes record one. It is a second server-side object, reached lazily off -the model — Spark has no separate cache key for it, so nothing is sent until you ask it -something: +Ten of the 43 model classes record one. It is a second server-side object, reached lazily off the +model. Spark has no separate cache key for it, so nothing is sent until you ask it something: ```elixir summary = ML.summary(model) @@ -135,10 +131,10 @@ scored = ML.transform(model, features) 6 = length(rows) ``` -Note the `select`. **A `Vector` column cannot be collected**: on 4.2.0 the server describes -`features`, `rawPrediction` and `probability` as UDTs with no SQL type, so Latu's dtype guard -refuses them rather than guessing a layout. `Latu.to_nx/2` reads the Arrow bytes, where the type -*is* stated: +Note the `select`. **A `Vector` column cannot be collected.** On 4.2.0 the server describes +`features`, `rawPrediction` and `probability` as UDTs with no SQL type. Latu's dtype guard refuses +them rather than guessing a layout. `Latu.to_nx/2` reads the Arrow bytes, where the type *is* +stated: ```elixir {:ok, %{"features" => x}} = Latu.to_nx(features, columns: ["features"]) @@ -146,8 +142,8 @@ refuses them rather than guessing a layout. `Latu.to_nx/2` reads the Arrow bytes {6, 2} = Nx.shape(x) ``` -An evaluator scores a frame and answers with one number. It is inert data, so a second metric -is a second value rather than an override at the call site: +An evaluator is inert data, so a second metric is a second value rather than an override at the +call site: ```elixir {:ok, auc} = ML.evaluate(Evaluation.binary_classification_evaluator(), scored) @@ -178,10 +174,6 @@ true = is_float(bracketed) {:ok, []} = ML.cache_info(session) ``` -What you do **not** have to worry about is eviction. A model is offloaded to disk under memory -pressure and comes back transparently; over budget it is the *fit* that is refused rather than -something already held being dropped. A `Latu.ML.Model` does not go stale underneath you. - ## The registry, which needs no server at all Every operator, param and attribute is data in the package, and queryable: @@ -193,10 +185,7 @@ true = length(ML.operators()) > 100 [_ | _] = ML.attributes(LogisticRegressionModel) ``` -`ML.operators/1` also filters on `status:` — `:probed` for an operator a live server has -actually run, `:built` for one generated from PySpark's param table and not yet exercised. Every -constructor's `@doc` opens with its status, so `h Classification.logistic_regression` tells you -what is verified rather than what is claimed. +Then hand the session back: ```elixir Latu.disconnect(session, release: true) @@ -204,10 +193,10 @@ Latu.disconnect(session, release: true) ## Where to go next - * [Cookbook](cookbook.md) — a recipe per model family, plus pipelines, grid search and - cleaning up - * [Coming from PySpark ML](from-pyspark-ml.md) — the five differences, if MLlib is already - familiar - * [With Nx and Scholar](with-scholar-and-nx.md) — the seam back onto the BEAM, measured - * [`usage-rules.md`](../../usage-rules.md) — the rules that are not guessable from the - function names + * [Cookbook](cookbook.md). A recipe per model family, plus pipelines, grid search and cleaning + up. + * [Coming from PySpark ML](from-pyspark-ml.md). The five differences, if MLlib is already + familiar. + * [With Nx and Scholar](with-scholar-and-nx.md). The seam back onto the BEAM, and where it ends. + * [`usage-rules.md`](../../usage-rules.md). The rules that are not guessable from the function + names. diff --git a/docs/guides/with-scholar-and-nx.md b/docs/guides/with-scholar-and-nx.md index 7fbbfd9..ef82b35 100644 --- a/docs/guides/with-scholar-and-nx.md +++ b/docs/guides/with-scholar-and-nx.md @@ -5,8 +5,8 @@ onto the BEAM, where `Nx`, `Scholar` and `defn` live. Three things can cross, and they are not equally easy. **Features** come back as tensors. **Fitted parameters** come back as tensors, and for some model families that is the whole model. -**The model itself** does not cross at all — and knowing which family you are in is most of what -this page is for. +**The model itself** does not cross at all. Knowing which family you are in is most of what this +page is for. Every fence below runs against a live server as part of the test suite. @@ -33,17 +33,16 @@ features = ML.transform(assembler, training) ## Features out -A `features` column is a `Vector`, and a Vector column is the one thing in Spark that -`Latu.collect/2` will not give you: +A `features` column is a `Vector`. That is the one thing in Spark that `Latu.collect/2` will not +give you: ```elixir {:error, refused} = Latu.collect(features) true = refused.message =~ "UDT that does not say its SQL type" ``` -That is not Latu being fussy. Spark describes the column as a UDT and declines to say what it -serialises as, so the decoder has nothing to check against Polars' dtypes and refuses rather than -risk a panic that would name neither the column nor the type. `docs/deviations.md` has the whole +Spark describes the column as a UDT and declines to say what it serialises as. The decoder has +nothing to check it against, so it refuses rather than guess. `docs/deviations.md` has the whole of it. `Latu.to_nx/2` reads the Arrow bytes directly, where the type *is* stated, and hands back one @@ -57,22 +56,7 @@ of it. [1.0, 1.0, 2.0, 2.0] = rows |> Nx.slice([0, 0], [2, 2]) |> Nx.to_flat_list() ``` -For a **single** batch this costs no copy: the Arrow buffer *is* the tensor's binary. Two things -qualify that. Ask for a subset with `columns:` and it copies, deliberately — an Arrow buffer is a -slice of the whole batch and holds it alive, so pruning without copying would keep every column -you asked to drop. And a result that arrives in several batches is concatenated into one buffer -per column, so the blobs and the tensor are both live: measured at 100 MB of doubles, that is -about twice the payload in BEAM binary (`dev/probe_nx_copies.exs` in Latu). - -**On a plain numeric column that makes `to_nx/2` a convenience, not a saving** — the same probe -put it within a few percent of `to_explorer/2` plus `Explorer.Series.to_tensor/1` on wall time, -and slightly *above* it on peak memory. Reach for it there because a tensor is what you wanted, -not because it is cheaper. - -**On a `Vector` column it is a different regime.** At 100 MB of payload the routes that existed -before it peaked at 1682 MB and 1979 MB of BEAM against `to_nx/2`'s 135 MB — twelve to fifteen -times — and took about twice as long. Both of them materialise every row as a list of boxed -floats before `Nx.tensor/1` walks it; `to_nx/2` reads the buffer. +For a single batch this costs no copy: the Arrow buffer *is* the tensor's binary. **When you want a DataFrame rather than a tensor**, go through Spark instead. `Functions.vector_to_array/2` turns the Vector into an ordinary `array` server-side, and @@ -85,19 +69,12 @@ arrays = Latu.select(features, [:label, x: Functions.vector_to_array(:features)] 6 = Explorer.DataFrame.n_rows(frame) ``` -That costs a pass over the rows on the server, where `to_nx/2` costs none. Use it when the -destination is Explorer; use `to_nx/2` when the destination is a tensor. - -The split matters more than it looks. Decoding to a *frame* this way is cheap — 119 MB at the -100 MB size, against `to_nx/2`'s 135 MB. It is only carrying on from the frame to a tensor, row -by row, that costs the 1682 MB above. So `vector_to_array` is the right answer for Explorer and -the wrong one for `Nx`. +`vector_to_array` is the right answer for Explorer and the wrong one for `Nx`. ## Parameters out For the model families where the parameters *are* the model, the fit happens on the cluster and -the scoring happens here. A linear model is the clearest case — it is a dot product and an -intercept. +the scoring happens here. A linear model is the clearest case: a dot product and an intercept. ```elixir {:ok, model} = ML.fit(Regression.linear_regression(max_iter: 20), features) @@ -113,7 +90,7 @@ true = is_float(intercept) ### The one thing to get right `Nx.tensor(2.0)` is **f32**. A bare Elixir float entering `defn` becomes an f32 tensor, and an -f32 intercept costs about 1e-7 of precision — enough that your predictions and Spark's quietly +f32 intercept costs about 1e-7 of precision. Enough that your predictions and Spark's quietly disagree in the eighth decimal. `Latu.ML.Linalg` builds the coefficients as f64, so the vector is already right and only the scalar bites: @@ -149,7 +126,7 @@ scored = ML.transform(model, features) ``` Then score, and compare. Both sides used the same coefficients, so a mismatch here is arithmetic -and nothing else — which is what makes it worth asserting rather than eyeballing: +and nothing else. Worth asserting rather than eyeballing: ```elixir ours = Linear.predict(x, coefficients, intercept) @@ -158,7 +135,7 @@ ours = Linear.predict(x, coefficients, intercept) ``` The tensors are ordinary BEAM terms, so they outlive the handle they came from. Delete the model -and the scoring still works — that is the point of this seam: +and the scoring still works. That is the point of this seam: ```elixir :ok = ML.delete(model) @@ -175,22 +152,19 @@ train on a cluster and predict in a GenServer. ## Where this stops working -It stops at models that are a *structure* rather than a set of parameters — trees above all. +It stops at models that are a *structure* rather than a set of parameters. Trees above all. -What the server's allowlist gives a fitted tree is `depth`, `num_nodes`, `total_num_nodes`, -`num_features`, `num_classes`, `feature_importances`, `tree_weights`, `trees`, `get_num_trees`, -the four `predict*` methods, and `to_debug_string`. **No node table, and no thresholds as data.** -The splits cross only inside `to_debug_string`, which is a text dump with no compatibility -promise, and the `predict*` methods are one round trip per row, so they are an inspection tool -rather than a scoring path. +What the server's allowlist gives a fitted tree is its shape: `depth`, `num_nodes`, +`feature_importances`, and `to_debug_string`. **No node table, and no thresholds as data.** The +splits cross only inside `to_debug_string`, which is a text dump with no compatibility promise. -Scholar does not close the gap from its side either: it has no decision tree, random forest or -gradient-boosted tree at all — they do not express as `defn`, and Scholar's own README points at +Scholar does not close the gap from its side either. It has no decision tree, random forest or +gradient-boosted tree at all. They do not express as `defn`, and Scholar's own README points at EXGBoost instead. So there are three honest answers for a tree, and none of them is "port the model": -* **Score on the cluster** with `ML.transform/2`. Not a workaround — Spark already holds the +* **Score on the cluster** with `ML.transform/2`. Not a workaround. Spark already holds the structure, and for a tree that structure is the model. * **`ML.save/3` and read the artefact.** Spark's on-disk format carries the node table as Parquet, which Explorer reads. A real route, and a project rather than an afternoon. @@ -198,21 +172,20 @@ So there are three honest answers for a tree, and none of them is "port the mode ## Scholar, and when to reach for it instead -Scholar and `latu_ml` share their verbs — `fit`, `transform` — and disagree about what a model +Scholar and `latu_ml` share their verbs, `fit` and `transform`, and disagree about what a model *is*. Scholar's is a struct of tensors you can inspect, ship and pattern-match. This package's is a reference into a server-side cache that offloads under memory pressure and is gone when the session ends. Choose Scholar when the training set fits one node. Choose this when it does not, or when the -features already live in a lakehouse and moving them would cost more than the fit. And when you -have trained here and want to predict there, the seam above is the road: parameters out as -tensors, scoring in `defn`. +features already live in a lakehouse and moving them would cost more than the fit. Trained here +and predicting there, the seam above is the road. ## What `to_nx/2` will not read -A tensor has one type and one shape, so anything without both is refused by name rather than -guessed at: nulls, strings, booleans (Arrow packs them as a bitmap rather than a byte a value), -lists whose rows differ in length, and sparse `Vector`s. +A tensor has one type and one shape. Anything without both is refused by name rather than guessed +at: nulls, strings, booleans, lists whose rows differ in length, and sparse `Vector`s. Arrow packs +booleans as a bitmap, not one byte per value. ```elixir strings = Latu.sql!(session, "SELECT 'a' AS s") @@ -220,8 +193,8 @@ strings = Latu.sql!(session, "SELECT 'a' AS s") true = why.message =~ "column s is a string column" ``` -A sparse Vector is the one worth planning around: densify it on the server before you read it, -because there is no one width to reshape to. +A sparse Vector is the one worth planning around. Densify it on the server before you read it: +there is no one width to reshape to. ```elixir Latu.disconnect(session, release: true) diff --git a/lib/latu/ml.ex b/lib/latu/ml.ex index 0eb6874..9c685dd 100644 --- a/lib/latu/ml.ex +++ b/lib/latu/ml.ex @@ -97,6 +97,10 @@ defmodule Latu.ML do """ @type loadable :: atom() | {String.t(), Plan.kind()} + # ============================================= + # Fitting + # ============================================= + @doc """ Fit an estimator, or a whole pipeline, on a frame. @@ -295,6 +299,10 @@ defmodule Latu.ML do "a model already fitted, or another pipeline." end + # ============================================= + # Transform and evaluate + # ============================================= + @doc """ Apply a transformer or a fitted model to a frame. @@ -405,6 +413,10 @@ defmodule Latu.ML do """ @type param_map :: [{String.t(), atom(), term()}] + # ============================================= + # Grid search + # ============================================= + @doc """ A grid of params to try, as data. @@ -671,6 +683,10 @@ defmodule Latu.ML do {required, Keyword.drop(opts, [:estimator, :param_maps, :evaluator])} end + # ============================================= + # Operators that are neither fitted nor applied + # ============================================= + @doc """ Assign a cluster to every vertex of an affinity matrix — Power Iteration Clustering. @@ -728,6 +744,10 @@ defmodule Latu.ML do raise ArgumentError, "that verb is #{expected}'s, and this operator is a #{actual}" end + # ============================================= + # Attributes + # ============================================= + @doc """ Read a model attribute whose answer is a value — a coefficient, an intercept, a count. @@ -862,6 +882,10 @@ defmodule Latu.ML do } end + # ============================================= + # The helper object + # ============================================= + @doc """ Call a method on the server's own helper object. @@ -941,6 +965,10 @@ defmodule Latu.ML do %DataFrame{session: Internal.frame_of!(row, args).session, plan: plan} end + # ============================================= + # Summaries + # ============================================= + @doc """ The training summary a fitted model carries. @@ -962,6 +990,10 @@ defmodule Latu.ML do @spec summary(Model.t()) :: Summary.t() def summary(%Model{} = model), do: Internal.summary(model) + # ============================================= + # Saving + # ============================================= + @doc """ Write a model or an unfitted operator to a path, in Spark's own on-disk format. @@ -1277,6 +1309,10 @@ defmodule Latu.ML do "session: to say which server to write it to." end + # ============================================= + # Loading + # ============================================= + @doc """ Read a model or an operator back from a path. @@ -1620,6 +1656,10 @@ defmodule Latu.ML do defp cached?(_info, _kind, _class), do: :ok + # ============================================= + # The model cache + # ============================================= + @doc """ Release a model, or a list of them, from the server's ML cache. @@ -1894,6 +1934,10 @@ defmodule Latu.ML do "CONNECT_ML.ML_CACHE_SIZE_OVERFLOW_EXCEPTION" => :cache_full } + # ============================================= + # Errors + # ============================================= + @doc """ Which ML failure this is, as an atom, or `nil` for anything that is not one. @@ -1973,6 +2017,10 @@ defmodule Latu.ML do defp hint_for(_unknown), do: nil + # ============================================= + # The registry, at runtime + # ============================================= + @doc """ Every operator this package knows, as `Latu.ML.Operator` structs. @@ -2101,6 +2149,11 @@ defmodule Latu.ML do end defp released(%PipelineModel{uid: uid}), do: "could not delete the models in #{uid}: " + defp released(%CrossValidatorModel{uid: uid}), do: "could not delete the models in #{uid}: " + + defp released(%TrainValidationSplitModel{uid: uid}), + do: "could not delete the models in #{uid}: " + defp released(%Model{ref: ref}), do: "could not delete model #{ref}: " defp released(models) when is_list(models), diff --git a/lib/latu/ml/generate.ex b/lib/latu/ml/generate.ex index 50388ff..075aa70 100644 --- a/lib/latu/ml/generate.ex +++ b/lib/latu/ml/generate.ex @@ -86,6 +86,8 @@ defmodule Latu.ML.Generate do # none of them by taste: # # * `:summary` answers with another cached object, and only `evaluate` is still that shape; + # * an attribute whose argument types nothing could read from PySpark, which `@reasons` + # calls `:untyped`; # * `toString`, for the reason `@skip` gives. # # An attribute that takes arguments is generated at `1 + length(args)`, with each argument's diff --git a/lib/latu/ml/internal.ex b/lib/latu/ml/internal.ex index 5c7ef01..d97b5e1 100644 --- a/lib/latu/ml/internal.ex +++ b/lib/latu/ml/internal.ex @@ -23,11 +23,6 @@ defmodule Latu.ML.Internal do @kinds [:estimator, :transformer, :evaluator, :model] - # What `load/4` can be asked for that has no `Read` behind it: a pipeline and a search are - # directories this package wrote, so they are read rather than loaded. Their "class" is - # PySpark's spelling of the format, which is what `Latu.ML.Layout` writes into the metadata - # and what `load/4` reads back — both to tell a nested pipeline from a stage, and to tell - # which of the two shapes a directory is. @doc """ Whether a bigger metric is a better one, for this evaluator. `Latu.ML.larger_better?/1`. @@ -250,14 +245,14 @@ defmodule Latu.ML.Internal do defp uids_of(%{uid: uid}) when is_binary(uid), do: [uid] defp uids_of(_operator), do: [] - @meta_algorithms %{ - pipeline: :pipeline, - pipeline_model: :pipeline_model, - cross_validator: :cross_validator, - cross_validator_model: :cross_validator_model, - train_validation_split: :train_validation_split, - train_validation_split_model: :train_validation_split_model - } + @meta_algorithms [ + :pipeline, + :pipeline_model, + :cross_validator, + :cross_validator_model, + :train_validation_split, + :train_validation_split_model + ] @type saveable :: Model.t() | Estimator.t() | Transformer.t() | Evaluator.t() @type loadable :: atom() | {String.t(), Plan.kind()} @@ -270,7 +265,7 @@ defmodule Latu.ML.Internal do nil row too, so nil alone cannot be the test. """ @spec meta_algorithms() :: [atom()] - def meta_algorithms, do: Map.keys(@meta_algorithms) + def meta_algorithms, do: @meta_algorithms @doc """ Build the operator a generated constructor stands for. @@ -533,8 +528,8 @@ defmodule Latu.ML.Internal do def loadable!({class, kind}) when is_binary(class) and kind in @kinds, do: {class, kind, nil} - def loadable!(name) when is_map_key(@meta_algorithms, name) do - {Latu.ML.Layout.class(name), Map.fetch!(@meta_algorithms, name), nil} + def loadable!(name) when name in @meta_algorithms do + {Latu.ML.Layout.class(name), name, nil} end def loadable!(name) when is_atom(name) and not is_nil(name) do diff --git a/mix.exs b/mix.exs index b4801f2..c9b7ec7 100644 --- a/mix.exs +++ b/mix.exs @@ -38,7 +38,7 @@ defmodule Latu.ML.MixProject do defp deps do [ - {:latu, "~> 0.3"}, + {:latu, "~> 0.4"}, # Hard, not optional: a fitted model's attributes come back as tensors and there is no # useful surface here without them. Roadmap section 6. {:nx, "~> 0.13"}, @@ -51,6 +51,7 @@ defmodule Latu.ML.MixProject do licenses: ["Apache-2.0"], links: %{ "GitHub" => @source_url, + "Changelog" => "https://hexdocs.pm/latu_ml/changelog.html", "Latu" => "https://hexdocs.pm/latu", "MLlib" => "https://spark.apache.org/docs/latest/ml-guide.html" }, diff --git a/mix.lock b/mix.lock index 96aca29..ed06065 100644 --- a/mix.lock +++ b/mix.lock @@ -11,7 +11,7 @@ "grpc_core": {:hex, :grpc_core, "1.0.5", "add39a2ca38604f73c8b2feed30c0fd2d2291daedac8060ee1a75b5658f0a69d", [:mix], [{:googleapis, "~> 0.1.0", [hex: :googleapis, repo: "hexpm", optional: false]}, {:jason, ">= 0.0.0", [hex: :jason, repo: "hexpm", optional: false]}, {:protobuf, "~> 0.17", [hex: :protobuf, repo: "hexpm", optional: false]}, {:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "a18ae7380cfebc20271aad36393e8aa041e1faa926fa25f40328e4350f83d8f0"}, "gun": {:hex, :gun, "2.4.1", "c3a8bff8e155e1fc8e499216599bb7effbd27bc1985662a8b25016090dc18428", [:make, :rebar3], [{:cowlib, ">= 2.15.0 and < 3.0.0", [hex: :cowlib, repo: "hexpm", optional: false]}], "hexpm", "1450575b4d393aa0811322727b90ad1dd94b5c10026f54a1641785bcbd250384"}, "jason": {:hex, :jason, "1.4.5", "2e3a008590b0b8d7388c20293e9dcc9cf3e5d642fd2a114e4cbbb52e595d940a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "b0c823996102bcd0239b3c2444eb00409b72f6a140c1950bc8b457d836b30684"}, - "latu": {:hex, :latu, "0.3.0", "69f561c0d32cba35b7a222ad7a3f234f59d9958edfb4f3b6d6b6e0ecefa0156c", [:mix], [{:decimal, "~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:explorer, "~> 0.12", [hex: :explorer, repo: "hexpm", optional: false]}, {:grpc, "~> 1.0", [hex: :grpc, repo: "hexpm", optional: false]}, {:gun, "~> 2.4", [hex: :gun, repo: "hexpm", optional: false]}, {:kino, "~> 0.12", [hex: :kino, repo: "hexpm", optional: true]}, {:nx, "~> 0.13", [hex: :nx, repo: "hexpm", optional: true]}, {:protobuf, "~> 0.17", [hex: :protobuf, repo: "hexpm", optional: false]}, {:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "97258b47190f24276d3814c3f0031008f5e30a09ce446ab2ff4e4a41dac9aa8e"}, + "latu": {:hex, :latu, "0.4.0", "c779cfa5a86d5d25c1e6a0fbcbe3f4c49fae2fe945ac6e000444ea0f604029ec", [:mix], [{:decimal, "~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:explorer, "~> 0.12", [hex: :explorer, repo: "hexpm", optional: false]}, {:grpc, "~> 1.0", [hex: :grpc, repo: "hexpm", optional: false]}, {:gun, "~> 2.4", [hex: :gun, repo: "hexpm", optional: false]}, {:kino, "~> 0.12", [hex: :kino, repo: "hexpm", optional: true]}, {:nx, "~> 0.13", [hex: :nx, repo: "hexpm", optional: true]}, {:protobuf, "~> 0.17", [hex: :protobuf, repo: "hexpm", optional: false]}, {:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "2cc39a5e823e9ef1f80d1f4b33a0bb54f6bfe62fa0d5491020d889f0a6fd5f03"}, "makeup": {:hex, :makeup, "1.2.2", "882d46dc0905e9ff7abf2aab61a7e6b3dcc555533977d8a23b06019e6c89ac94", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "9a1a24e5b343b8ae16abea0822c10a6f75da27af7fa802ada5251f7579bfccfa"}, "makeup_elixir": {:hex, :makeup_elixir, "1.0.1", "e928a4f984e795e41e3abd27bfc09f51db16ab8ba1aebdba2b3a575437efafc2", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "7284900d412a3e5cfd97fdaed4f5ed389b8f2b4cb49efc0eb3bd10e2febf9507"}, "makeup_erlang": {:hex, :makeup_erlang, "1.1.0", "835f7e60792e08824cda445639555d7bf1bbbddb1b60b306e33cb6f6db24dc74", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "1cd6780fb1dd1a03979abaed0fe82712b0625118fd5257d3ebbf73f960c73c3c"}, diff --git a/usage-rules.md b/usage-rules.md index 1c535d3..f14cab7 100644 --- a/usage-rules.md +++ b/usage-rules.md @@ -5,8 +5,8 @@ side holds plans and handles. This file is the short set of rules that are not g the function names. It follows the `usage_rules` convention, so a consuming project can sync it into an agent's context. -**Latu's own [`usage-rules.md`](https://hexdocs.pm/latu/usage-rules.html) applies here in full** -— coercion, the `!` twins, errors, session config. What follows is the delta. Every deliberate +**Latu's own [`usage-rules.md`](https://hexdocs.pm/latu/usage-rules.html) applies here in full**: +coercion, the `!` twins, errors, session config. What follows is the delta. Every deliberate departure from `pyspark.ml` is in `docs/deviations.md`, with why. ## The three shapes @@ -14,7 +14,7 @@ departure from `pyspark.ml` is in `docs/deviations.md`, with why. Latu has two; this has three, and the third is the one that surprises. **A builder takes a struct and returns a struct.** Pure, no IO. `Latu.ML.pipeline/1`, -`Latu.ML.param_grid/2`, `Latu.ML.cross_validator/1`, and every generated constructor — +`Latu.ML.param_grid/2`, `Latu.ML.cross_validator/1`, and every generated constructor: `Latu.ML.Classification.logistic_regression/1` and its sixty-seven siblings. **An action runs something** and returns `{:ok, value} | {:error, %Latu.Error{}}`, with a `!` @@ -23,9 +23,9 @@ twin. `Latu.ML.fit/2`, `Latu.ML.evaluate/2`, `Latu.ML.attribute/2`, `Latu.ML.sav `Latu.ML.clean_cache/1`. **A relation builder returns a `Latu.DataFrame` and reaches no server.** `Latu.ML.transform/2` -is one — applying a transformer or a fitted model builds a plan, nothing more, and -`Latu.schema/1` answers on it without executing. So is `Latu.ML.attribute_frame/2` and every -generated accessor for a DataFrame-valued attribute, and so are `Latu.ML.Stat`'s three tests and +is one. Applying a transformer or a fitted model builds a plan, nothing more, and +`Latu.schema/1` answers on it without executing. So is `Latu.ML.attribute_frame/2`, and every +generated accessor for a DataFrame-valued attribute. So are `Latu.ML.Stat`'s three tests and `Latu.ML.assign_clusters/2`. features = Latu.ML.transform(assembler, training) # nothing has run @@ -50,7 +50,7 @@ The BEAM has no finalizer, so nothing here can free it for you. `Latu.ML.delete/1` takes a list, and a mixed one. A `Latu.ML.PipelineModel` or a search result owns the models inside it, so deleting one empties the tree in a single `Delete`. -Two things that also spend cache, and are easy to miss: `Latu.ML.load/4` on a model registers a +Two things also spend cache, and are easy to miss: `Latu.ML.load/4` on a model registers a **fresh** entry, exactly as a fit does; and a `trees` accessor answers with one cache entry per tree. `Latu.ML.cache_info/1` is how you find out what you are holding. @@ -60,44 +60,44 @@ rather than something already held being dropped. ## Params: snake_case, only what you set, kind not range -A constructor takes a keyword list in Elixir's spelling — `max_iter:` is `maxIter` on the wire. +A constructor takes a keyword list in Elixir's spelling: `max_iter:` is `maxIter` on the wire. Only the params you set are sent; the server fills in every default. **A documented default is never sent**, because a param you did not set and a param sent with its default value are different requests. Client-side validation refuses the **kind** and never the range. `reg_param: :bad` is this -package's error; `reg_param: -1.0` is Spark's own `ParamValidators`' error, and it is a better -one. A column is an atom, as everywhere in Latu. +package's error; `reg_param: -1.0` is Spark's own `ParamValidators`' error. A column is an atom, +as everywhere in Latu. `Latu.ML.params/1` prints the table for an operator, with each param's type and default. ## Attributes: the server has an allowlist, and there are two verbs `MLUtils` on the server holds a list of the methods a fetch may invoke on each model and summary -class; anything else is `CONNECT_ML.ATTRIBUTE_NOT_ALLOWED`. So the set is not "whatever PySpark -exposes", and `Latu.ML.attributes/1` is what it actually is. +class; anything else is `CONNECT_ML.ATTRIBUTE_NOT_ALLOWED`. The set is not "whatever PySpark +exposes". `Latu.ML.attributes/1` is what it actually is. **Reach for the generated accessor first.** There is one function per allowlisted attribute, on -a module per class — `Latu.ML.Regression.LinearRegressionModel.coefficients/1` — carrying the -class, the wire name and Spark's own docs. It checks the class before the round trip; the -generic verbs underneath do not. +a module per class, carrying the class, the wire name and Spark's own docs: +`Latu.ML.Regression.LinearRegressionModel.coefficients/1`. It checks the class before the round +trip; the generic verbs underneath do not. Which generic verb depends on how the attribute answers, and they refuse each other's names: - * `Latu.ML.attribute/2` for a value — `{:ok, term}`, an action. A `Vector` or `Matrix` comes + * `Latu.ML.attribute/2` for a value: `{:ok, term}`, an action. A `Vector` or `Matrix` comes back as an `Nx.Tensor`, or a `Latu.ML.SparseVector` where densifying would be this package's decision rather than yours. A `Matrix` is always row-major. - * `Latu.ML.attribute_frame/2` for a DataFrame-valued one — a lazy `Latu.DataFrame`. + * `Latu.ML.attribute_frame/2` for a DataFrame-valued one: a lazy `Latu.DataFrame`. Either verb takes either spelling: the snake_case name `Latu.ML.attributes/1` advertises, or the camelCase one the allowlist holds. ## Summaries -Ten of the 43 model classes record a training summary. `Latu.ML.summary/1` is a **lazy -builder** — Spark reaches a summary through the model that owns it, so the reference is composed -locally and nothing is sent until you ask it for something. It raises for a class that has none, -naming the ten that do. +Ten of the 43 model classes record a training summary. `Latu.ML.summary/1` is a **lazy builder**. +Spark reaches a summary through the model that owns it, so the reference is composed locally and +nothing is sent until you ask it for something. It raises for a class that has none, naming the +ten that do. The cache **drops** a summary rather than offloading it, so a fetch can answer `CONNECT_ML.MODEL_SUMMARY_LOST` through no fault of yours. `Latu.ML.attribute/2` recovers from @@ -108,7 +108,7 @@ never saw the data: there the server's refusal reaches you, and `Latu.ML.hint/1` On Spark 4.2.0 the server describes `features`, `rawPrediction` and `probability` as UDTs with no SQL type, so Latu's dtype guard refuses them rather than guessing a layout. This is how -Connect describes the type, not something a fit does — a column you build yourself with +Connect describes the type, not something a fit does. A column you build yourself with `Latu.ML.Functions.array_to_vector/1` is refused the same way. Three routes through, and the destination picks one: @@ -118,22 +118,22 @@ Three routes through, and the destination picks one: * **`Latu.ML.Functions.vector_to_array/2`** converts server-side, so the column arrives as an ordinary `array` any reader takes. Use it when the destination is an `Explorer.DataFrame`. - * **`select` or `drop` the column**, which is often the answer — a `prediction` column is a + * **`select` or `drop` the column**, which is often the answer. A `prediction` column is a double and was never the problem. ## Pipelines and tuning are client code Spark exposes no `Fit` for `Pipeline`, `CrossValidator` or `TrainValidationSplit`, so both PySpark and this package loop over the stages themselves. Which means **the wire is not what has -to match — the on-disk format is**. +to match; the on-disk format is**. -Two consequences worth knowing before you build one. A `Latu.ML.param_grid/2` entry carries the +Two consequences before you build one. A `Latu.ML.param_grid/2` entry carries the **uid** of the operator it sets, because the thing searched is usually a pipeline and a param -belongs to one stage of it; a grid whose params reach nothing is refused before the first fit. -And a search is only repeatable with a `seed:` — folds are cut with `rand(seed)` and range +belongs to one stage of it. A grid whose params reach nothing is refused before the first fit. +And a search is only repeatable with a `seed:`. Folds are cut with `rand(seed)` and range filters, and without one the draw differs between runs. -`Latu.ML.larger_better?/1` is what turns a metric into an argmax or an argmin. It is pure: the +`Latu.ML.larger_better?/1` turns a metric into an argmax or an argmin. It is pure: the server's allowlist has no `isLargerBetter`, so the registry carries PySpark's own client-side overrides. @@ -142,13 +142,13 @@ overrides. `Latu.ML.save/3` writes where the **session** is, so a bare path is the driver's disk. Anything a second machine has to read wants a URL the cluster's filesystem understands. -`Latu.ML.load/4` **names** what is at the path rather than discovering it — a `Read` has to say +`Latu.ML.load/4` **names** what is at the path rather than discovering it. A `Read` has to say which class to load before the server will look. Three spellings: an operator name from the registry, a generated model module, or `{class, kind}` for a class this package does not know. A bare model's directory is written entirely by the server, so any Spark client reads it. A **pipeline's** wrapper is written by the client in PySpark's layout, which Scala's reader -refuses — as it refuses PySpark's own, for the same one key. +refuses. It refuses PySpark's own too, for the same one key. ## Errors @@ -169,10 +169,10 @@ server: Latu.ML.params(:logistic_regression) Latu.ML.attributes(Latu.ML.Classification.LogisticRegressionModel) -`status:` is `:probed` for an operator a live server has actually run with every allowlisted -attribute answered, `:built` for one generated from PySpark's param table and not yet exercised, -`:missing` for one PySpark names and the server does not load. Every constructor's `@doc` opens -with its status, so `h` tells you what is verified rather than what is claimed. +`status:` is `:probed` for an operator a live server has run, with every allowlisted attribute +answered. `:built` is one generated from PySpark's param table and not yet exercised. `:missing` +is one PySpark names and the server does not load. Every constructor's `@doc` opens with its +status, so `h` tells you what is verified rather than what is claimed. An unknown filter key raises rather than matching nothing. A model has no constructor to look up, because a model exists only by a fit or a read. @@ -180,15 +180,14 @@ up, because a model exists only by a fit or a read. ## Things this deliberately does not do * **No `predict/2` on tensors.** MLlib is DataFrame in, DataFrame out, with a `features` - `Vector` column. `Latu.ML.transform/2` is the scoring path; the per-row `predict` attribute - is a round trip a row and is not one. - * **No building a model from parameters you hold.** There is no wire path — a model exists - only by `Latu.ML.fit/2` or `Latu.ML.load/4`. Nothing goes the other way, including from - Scholar. + `Vector` column. `Latu.ML.transform/2` is the scoring path. The per-row `predict` attribute + costs a round trip per row, so it is not one. + * **No building a model from parameters you hold.** There is no wire path: a model exists only + by `Latu.ML.fit/2` or `Latu.ML.load/4`. Nothing goes the other way, including from Scholar. * **No closures on the cluster.** `predict_batch_udf` and `xgboost.spark` ship Python to Python workers; there is no equivalent for the BEAM. - * **No parallel grid search yet.** PySpark runs the grid on a thread pool; whether several + * **No parallel grid search yet.** PySpark runs the grid on a thread pool. Whether several processes can drive one session's channel at once is unmeasured here, so the option is not - offered rather than offered untested. + offered. * **No process, and no supervision tree entry**, exactly as Latu promises. The one thing that outlives a call is the server-side cache entry, which is why `Latu.ML.delete/1` exists.