Skip to content

DOC Array API examples - #33564

Draft
betatim wants to merge 1 commit into
scikit-learn:mainfrom
betatim:sklearn-array-api-examples-20260316
Draft

betatim wants to merge 1 commit into
scikit-learn:mainfrom
betatim:sklearn-array-api-examples-20260316

Conversation

@betatim

@betatim betatim commented Mar 17, 2026 •

Copy link
Copy Markdown
Member

What does this implement/fix? Explain your changes.

This PR contains several examples that show off GPU support (via array API) in scikit-learn. Some of them focus on speed up, some of them show how your pipeline is simpler if you don't have to transfer from GPU to CPU, and one shows the kind of mixed input (numbers and strings) where text processing happens on the CPU.

I don't think we want to add these to the gallery, but I wanted to share them and making a PR feels like a good way to do this. The goal of having examples is to try and find bugs and other warts in our array API support. Things that you only find or notice if you use things together (think "integration tests").

It would be great to hear what other people think about these examples and things that are missing.

AI usage disclosure

I used AI assistance for:

  • Code generation (e.g., when writing an implementation or fixing a bug)
  • Test/benchmark generation
  • Documentation (including examples)
  • Research and understanding

ping @ogrisel @lucyleeow

related #33444 #32886 #32873

@github-actions github-actions Bot added Documentation CI:Linter failure The linter CI is failing on this PR labels Mar 17, 2026
@github-actions

Copy link
Copy Markdown

❌ Linting issues

This PR is introducing linting issues. Here's a summary of the issues. Note that you can avoid having linting issues by enabling pre-commit hooks. Instructions to enable them can be found here.

You can see the details of the linting issues under the lint job here


ruff check

ruff detected issues. Please run ruff check --fix --output-format=full locally, fix the remaining issues, and push the changes. Here you can see the detected issues. Note that the installed ruff version is ruff=0.12.2.

Details

examples/array_api/plot_gpu_gmm_anomaly_detection.py:32:20: F401 [*] `joblib.parallel_backend` imported but unused
   |
30 |     sys.exit(0)
31 |
32 | from joblib import parallel_backend
   |                    ^^^^^^^^^^^^^^^^ F401
33 |
34 | import sklearn
   |
   = help: Remove unused import: `joblib.parallel_backend`

examples/array_api/plot_gpu_mixed_data_pipeline.py:173:89: E501 Line too long (97 > 88)
    |
172 | fig, ax = plt.subplots(figsize=(7, 4))
173 | labels = ["CPU pipeline\n(all NumPy)", f"GPU pipeline\n(FunctionTransformer → {device.upper()})"]
    |                                                                                         ^^^^^^^^^ E501
174 | bars = ax.bar(labels, [elapsed_cpu, elapsed_gpu])
175 | ax.set_ylabel("Wall-clock time (seconds)")
    |

examples/array_api/plot_gpu_ridge_tuning.py:131:89: E501 Line too long (89 > 88)
    |
129 |               [elapsed_cpu, elapsed_gpu])
130 | ax.set_ylabel("Wall-clock time (seconds)")
131 | ax.set_title(f"GridSearchCV: 25 configs x 3 folds on Covertype\nSpeedup: {speedup:.1f}x")
    |                                                                                         ^ E501
132 | ax.bar_label(bars, fmt="%.1fs")
133 | plt.tight_layout()
    |

examples/array_api/plot_gpu_semantic_similarity.py:19:1: I001 [*] Import block is un-sorted or un-formatted
   |
17 |   # SPDX-License-Identifier: BSD-3-Clause
18 |
19 | / import os
20 | | import sys
21 | | import time
22 | | import textwrap
   | |_______________^ I001
23 |
24 |   os.environ["SCIPY_ARRAY_API"] = "1"
   |
   = help: Organize imports

examples/array_api/plot_gpu_semantic_similarity.py:139:89: E501 Line too long (92 > 88)
    |
137 | print()
138 | for rank, idx in enumerate(top_indices, 1):
139 |     print(f"  #{rank} (sim={query_sims[idx]:.3f}, group: {target_names[all_targets[idx]]})")
    |                                                                                         ^^^^ E501
