Implementation of Machine Learning Workflows with NVIDIA cuML, RAPIDS, GPU Benchmarking, Explainability, Clustering, and Model Inference

2026年9月13日 01:42
站內 AI 整理稿

In this tutorial, we implement NVIDIA cuML as a GPU-accelerated machine learning framework and build a practical workflow that demonstrates how RAPIDS can accelerate familiar data science and machine learning tasks.We begin by configuring the GPU environment and examining cuml.

accel, which lets us accelerate existing scikit-learn workloads with minimal code changes, before moving to the native cuML API for direct CuPy and cuDF interoperability.

We then benchmark CPU and GPU implementations of PCA, K-Means, nearest-neighbor search, logistic regression, random forests, and DBSCAN, while using synchronized timing to obtain meaningful performance measurements.

We also build GPU-based manifold-learning and clustering pipelines with UMAP, t-SNE, HDBSCAN, and trustworthiness metrics; explore high-throughput forest inference with FIL; validate GPU-generated SHAP explanations; perform hyperparameter optimization with scikit-learn meta-estimators; and finally serialize trained models while examining portability between GPU and CPU environments.

Copy CodeCopiedUse a different Browserimport os import sys import time import json import shutil import warnings import subprocess import importlib import traceback warnings.filterwarnings("ignore") QUICK = False SEED = 42 SCALE = 0.25 if QUICK else 1.

0 NMAIN = int(200000 SCALE) DMAIN = 64 NRF = int(50000 SCALE) DRF = 32 NNNINDEX = int(50000 SCALE) NNNQUERY = int(5000 SCALE) NDBSCAN = int(20000 SCALE) NMANIFOLD = int(60000 SCALE) NACCEL = int(80000 SCALE) RESULTS = [] NOTES = [] def banner(title): line = "=" 78 print(f"\n{line}\n {title}\n{line}", flush=True) def section(title, fn, args, kwargs): banner(title) t0 = time.

perfcounter() try: fn(args, kwargs) except Exception: print(f"[!] Section skipped due to an error:\n{traceback.formatexc()}") print(f"[section wall time: {time.perfcounter() - t0:.1f}s]", flush=True) def bootstrap(): if shutil.which("nvidia-smi") is None: raise SystemExit( "No NVIDIA GPU found.

In Colab: Runtime > Change runtime type > GPU." ) print(subprocess.run( ["nvidia-smi", "--query-gpu=name,memory.total,computecap,driverversion", "--format=csv"], captureoutput=True, text=True).stdout) try: import cuml print("cuML already available — skipping install.

") except ImportError: print("Installing RAPIDS cuML (this takes ~1-3 minutes)...") pin = "" try: import cudf majorminor = ".".join(cudf.version.split("+")[0].split(".")[:2]) pin = f"=={majorminor}.

" print(f" Pinning to the preinstalled cuDF line: cuml-cu12{pin}") except Exception: print(" cuDF not found; installing the latest stable cuml-cu12.") cmd = [sys.executable, "-m", "pip", "install", "-q", "--extra-index-url=https://pypi.nvidia.com", f"cuml-cu12{pin}"] print("$ " + " ".

join(cmd)) rc = subprocess.run(cmd).returncode if rc != 0: raise SystemExit( "pip install failed.Alternative that always works on Colab:\n" " !git clone https://github.com/rapidsai/rapidsai-csp-utils.git\n" " !python rapidsai-csp-utils/colab/pip-install.py" ) importlib.

invalidatecaches() import cuml import cupy print(f"cuml {cuml.version}") print(f"cupy {cupy.version}") try: import cudf print(f"cudf {cudf.version}") except Exception: pass import sklearn print(f"sklearn {sklearn.version} (cuML requires scikit-learn >= 1.

6)") bootstrap() import numpy as np import cupy as cp import cuml import matplotlib.pyplot as plt from cuml.datasets import makeclassification as gpumakeclassification from cuml.datasets import makeblobs as gpumakeblobs rng = np.random.RandomState(SEED) cp.random.

seed(SEED) class Timer: def init(self, label, sync=True): self.label = label self.sync = sync def enter(self): if self.sync: cp.cuda.runtime.deviceSynchronize() self.t0 = time.perfcounter() return self def exit(self, exc): if self.sync: cp.cuda.runtime.deviceSynchronize() self.dt = time.

