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

相關文章

消息稱 Anthropic 低調建立生物實驗室,借 AI 推進藥學研究

作者:清源 責編:清源 評論: 9 月 18 日消息,路透社今天(18 日)晚間援引知情人士消息稱,Anthropic 在舊金山灣區低調建立了一座溼實驗室,把 AI 業務進一步延伸到需要實際動手操作的生物學研究和藥物科學領域。知情人士透露,在公眾對 AI 風險愈發擔憂之際,Anthropic 開始在溼實驗室進行實體實驗。Anthropic 此前提出,希望藉助 AI 推動罕見病治療方法的發展,公司的生物學研究也從“計算機模擬”和計算機評估進一步走向真實實驗。注:溼實驗室是一個科學概念,與“幹實驗室”相對。相比干實驗室,溼實驗室在實驗中需要用到較多的化學試劑。相比之下,幹實驗室則注重通過各種儀器進行計算,以歸納出實驗材料的物理模型。Anthropic 生命科學負責人埃裡克 · 考德勒-艾布拉姆斯證實了溼實驗室的存在。“我們認為,生物學研究最終還是要接受真實實驗室工作的檢驗,而且未來一段時間都會如此。我們現在確實在做這些工作。整體模式和大多數生物科技公司類似,一部分在自己的設施裡完成,另一部分則與外部合作伙伴共同開展。”Anthropic 發言人又進一步補充,這座實驗室並非專門用於藥物發現,並拒絕進一步說明具體用途。知情人士稱,建立溼實驗室只是 Anthropic 邁向更大目標的一小步。Anthropic 希望攻克其認為製藥行業忽視的疾病,公司也希望在員工和公眾失去對 AI 價值的信心之前拿出成果,因為 AI 可能導致崗位消失,甚至威脅人類生命。不過,任何藥物研發項目都無法保證成功,大多數候選藥物最終都無法通過臨床安全性和有效性試驗。這項工作對 Anthropic CEO 達裡奧 · 阿莫迪還有一層個人意義。

5 小時前

AGI最難一戰,竟在醫院!中國AI登上Science,醫生不怕失業還催著上線

。 2016年,Hinton老爺子就預言:“人們現在就應該停止培養放射科醫生。”他甚至認為,五年內,AI就會在醫療影像識別上超過放射科醫生。 老爺子一生謹慎,但歷史和他開了個玩笑。十年過去了,人們離AGI已經越來越近,但在醫療場景裡,即使圖像識別這樣的AI新手村任務,依然是hard模式。 如果從IBM的Watson算起,在醫療上遭遇滑鐵盧的AI專家數不勝數。

9 小時前

AGI最難一戰,竟在醫院,中國AI登上Science,醫生不怕失業還催著上線

我没办法凭这条标题写出符合要求的完整新闻稿,原因很直接: 现有"可用资料"其实只有一行标题,正文是空的。后面的内容全是的侧边栏推荐和网站导航(Anthropic华人、Manus估值、腾讯投资药企等),跟这条新闻没有关系。 如果硬写 900–1600 字,我就得自己编造这些关键事实: 是哪个团队、哪家医院、哪篇 Science 论文 论文的具体方法和结果数据 医生"催着上线"的具体场景和原话 这些一旦写出来就是假新闻,我不做这个。

11 小時前

AI製藥獨角獸Anew單飛,字節推了一把“最燒錢的慢生意”

Reuters:Anew Labs完成首輪外部融資2.9億美元、投後估值15億美元,HSG、IDG Capital、GL Ventures、五源資本等機構入股,字節跳動融資後持股56%。2. IQVIA 2026年分析:經確認有AI參與的新興生物科技項目I期、II期臨床成功率比較,及樣本有限的說明。3. 《Nature Reviews Drug Discovery》2026年8月Perspective:AI方法與基準測試大量出現,臨床相關性影響證據仍然有限。4. Deloitte全球大型生物製藥公司晚期研發管線年度研究:2025年平均藥物開發成本約26.7億美元,計算含研發失敗成本。

12 小時前