140 |     print(f"       {textwrap.shorten(all_texts[idx].replace(chr(10), ' '), width=100)}")
    |

examples/array_api/plot_gpu_text_classification.py:186:89: E501 Line too long (90 > 88)
    |
184 | # ---------------------
185 |
186 | y_pred_report = np.asarray(y_pred_gpu.cpu()) if hasattr(y_pred_gpu, "cpu") else y_pred_gpu
    |                                                                                         ^^ E501
187 | print(classification_report(y_test_np, y_pred_report, target_names=target_names))
    |

Found 6 errors.
[*] 2 fixable with the `--fix` option.

ruff format

ruff detected issues. Please run ruff format locally and push the changes. Here you can see the detected issues. Note that the installed ruff version is ruff=0.12.2.

Details

--- examples/array_api/plot_gpu_gmm_anomaly_detection.py
+++ examples/array_api/plot_gpu_gmm_anomaly_detection.py
@@ -64,6 +64,7 @@
 # API compatibility. We search over the number of mixture components with
 # ``reg_covar=1e-4`` for numerical stability.
 
+
 def make_gmm_pipeline():
     return make_pipeline(
         StandardScaler(),
@@ -74,6 +75,7 @@
         ),
     )
 
+
 param_grid = {"gaussianmixture__n_components": [2, 5, 10, 15, 20, 25, 30]}
 search = GridSearchCV(make_gmm_pipeline(), param_grid, cv=3)
 
@@ -128,12 +130,11 @@
 speedup = elapsed_cpu / elapsed_gpu if elapsed_gpu > 0 else float("inf")
 
 fig, ax = plt.subplots(figsize=(6, 4))