perfcounter() - self.t0 print(f" {self.label:<44s} {self.dt:8.3f}s") return False def tonumpy(a): if isinstance(a, cp.ndarray): return cp.asnumpy(a) if hasattr(a, "tonumpy"): return a.tonumpy() return np.asarray(a) def record(task, cpus, gpus): RESULTS.

append((task, cpus, gpus)) if cpus and gpus: print(f" -> {task}: {cpus / gpus:.1f}x speedup\n") ACCELSCRIPT = f''' import time import numpy as np from sklearn.datasets import makeblobs from sklearn.decomposition import PCA from sklearn.cluster import KMeans from sklearn.

neighbors import NearestNeighbors from sklearn.linearmodel import Ridge X, y = makeblobs(nsamples={NACCEL}, nfeatures=32, centers=12, randomstate=0) X = X.astype("float32"); y = y.astype("float32") t0 = time.perfcounter() PCA(ncomponents=8).

fittransform(X) KMeans(nclusters=12, ninit=1, randomstate=0).fit(X) NearestNeighbors(nneighbors=8).fit(X[:{NACCEL // 2}]).kneighbors(X[:5000]) Ridge(alpha=1.0).fit(X, y) Ridge(alpha=1.0, positive=True).fit(X[:5000], y[:5000]) print("MODELTIME %.3f" % (time.

perfcounter() - t0)) ''' def demoaccel(): path = "/content/acceldemo.py" if os.path.isdir("/content") else "acceldemo.py" with open(path, "w") as f: f.write(ACCELSCRIPT) def run(cmd, label): print(f"\n$ {' '.join(cmd[1:])}") t0 = time.perfcounter() p = subprocess.

run(cmd, captureoutput=True, text=True) wall = time.perfcounter() - t0 out = p.stdout + p.stderr models = None for line in out.splitlines(): if line.startswith("MODELTIME"): models = float(line.split()[1]) print(out.strip()[:4000]) print(f"[{label}] model time = {models}s | process wall = {wall:.

1f}s") return models cpus = run([sys.executable, path], "stock sklearn") cmd = [sys.executable, "-m", "cuml.accel", "--profile", path] gpus = run(cmd, "cuml.accel") if gpus is None: gpus = run([sys.executable, "-m", "cuml.accel", path], "cuml.accel") record("cuml.

accel (sklearn script, unmodified)", cpus, gpus) NOTES.append( "cuml.accel needed ZERO source changes; the profile table above shows " "which calls ran on GPU and why Ridge(positive=True) fell back to CPU.

" ) We configure the tutorial environment, define dataset sizes and benchmarking utilities, and verify that an NVIDIA GPU is available.We install and initialize RAPIDS cuML when necessary, set up CuPy and reproducibility controls, and create synchronized timing and result-tracking helpers.

We also demonstrate cuml.accel by running an unmodified scikit-learn workload and comparing its CPU execution with GPU-accelerated execution.Copy CodeCopiedUse a different Browserdef demonativeapi(): from cuml.preprocessing import StandardScaler from cuml.

modelselection import traintestsplit X, y = gpumakeblobs(nsamples=50000, nfeatures=8, centers=5, randomstate=SEED, dtype=np.float32) print(f"cuml.datasets output lives on device: {type(X).module}, " f"shape={X.shape}, dtype={X.dtype}") try: import cudf df = cudf.