-bars = ax.bar(["NumPy / CPU", f"PyTorch / {device.upper()}"],
-              [elapsed_cpu, elapsed_gpu])
-ax.set_ylabel("Wall-clock time (seconds)")
-ax.set_title(
-    f"GMM GridSearchCV on Credit Card Fraud\nSpeedup: {speedup:.1f}x"
+bars = ax.bar(
+    ["NumPy / CPU", f"PyTorch / {device.upper()}"], [elapsed_cpu, elapsed_gpu]
 )
+ax.set_ylabel("Wall-clock time (seconds)")
+ax.set_title(f"GMM GridSearchCV on Credit Card Fraud\nSpeedup: {speedup:.1f}x")
 ax.bar_label(bars, fmt="%.1fs")
 plt.tight_layout()
 plt.show()

--- examples/array_api/plot_gpu_mixed_data_pipeline.py
+++ examples/array_api/plot_gpu_mixed_data_pipeline.py
@@ -63,16 +63,18 @@
 newsgroups = fetch_20newsgroups(subset="all")
 
 texts = newsgroups.data
-df = pd.DataFrame({
-    "text": texts,
-    "n_chars": [len(t) for t in texts],
-    "n_lines": [t.count("\n") + 1 for t in texts],
-    "quote_ratio": [
-        sum(1 for line in t.split("\n") if line.startswith(">"))
-        / max(t.count("\n") + 1, 1)
-        for t in texts
-    ],
-})
+df = pd.DataFrame(
+    {
+        "text": texts,
+        "n_chars": [len(t) for t in texts],
+        "n_lines": [t.count("\n") + 1 for t in texts],
+        "quote_ratio": [
+            sum(1 for line in t.split("\n") if line.startswith(">"))
+            / max(t.count("\n") + 1, 1)
+            for t in texts
+        ],
+    }
+)
 y = newsgroups.target
 
 df_train, df_test, y_train, y_test = train_test_split(
@@ -170,7 +172,10 @@
 # changes to any other pipeline step.
 
 fig, ax = plt.subplots(figsize=(7, 4))
-labels = ["CPU pipeline\n(all NumPy)", f"GPU pipeline\n(FunctionTransformer → {device.upper()})"]
+labels = [
+    "CPU pipeline\n(all NumPy)",
+    f"GPU pipeline\n(FunctionTransformer → {device.upper()})",
+]
 bars = ax.bar(labels, [elapsed_cpu, elapsed_gpu])
 ax.set_ylabel("Wall-clock time (seconds)")
 ax.set_title("Mixed-type pipeline: TF-IDF + numeric → PCA → LogisticRegression")

--- examples/array_api/plot_gpu_nystroem_classification.py
+++ examples/array_api/plot_gpu_nystroem_classification.py
@@ -141,12 +141,11 @@
 
 fig, axes = plt.subplots(1, 2, figsize=(12, 4))
 
-bars = axes[0].bar(["NumPy / CPU", f"PyTorch / {device.upper()}"],
-                   [elapsed_cpu, elapsed_gpu])
+bars = axes[0].bar(
+    ["NumPy / CPU", f"PyTorch / {device.upper()}"], [elapsed_cpu, elapsed_gpu]
+)
 axes[0].set_ylabel("Wall-clock time (seconds)")
-axes[0].set_title(
-    f"Nystroem + RidgeClassifierCV on Covertype\nSpeedup: {speedup:.1f}x"
-)
+axes[0].set_title(f"Nystroem + RidgeClassifierCV on Covertype\nSpeedup: {speedup:.1f}x")
 axes[0].bar_label(bars, fmt="%.1fs")
 
 axes[1].bar(["CPU", "GPU"], [acc_cpu, acc_gpu])
@@ -162,6 +161,7 @@
 # ----------------------------------
 
 y_pred_np = np.asarray(y_pred_gpu.cpu()) if hasattr(y_pred_gpu, "cpu") else y_pred_gpu
-y_test_report = np.asarray(
-    y_test_torch.cpu()) if hasattr(y_test_torch, "cpu") else y_test_torch
+y_test_report = (
+    np.asarray(y_test_torch.cpu()) if hasattr(y_test_torch, "cpu") else y_test_torch
+)
 print(classification_report(y_test_report.astype(int), y_pred_np.astype(int)))

--- examples/array_api/plot_gpu_ridge_tuning.py
+++ examples/array_api/plot_gpu_ridge_tuning.py
@@ -125,11 +125,13 @@
 speedup = elapsed_cpu / elapsed_gpu if elapsed_gpu > 0 else float("inf")
 
 fig, ax = plt.subplots(figsize=(6, 4))
-bars = ax.bar(["NumPy / CPU", "PyTorch / " + device.upper()],
-              [elapsed_cpu, elapsed_gpu])
+bars = ax.bar(
+    ["NumPy / CPU", "PyTorch / " + device.upper()], [elapsed_cpu, elapsed_gpu]
+)
 ax.set_ylabel("Wall-clock time (seconds)")
-ax.set_title(f"GridSearchCV: 25 configs x 3 folds on Covertype\nSpeedup: {speedup:.1f}x")
+ax.set_title(
+    f"GridSearchCV: 25 configs x 3 folds on Covertype\nSpeedup: {speedup:.1f}x"
+)
 ax.bar_label(bars, fmt="%.1fs")
 plt.tight_layout()
 plt.show()
-

--- examples/array_api/plot_gpu_semantic_similarity.py
+++ examples/array_api/plot_gpu_semantic_similarity.py
@@ -110,8 +110,9 @@
 speedup = elapsed_cpu / elapsed_gpu if elapsed_gpu > 0 else float("inf")
 
 fig, ax = plt.subplots(figsize=(6, 4))
-bars = ax.bar(["NumPy / CPU", f"PyTorch / {device.upper()}"],
-              [elapsed_cpu, elapsed_gpu])
+bars = ax.bar(
+    ["NumPy / CPU", f"PyTorch / {device.upper()}"], [elapsed_cpu, elapsed_gpu]
+)
 ax.set_ylabel("Wall-clock time (seconds)")
 ax.set_title(
     f"Pairwise cosine similarity ({len(all_texts)} docs)\nSpeedup: {speedup:.1f}x"
@@ -130,13 +131,15 @@
 query_idx = 42
 query_sims = sim_np[query_idx]
 top_k = 5
-top_indices = np.argsort(query_sims)[::-1][1:top_k + 1]
+top_indices = np.argsort(query_sims)[::-1][1 : top_k + 1]
 
 print(f"Query (index {query_idx}, group: {target_names[all_targets[query_idx]]}):")
 print(textwrap.shorten(all_texts[query_idx].replace("\n", " "), width=120))
 print()
 for rank, idx in enumerate(top_indices, 1):
-    print(f"  #{rank} (sim={query_sims[idx]:.3f}, group: {target_names[all_targets[idx]]})")
+    print(
+        f"  #{rank} (sim={query_sims[idx]:.3f}, group: {target_names[all_targets[idx]]})"
+    )
     print(f"       {textwrap.shorten(all_texts[idx].replace(chr(10), ' '), width=100)}")
 
 # %%
@@ -153,10 +156,14 @@
 for i in range(min(3, len(dup_rows))):
     r, c = dup_rows[i], dup_cols[i]
     print(f"\n  Pair (sim={sim_np[r, c]:.3f}):")
-    print(f"    Doc {r} [{target_names[all_targets[r]]}]: "
-          f"{textwrap.shorten(all_texts[r].replace(chr(10), ' '), width=90)}")
-    print(f"    Doc {c} [{target_names[all_targets[c]]}]: "
-          f"{textwrap.shorten(all_texts[c].replace(chr(10), ' '), width=90)}")
+    print(
+        f"    Doc {r} [{target_names[all_targets[r]]}]: "
+        f"{textwrap.shorten(all_texts[r].replace(chr(10), ' '), width=90)}"
+    )
+    print(
+        f"    Doc {c} [{target_names[all_targets[c]]}]: "
+        f"{textwrap.shorten(all_texts[c].replace(chr(10), ' '), width=90)}"
+    )
 
 # %%
 # Distribution of pairwise similarities

--- examples/array_api/plot_gpu_text_classification.py
+++ examples/array_api/plot_gpu_text_classification.py
@@ -108,10 +108,12 @@
 
 t0 = time.perf_counter()
 
-emb_train_np = encoder.encode(texts_train, convert_to_numpy=True, batch_size=128,
-                              show_progress_bar=False)
-emb_test_np = encoder.encode(texts_test, convert_to_numpy=True, batch_size=128,
-                             show_progress_bar=False)
+emb_train_np = encoder.encode(
+    texts_train, convert_to_numpy=True, batch_size=128, show_progress_bar=False
+)
+emb_test_np = encoder.encode(
+    texts_test, convert_to_numpy=True, batch_size=128, show_progress_bar=False
+)
 
 search_np = GridSearchCV(make_clf_pipeline(), param_grid, cv=3)
 search_np.fit(emb_train_np, y_train_np)
@@ -136,10 +138,12 @@
 
 t0 = time.perf_counter()
 
-emb_train_gpu = encoder.encode(texts_train, convert_to_tensor=True, batch_size=128,
-                               show_progress_bar=False)
-emb_test_gpu = encoder.encode(texts_test, convert_to_tensor=True, batch_size=128,
-                              show_progress_bar=False)
+emb_train_gpu = encoder.encode(
+    texts_train, convert_to_tensor=True, batch_size=128, show_progress_bar=False
+)
+emb_test_gpu = encoder.encode(
+    texts_test, convert_to_tensor=True, batch_size=128, show_progress_bar=False
+)
 
 search_gpu = GridSearchCV(make_clf_pipeline(), param_grid, cv=3)
 search_gpu.fit(emb_train_gpu, y_train_np)
@@ -183,5 +187,7 @@
 # Classification report
 # ---------------------
 
-y_pred_report = np.asarray(y_pred_gpu.cpu()) if hasattr(y_pred_gpu, "cpu") else y_pred_gpu
+y_pred_report = (
+    np.asarray(y_pred_gpu.cpu()) if hasattr(y_pred_gpu, "cpu") else y_pred_gpu
+)
 print(classification_report(y_test_np, y_pred_report, target_names=target_names))

--- examples/array_api/plot_gpu_topic_discovery.py
+++ examples/array_api/plot_gpu_topic_discovery.py
@@ -84,6 +84,7 @@
 
 param_grid = {"gaussianmixture__n_components": [10, 15, 20, 25, 30]}
 
+
 def make_topic_pipeline():
     return make_pipeline(
         StandardScaler(),
@@ -94,6 +95,7 @@
         ),
     )
 
+
 # %%
 # CPU / NumPy baseline
 # --------------------
@@ -143,12 +145,11 @@
 speedup = elapsed_cpu / elapsed_gpu if elapsed_gpu > 0 else float("inf")
 
 fig, ax = plt.subplots(figsize=(6, 4))
-bars = ax.bar(["NumPy / CPU", f"PyTorch / {device.upper()}"],
-              [elapsed_cpu, elapsed_gpu])
+bars = ax.bar(
+    ["NumPy / CPU", f"PyTorch / {device.upper()}"], [elapsed_cpu, elapsed_gpu]
+)
 ax.set_ylabel("Wall-clock time (seconds)")
-ax.set_title(
-    f"GMM Topic Discovery on 20 Newsgroups\nSpeedup: {speedup:.1f}x"
-)
+ax.set_title(f"GMM Topic Discovery on 20 Newsgroups\nSpeedup: {speedup:.1f}x")
 ax.bar_label(bars, fmt="%.1fs")
 plt.tight_layout()
 plt.show()
@@ -179,8 +180,12 @@
 fig, axes = plt.subplots(1, 2, figsize=(16, 6))
 
 scatter0 = axes[0].scatter(
-    coords[:, 0], coords[:, 1],
-    c=labels_gpu_np, cmap="tab20", s=1, alpha=0.5,
+    coords[:, 0],
+    coords[:, 1],
+    c=labels_gpu_np,
+    cmap="tab20",
+    s=1,
+    alpha=0.5,
 )
 axes[0].set_title(f"Discovered Topics ({best_n_gpu} clusters)")
 axes[0].set_xlabel("PC 1")
@@ -188,8 +193,12 @@
 plt.colorbar(scatter0, ax=axes[0], label="Cluster")
 
 scatter1 = axes[1].scatter(
-    coords[:, 0], coords[:, 1],
-    c=all_targets, cmap="tab20", s=1, alpha=0.5,
+    coords[:, 0],
+    coords[:, 1],
+    c=all_targets,
+    cmap="tab20",
+    s=1,
+    alpha=0.5,
 )
 axes[1].set_title("True Newsgroup Categories")
 axes[1].set_xlabel("PC 1")

7 files would be reformatted, 936 files already formatted

Generated for commit: 22b89c0. Link to the linter CI: here

@lucyleeow

lucyleeow commented Mar 17, 2026 •

Copy link
Copy Markdown
Member

FYI xref #32886

The goal of having examples is to try and find bugs and other warts in our array API support. Things that you only find or notice if you use things together (think "integration tests").

If we do find anything, I think it would be nice to add a test (if possible).

@betatim

betatim commented Mar 17, 2026

Copy link
Copy Markdown
Member Author

If we do find anything, I think it would be nice to add a test (if possible).

👍


pipe = make_pipeline(
StandardScaler(),
PCA(svd_solver="full"),

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens with the new solver for PCA?

@betatim

betatim commented Mar 19, 2026 •

Copy link
Copy Markdown
Member Author

Maybe it would be nice to include these examples with a link to colab so people can run them

One thing that needs figuring out is how to mark these as "don't run them" for the gallery, because they take a long time to run and need "weird" dependencies. (Maybe by not naming the file plot_foo.py?)

@lucyleeow

lucyleeow commented Mar 20, 2026 •

Copy link
Copy Markdown
Member

One thing that needs figuring out is how to mark these as "don't run them" for the gallery,

There are a few ways to do it:

  • add to ignore_pattern in conf.py - but these are completely ignored - as in not added at all
  • exclude from filename_pattern - not executed but example still present in gallery
    • you can also amend the filename_pattern regex to specifically exclude the array API example

See https://sphinx-gallery.github.io/stable/configuration.html#parsing-and-executing-examples-via-matching-patterns for docs.

Note that Sphinx has the -D build option which will let you override conf.py configurations - so this could be used in CI workflows such that this example is only run in some workflows.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Array API CI:Linter failure The linter CI is failing on this PR Documentation

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

2 participants