DataFrame(X, columns=[f"f{i}" for i in range(X.shape[1])]) back = df.values ptra = X.cudaarrayinterface["data"][0] ptrb = back.cudaarrayinterface["data"][0] print(f"CuPy ptr = {hex(ptra)}") print(f"cuDF->CuPy= {hex(ptrb)}") print("Same device pointer (true zero-copy)?

", ptra == ptrb) print("Note: a column-major DataFrame round trip may re-pack; what " "matters is that no host (CPU) round trip ever happens.") scaled = StandardScaler().fittransform(df) print(f"StandardScaler(cuDF) -> {type(scaled).

name}") except Exception as e: print(f"cuDF interop skipped: {e}") from cuml.decomposition import PCA pca = PCA(ncomponents=3).fit(X) print(f"default (mirrors input) -> {type(pca.transform(X)).name}") with cuml.usingoutputtype("numpy"): print(f"inside usingoutputtype() -> {type(pca.transform(X)).

name}") print(f"after the context manager -> {type(pca.transform(X)).name}") NOTES.append( "Keep outputtype as CuPy/cuDF inside a pipeline; converting to NumPy " "on every step forces a device->host copy and eats the speedup." ) Xtr, Xte, ytr, yte = traintestsplit(X, y, testsize=0.

2, randomstate=SEED) print(f"traintestsplit -> {Xtr

Related

相關文章

一加 Ace 7 Pro 火爆熱銷:首銷銷量同比上漲 225%

10月29日,「性能直升跨代之作」一加 Ace 7 系列發佈即開售,憑藉“性能直升一代、遊戲橫掃全場”的超旗艦體驗首銷告捷,一加 Ace 7 Pro 首銷銷量同比一加 Ace 6上漲225%,同時,一加 16 和一加 Ace 7 Pro 包攬2026 年安卓手機首銷銷量冠軍和亞軍。一加中國區總裁李傑表示:“一加 Ace 7 系列性能、屏幕、影像全面領先,好產品自己會說話。 一加 Ace 7 系列的實際體驗,相信大家上手之後會更加驚喜。

4 天前

腦景中心啟幕、四款新品齊發!熵基科技加碼非侵入式腦機接口全棧技術與應用平臺

10月29日,以"BE THE CHANGE MAKER"為主題的熵基科技全球合作伙伴大會2026在東莞啟幕,會期將持續至10月31日。本屆大會聚焦原生AI發展趨勢,圍繞空間智能、腦機接口與人工智能融合創新,以及全球產業生態協同展開,集中呈現熵基科技在技術創新、產品研發與場景應用方面的最新進展。大會期間,ZKBrainScape腦景中心正式啟幕,MarsLume火星慧知AI全域解決方案全球發佈,熵基科技攜手生態夥伴聯合發佈四款腦機接口新品,並通過產業合作與技術交流,探索創新技術走向真實場景的更多路徑。

4 天前
何夕2077研究與前沿

推理蒸餾開始改寫教師解題軌跡

Computer Science > Artificial Intelligence arXiv:2610.36445 (cs) [Submitted on 27 Oct 2026] Title:From Solver Trajectories to Teaching Trajectories: Cognition-Aligned Reasoning Distillation Authors:Yashuo Luo, Qianren Ma。

4 天前

OpenAI官宣數學與物理學三大突破:AI攻克百年猜想,攜手全球學者開啟科學驗證新模式

為了將這些前沿的原始研究數據轉化為真正的科學理解,OpenAI創新性地嘗試了與外部學術社區進行深度合作的新模式,並針對不同領域的成果制定了多元化的發佈策略。在調和分析領域,模型成功給出了各維度下局部光滑(local smoothing)猜想的證明,從而在所有維度上直接解決了數學界的 Kakeya 猜想與 Stein 限制猜想。

1 週前7600

Reddit 開源社區 r/opensource 封殺 AI 項目,開發者另起爐灶

管理團隊稱,當下 AI 的發展模式與開源理念相沖突,須以限制護住社區價值取向。一條新規,邊界模糊這條禁令迅速引爆爭論,因為它沒說清"AI 參與"的紅線在哪。如今開發普遍用 AI 輔助編程、代碼補全和自動測試,主體由人寫的項目也可能夾帶 AI 生成的片段;用戶甚至點出,Linux 內核也已出現 AI 生成代碼——若按字面執行,海量主流開源軟件都可能被擋在門外。

1 週前4300

全球互聯網經歷“黑色十月”,這個中國AI在風暴來臨前留了後手

作者 | Saul 編輯 | 漠影 過去48小時,全球互聯網經歷“黑色十月”:支撐七成網站的PHP代碼,被AI挖出存在兩個CVSS9.2分的嚴重漏洞。更棘手的是,漏洞細節在補丁發佈前就遭洩露:據The Register報道,亞馬遜的威脅情報團隊在公開前四天就捕獲了利用嘗試; Cloudflare的監測數據顯示,攻擊嘗試在公開後兩小時內從數千次漲到數百萬次。

1 週前