<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by John Zedlewski on Medium]]></title>
        <description><![CDATA[Stories by John Zedlewski on Medium]]></description>
        <link>https://medium.com/@jzedlewski?source=rss-7518c982eedd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mudJ5GxFLiZJvMnY.jpg</url>
            <title>Stories by John Zedlewski on Medium</title>
            <link>https://medium.com/@jzedlewski?source=rss-7518c982eedd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:50:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jzedlewski/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Optimizing Machine Learning Models with Hyperopt and RAPIDS on Databricks Cloud]]></title>
            <link>https://medium.com/rapids-ai/optimizing-machine-learning-models-with-hyperopt-and-rapids-on-databricks-cloud-fdac9154e3e4?source=rss-7518c982eedd------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdac9154e3e4</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[open-source-software]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[John Zedlewski]]></dc:creator>
            <pubDate>Wed, 24 Jun 2020 18:21:00 GMT</pubDate>
            <atom:updated>2020-06-24T18:21:00.456Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzrEmTzro2kdvy_7cVunvw.png" /><figcaption>Parallel coordinates plot from a hyperopt experiment</figcaption></figure><p><strong>TL;DR A quick tutorial on how to use the Hyperopt HPO package with RAPIDS on the Databricks Cloud to optimize the accuracy of a random forest classifier. (Full code samples available </strong><a href="https://github.com/rapidsai/cloud-ml-examples"><strong>here</strong></a><strong>.)</strong></p><p>In our earlier <a href="https://medium.com/rapids-ai/managing-and-deploying-high-performance-models-on-gpus-with-rapids-and-mlflow-753b6fcaf75a">blog</a>, we showed how to use <a href="https://mlflow.org/">MLFlow</a> together with <a href="https://github.com/rapidsai/cuml">RAPIDS cuML</a> to train models faster and manage them more efficiently. These tools allow individual data scientists and teams to iterate quickly on models and continuously improve them while maintaining a smooth flow to production. But as it becomes easier to train large numbers of models, we have to ask — why not let an algorithm do the job for us? Here, hyperparameter optimization (HPO) can step in and help us build more accurate models with minimal effort.</p><p>This blog will walk you through using the <a href="http://hyperopt.github.io/">hyperopt</a> HPO package together with RAPIDS on the <a href="https://databricks.com/product/enterprise-cloud-service">Databricks cloud</a> to optimize the accuracy of a simple random forest classifier. RAPIDS will accelerate model training, and the Databricks cloud will parallelize it over as many workers as you want. In the training example (<a href="https://github.com/rapidsai/cloud-ml-examples/tree/master/databricks/notebooks">shared here in the cloud-ml-examples repo</a>), this leads to an optimized model about 40x faster than a similar model built on a CPU without RAPIDS.</p><h3>What is Hyperparameter Optimization?</h3><p>Most data scientists have looked at the documentation for their algorithm of choice and marveled at the number of configurable parameters. <a href="https://rapids.ai/xgboost.html">XGBoost </a>(the popular gradient-boosted decision tree library) has nearly 30 parameters that can be set for training, and many ML algorithms are similarly tunable. Proper parameter tuning can often make the difference between a mediocre model and an excellent one. Outside of machine learning competitions or academic settings, few ML engineers have the time to explore every parameter.</p><p>HPO systems automatically build dozens or hundreds of model variants with different parameters, compare their accuracies, and allow users to select the best model. Algorithms for HPO have been an area of academic interest for decades. They have increased in popularity recently as high-performance computing, and GPU acceleration makes it feasible to train larger quantities of models.</p><p>Naive HPO systems can explore the available parameters by doing a “grid search” — evenly exploring combinations of parameters across their valid range. For instance, to explore max_depth within the range of (5, 14) and n_estimators within the range of (50, 500) with increments of 50, grid search would evaluate all 100 possible combinations of parameters:</p><pre>max_depth=5, n_estimators=50<br>max_depth=5, n_estimators=100<br>max_depth=5, n_estimators=150<br>...<br>max_depth=14, n_estimators=500</pre><p>This approach can be exhaustive but <em>very </em>slow and often inefficient. If we train a number of models and see that low <em>max_depth</em> always leads to poor performance for many values of <em>num_trees</em>, do we want to spend our compute time to keep trying that parameter value again and again?</p><p>Intelligent HPO algorithms continuously evaluate the accuracy of past models and use them to guide the next steps of parameter exploration. Hyperopt, one of the most popular HPO systems, relies on an algorithm called Tree-structured Parzen Estimators (TPE) to speed up this process. TPE models the relationship between the hyperparameters and the objective function with piecewise functions that have a tree-like structure. For more detail on the internals of TPE, see <a href="https://papers.nips.cc/paper/4443-algorithms-for-hyper-parameter-optimization.pdf">Bergstra et al. 2011</a>.</p><p>But you don’t have to master the details of TPE, because the open source <a href="http://hyperopt.github.io/">hyperopt</a> package encapsulates the algorithm in a friendly Python API. Hyperopt can be used standalone on any system to optimize a model, but it gets most interesting when combined with a distributed platform like Databricks.</p><h3>Getting started with RAPIDS and Hyperopt on Databricks</h3><p>In the Databricks directory under the <a href="https://github.com/rapidsai/cloud-ml-examples/tree/master/databricks">RAPIDSAI/cloud-ml-examples repo on GitHub</a>, we have an example notebook that walks through all of the code necessary to optimize a simple model with hyperopt on Databricks and track it through MLFlow. The repo also contains init scripts that make it easy to install RAPIDS on a Databricks cluster.</p><p>To build your RAPIDS-on-Databricks cluster, start by choosing a Databricks runtime that supports GPUs. We tested these scripts on “Runtime 6.6 ML” (later runtime versions may not be compatible yet). Choose a worker type that supports modern NVIDIA GPUs (Pascal or later) and choose the same instance type for the driver. For AWS-backed clusters, any of the “p3.” instances or “g4dn.” instances will support RAPIDS — just steer clear of the much older “p2.” instances, which have an earlier generation of GPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*zkkys8JsxPIYAJZm" /><figcaption>Instance types with GPU support</figcaption></figure><p>To install RAPIDS, you’ll need to copy the RAPIDS initialization scripts to your DBFS datastore. Copy the rapids_install_cuml0.13_cuda10.0_ubuntu16.04.sh script from the cloud-ml-examples repo to a DBFS location of your choice, e.g., by running the following commands in a Databricks notebook:</p><pre>dbfs configure</pre><pre>dbfs cp src/rapids_install_cuml0.13_cuda10.0_ubuntu16.04.sh dbfs:/databricks/init_scripts/</pre><p>In the Advanced Options section of the configuration, add the DBFS path of this script as an init script for your cluster:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/0*8_A_WSBm4f8WAoHr" /><figcaption>Configuring the init script</figcaption></figure><p>Now, when the cluster launches, it will automatically install RAPIDS. This process may take 10–15 minutes during launch, but it will not add additional runtime when you kick off jobs post-launch.</p><p>That’s it! You can launch a notebook, attach it to this cluster, and start using RAPIDS interactively right away. For some smaller jobs, you can compute directly within the notebook, running on the driver node. But for large-scale HPO, we’ll configure hyperopt to launch jobs on multiple workers to allow true scale-out.</p><h3>Integrating with Hyperopt</h3><p>Databricks has already installed a custom version of hyperopt in the ML environment on its cloud so that we can import it right away. We’ll start with a simple training function based on the same dataset and estimator we used in the <a href="https://medium.com/p/753b6fcaf75a">MLFlow blog</a>. Again, we’re training a classifier to predict whether a flight will arrive on time, using a dataset of past flights from the US Federal Aviation Administration. We want to tune the n_estimators (number of trees to build), max_depth(how deep each tree can be), and max_features (fraction of features to consider at each split) hyperparameters to maximize accuracy.</p><p>Integrating a model with hyperopt requires four steps:</p><ol><li>Define your objective function,</li><li>Define your parameter space,</li><li>Create a SparkTrials object, and</li><li>Launch hyperopt with the “hyperopt.fmin” function.</li></ol><h4>1. Define your objective function</h4><p>Hyperopt will explore parameters to minimize this function, and we can freely define it however we like. In a machine learning problem, this function will typically entail training a model with the given parameters, then evaluating it on a held-out validation set to measure its accuracy.<br>To match the hyperopt API, this objective function should return a dictionary with a “loss” value for the system to minimize. In the sample notebook, this is the “train_rapids” function.</p><pre>def <strong>train_rapids</strong>(hyperopt_params):<br>   “””<br>   Pseudo training function<br>   1. Unpack hyperopt_params<br>   2. Train a new model with those hyperopt_params<br>   3. Compute accuracy as ‘acc’ on validation set<br>   “””<br>   # …. function body here ….<br>   return {‘loss’: acc, ‘status’: STATUS_OK}</pre><h4>2. Define your parameter space</h4><p>For each parameter we want to explore, we need to give hyperopt a range of values to consider, in the form of a probability distribution. The hyperopt API provides probability range functions, like hyperopt.hp.uniform(parameter_name, lower_bound, upper_bound) to sample uniformly between the bounds. Hyperopt also supports distributions with integer ranges or categorical values.</p><pre>search_space = [<br>   hyperopt.hp.uniform(‘max_depth’, 5, 20),<br>   hyperopt.hp.uniform(‘max_features’, 0., 1.0),<br>   hyperopt.hp.uniform(‘n_estimators’, 150, 1000)<br>]</pre><h4>3. Create a “SparkTrials” object</h4><p>This will track our progress and allow integration with Apache Spark.</p><pre>import hyperopt<br>spark_trials = hyperopt.SparkTrials(parallelism=MAX_PARALLEL)</pre><h4>4. Launch hyperopt with the hyperopt.fmin function</h4><p>This will launch up to MAX_PARALLEL jobs in parallel (potentially limited by the number of workers in your Databricks cluster), track their results and return the best result achieved.</p><pre>results = hyperopt.fmin(fn=train_rapids,<br>   space=search_space,<br>   algo=algorithm,<br>   max_evals=2,<br>   trials=trials)</pre><p>The Databricks notebook UI allows you to track runs in progress as it optimizes. In the “Runs” tab of the notebook, you can see a quick summary view, but by clicking on the “Experiment UI” link at the bottom of this sidebar, you can get to a much richer view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*Jsr5v3a7KOIjkohD" /><figcaption>Runs view sidebar</figcaption></figure><p>Here, we can select metrics from our recent runs to the graph. Here, we’ll plot how accuracy varies as we increase the max_depth parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sUPB94xp_EcXpDfx" /><figcaption>Graphing in the Experiment UI</figcaption></figure><p>To build a large-scale model with the sample notebook, use the “airline_20000000.parquet” input file for the file name parameter. Running on two p3.2xlarge nodes (with one V100 GPU in each), this will take about 17 minutes to run on GPU. Model accuracy varies from about 83% for worse models to around 86% for high-accuracy models. So you can get a significant accuracy boost with just a few minutes of runtime. Depending on your budget and quotas, you can crank up the parallelism even further to complete the jobs faster. Because hyperopt is embarrassingly parallel, it scales extremely well to large systems.</p><p>When you want to deploy the model, you can take advantage of hyperopt’s built-in integration with the MLFlow model repository on Databricks. See the <a href="https://medium.com/p/753b6fcaf75a">MLFlow blog</a> for more details on MLFlow model management.</p><p>The notebook also contains sample code to run hyperopt on CPUs with <a href="https://scikit-learn.org/stable/">scikit-learn</a>. Be forewarned, though, that running it will take about 12 hours with two parallel nodes.</p><h3>Wrapping Up</h3><p>This blog has only scratched the surface of what’s possible with HPO and RAPIDS. The <a href="https://github.com/rapidsai/cloud-ml-examples/">cloud-ml-examples repo</a> contains several other HPO demos. If you have comments, questions, or problems, please file an issue on that repo or raise the question in the <a href="https://join.slack.com/t/rapids-goai/shared_invite/enQtMjE0Njg5NDQ1MDQxLTJiN2FkNTFkYmQ2YjY1OGI4NTc5Y2NlODQ3ZDdiODEwYmRiNTFhMzNlNTU5ZWJhZjA3NTg4NDZkMThkNTkxMGQ">RAPIDSAI Slack</a>.</p><p><strong>Also,</strong><a href="https://medium.com/u/7518c982eedd"><strong> John Zedlewski</strong></a><strong> gave a talk on <em>Optimizing models with hyperopt and RAPIDS on Databricks Cloud</em> at Spark+AI Summit. Check </strong><a href="https://databricks.com/session_na20/accelerating-mlflow-hyper-parameter-optimization-pipelines-with-rapids"><strong>here</strong></a><strong> for the on-demand recording.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdac9154e3e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rapids-ai/optimizing-machine-learning-models-with-hyperopt-and-rapids-on-databricks-cloud-fdac9154e3e4">Optimizing Machine Learning Models with Hyperopt and RAPIDS on Databricks Cloud</a> was originally published in <a href="https://medium.com/rapids-ai">RAPIDS AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing and Deploying High-Performance Machine Learning Models on GPUs with RAPIDS and MLFlow]]></title>
            <link>https://medium.com/rapids-ai/managing-and-deploying-high-performance-machine-learning-models-on-gpus-with-rapids-and-mlflow-753b6fcaf75a?source=rss-7518c982eedd------2</link>
            <guid isPermaLink="false">https://medium.com/p/753b6fcaf75a</guid>
            <category><![CDATA[open-source-software]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[John Zedlewski]]></dc:creator>
            <pubDate>Wed, 24 Jun 2020 16:01:01 GMT</pubDate>
            <atom:updated>2020-06-24T20:05:14.038Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRb0UO0O3GXQmTc1DoOUFQ.png" /></figure><p><a href="http://rapids.ai/">RAPIDS</a> and <a href="https://github.com/rapidsai/cuml">cuML</a> use NVIDIA GPUs to accelerate the training of machine learning models — by <a href="https://medium.com/rapids-ai/accelerating-random-forests-up-to-45x-using-cuml-dfb782a31bea?source=collection_home---6------4-----------------------">up to 45x in the case of random forests</a>, over<a href="https://medium.com/rapids-ai/fast-support-vector-classification-with-rapids-cuml-6e49f4a7d89e"> 100x for support vector machines</a>, and <a href="https://medium.com/rapids-ai/accelerating-k-nearest-neighbors-600x-using-rapids-cuml-82725d56401e">up to 600x for k-nearest neighbors</a>. These speedups can turn overnight jobs into interactive jobs, allow exploration of larger datasets, and allow users to save time on prototyping. But possibly the most exciting super-power of GPU-accelerated machine learning is that it enables data scientists to iterate much faster, trying dozens of model variants in the time it would have previously taken to train a single model.</p><p>Faster iteration leads to many more models, and that can lead to confusion and complexity if you track your efforts manually. <a href="https://mlflow.org/">MLFlow </a>is an open source model lifecycle management framework that simplifies the process of tracking, comparing, and deploying models. It can integrate with most machine learning frameworks and several cloud platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*FrCAGNuZIiYwJ4Sg" /><figcaption><em>Figure 1: Components of MLflow</em></figcaption></figure><p>In this blog, we’ll walk through a simple RAPIDS cuML model and show how we can integrate it with MLFlow to make our lives easier.</p><p>After integrating with MLFlow, data scientists will often want to incorporate <em>automated</em> hyperparameter optimization (HPO) to tune models with no intervention. To learn more about building an HPO pipeline with hyperopt, RAPIDS, and MLFlow, see the follow-up post on the <a href="https://medium.com/rapids-ai">RAPIDS blog</a>.</p><h3>Starting with a Basic Model in RAPIDS cuML</h3><p>RAPIDS cuML provides the same Python APIs as the popular scikit-learn library, but with a GPU-accelerated backend to speed up model training and inference. Similarly, cuDF provides an accelerated backend for Pandas APIs. For this example, we’ll build a trivial model using a dataset of flight departures. We’ll try to predict whether or not a flight will be delayed (<em>ArrDelayBinary </em>in the dataset) based on other metadata about the flight. We can do this using a Random Forest classifier, which will build a large number of varied decision trees to collectively vote on whether they expect a flight to be delayed. (For more on Random Forests, see <a href="https://medium.com/rapids-ai/accelerating-random-forests-up-to-45x-using-cuml-dfb782a31bea">this more detailed blog</a>.)</p><pre># See the full example at:<br># <a href="https://github.com/rapidsai/cloud-ml-examples/tree/master/mlflow_project/src">https://github.com/rapidsai/cloud-ml examples/tree/master/mlflow_project/src</a></pre><pre>from cuml import RandomForestClassifier<br>from cuml.metrics import accuracy_score</pre><pre># Loads data via cuDF and splits with cuml train_test_splitX_train, X_test, y_train, y_test = load_data(fpath)</pre><pre>mod = RandomForestClassifier(max_depth=max_depth, <br> max_features=max_features,<br> n_estimators=n_estimators)</pre><pre>preds = mod.predict(X_test)<br>acc = accuracy_score(y_test, preds)</pre><p>This looks almost identical to the scikit-learn-based code, with only imports being changed. One key difference is that it will run 10x-45x faster, depending on the dataset size and parameters.</p><p>While random forests can be solid classifiers right out of the box, they have several parameters that can be tuned to improve accuracy. How deep should the trees be allowed to grow? Deeper trees can express more complex functions but may lead to overfitting of the data. How many trees should we build? When we split a node in the tree, should we consider all of the features or a random subset? Like many data scientists, we may start by manually trying a few variants of the model.</p><h3>Tracking Models with MLFlow</h3><p>Once we start experimenting with model variations, it’s easy to lose track of what we’ve tried. Are we sure we can reproduce that best model? What was the good value of n_estimators again? Even in a single work session, it can be easy to lose track, but the problem grows as more team members iterate on a model over days or months.</p><p><a href="https://mlflow.org/">MLFlow </a>is designed to help solve these lifecycle and tracking issues. It provides hooks to snapshot your training code, your metrics, and your trained models. You can query any of these results later and pull down the best model to deploy for production. MLFlow works with RAPIDS cuML out of the box. Because cuML estimators match the scikit-learn API, the features of the mlflow.sklearn the module automatically works with cuML models as well.</p><p>We’ll want to encapsulate the training inside of an MLFlow run, then store the hyperparameters, the metrics, and the model itself. You can install MLFlow locally with a simple conda install -c conda-forge mlflow<em> </em>or pip install mlflow. Examples in this blog were tested with version 1.8.0.</p><pre>X_train, X_test, y_train, y_test = load_data(fpath)</pre><pre>mod = RandomForestClassifier(max_depth=max_depth,<br> max_features=max_features,<br> n_estimators=n_estimators)</pre><pre>mod.fit(X_train, y_train)<br>preds = mod.predict(X_test)<br>acc = accuracy_score(y_test, preds)</pre><pre>mlparams = {&quot;max_depth&quot;: max_depth,<br> &quot;max_features&quot;: max_features,<br> &quot;n_estimators&quot;: n_estimators}<br> mlflow.log_params(mlparams)</pre><pre>mlflow.log_metric(&quot;accuracy&quot;, acc)</pre><pre>mlflow.sklearn.log_model(mod, &quot;saved_models&quot;)</pre><blockquote><strong>See </strong><a href="https://github.com/rapidsai/cloud-ml-examples/blob/master/mlflow_project/src/rf_test/train.py"><strong>this repo</strong></a><strong> for the full example, including startup code.</strong></blockquote><p>We’re inserting just a few additional lines. The <em>mlflow.log_metric(&quot;accuracy&quot;, acc)</em> call is a typical MLFlow addition — it stores an arbitrary key=value style metric for the model. You can log as many metrics as you want for a given training run. For instance, you may want accuracy, precision, and recall. We also recorded the parameters used with <em>mlflow.log_params</em>, and this will allow us to find the parameters used to train the best model in the future.</p><p>Maybe the most critical line is the call to <em>mlflow.sklearn.log_model(mod, &quot;saved_models&quot;)</em>, which adds the trained model to MLFlow’s saved model repository. This is essentially a database of saved models so you can extract models again for further analysis or production deployment. It can be as simple as a local filesystem with past models, or a full-fledged model registry (<a href="https://www.mlflow.org/docs/latest/model-registry.html#adding-an-mlflow-model-to-the-model-registry">see more on model registry options here</a>). The mlflow.sklearn model logging API uses Python’s standard protocols to serialize the model via CloudPickle. cuML models support the same serialization and deserialization protocols so that they can be logged as well.</p><p>Before launching the training script, we’ll add an MLProject file in our directory. This is a simple yaml document describing the model, its parameters, and how to run it. The MLProject file provides a standardized entry point so that MLFlow tools know precisely how to run and configure the model training. This standardization becomes particularly valuable as your organization builds more and more models and shares them across multiple data scientists. In our <a href="https://github.com/rapidsai/cloud-ml-examples/blob/master/mlflow_project/MLproject">sample MLProject file</a>, we’ve defined both a “simple” MLFlow model and a more complex one that includes hyperparameter optimization.</p><p>Now we can run the model and specify its parameters with:</p><pre>mlflow run . -b local -e simple \<br>-P conda-env=$PWD/envs/conda.yaml \<br>-P fpath=<a href="https://rapidsai-cloud-ml-sample-data.s3-us-west-2.amazonaws.com/airline_small.parquet">https://rapidsai-cloud-ml-sample-data.s3-us-west-2.amazonaws.com/airline_small.parquet</a> \<br>-P n_estimators=50 -P max_features=0.5 -P n_estimators=10</pre><p>All the key=value parameters passed with the -P flag will show up as command-line arguments to the underlying script.</p><p>After you’ve run a few example experiments, you can browse the results in the MLFlow UI. Each model shows the experiment metadata as well as key metrics. We can select the best model and view the parameters, command line, and conda environment used to train it. We can also choose a model that we’ll deploy to production.</p><p>To launch the UI, just run mlflow ui in your shell, and it will start a local server on port 5000 by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uZLwcyAwSyL56WWp" /><figcaption>Browsing trained models and metrics in MLFlow UI</figcaption></figure><h3>Deploying the Model</h3><p>Training, of course, is only half the battle in machine learning. We ultimately want to use this model to predict results from new input data. Often this step will be developed by a different engineer or a different team entirely, comprised of data scientists who have experienced the struggle of managing models across multiple groups and who may be unfamiliar with each other’s APIs and model lifecycles. MLFlow supports various workflows to facilitate these use cases.</p><p>The first, a simple artifact style storage/retrieval pattern, allows a user or group of users to save, search, and load models programmatically using the MLFlow tracking server. This makes it possible for a well structured, and consistent design process, which is fully reproducible by other data scientists, or engineers tasked with moving these models into production. As RAPIDS provides a SKLearn compatible API, we can leverage the mlflow.sklearn module to save and restore models.</p><h3>Save a Model</h3><pre>import mlflow</pre><pre>from cuml.ensemble import RandomForestClassifier</pre><pre>model = RandomForestClassifier()</pre><pre># Store an existing RAPIDS model</pre><pre># Here, conda_env allows us to attach a conda environment<br># specification to a given model, that provides an explicit<br># declaration of the environment where it was trained, and allows us<br># to deploy it later.</pre><pre>mlflow.sklearn.log_model(model, &quot;rapids_rf_model&quot;,<br>     conda_env=&#39;conda.yaml&#39;)</pre><pre><em># Retrieve and load a model<br></em>model_name = &quot;rapids_rf_model&quot;<br>client = mlflow.tracking.MlflowClient()</pre><pre>model_data = \<br>  client.search_model_versions(&quot;name=&#39;rapids_mlflow_test&#39;&quot;)[0]<br>model = mlflow.sklearn.load_model(model_data.source)</pre><pre><em># Make predictions<br></em>preds = model.predict(X)</pre><p>The second workflow sets up a fully functional REST-style server for our model, managed by MLFLow. For this, we simply need to identify the model_uri, which we would like to deploy and launch the REST service via the MLFlow CLI. This will cause MLFLow to create a conda environment matching the ‘conda.yaml’ we supplied along with our model when it saved, load the model, and serve from its ‘predict’ method. This process provides a well-specified process for testing models via Continuous Integration (CI), as well as a potential path forward for integrated production deployment and updates.</p><p>mlflow models — serve -m [PATH TO MODEL] -p [PORT] -h [HOST]</p><p>Once our model is up and running, we can query the REST service as follows:</p><pre>import json<br>import requests</pre><pre>headers = {<br> &quot;Content-Type&quot;: &quot;application/json&quot;,<br> &quot;format&quot;: &quot;pandas-split&quot;<br>}</pre><pre># Some arbitrary sample data<br>data = {<br>  &quot;columns&quot;: [&quot;Year&quot;, &quot;Month”, &quot;DayofMonth&quot;, &quot;DayofWeek&quot;, &quot;CRSDepTime&quot;, &quot;CRSArrTime&quot;, &quot;UniqueCarrier&quot;, &quot;FlightNum&quot;, &quot;ActualElapsedTime&quot;, &quot;Origin&quot;, &quot;Dest&quot;, &quot;Distance&quot;, &quot;Diverted&quot;],<br>&quot;data&quot;: [[1987, 10, 1, 4, 1, 556, 0, 190, 247, 202, 162, 1846, 0]]<br>}</pre><pre>resp = requests.post(url=f&quot;http://{host}:{port}/invocations&quot;,<br>  data=json.dumps(data), headers=headers)</pre><pre>print(f&#39;Classification: {&quot;ON-Time&quot; if resp.text == &quot;[0.0]&quot; else &quot;LATE&quot;}&#39;)</pre><h3>Wrapping Up and Additional Resources</h3><p>This blog just scratches the surface of cuML and MLFlow. The code samples for this blog are found in the RAPIDS <a href="https://github.com/rapidsai/cloud-ml-examples">cloud-ml-examples repo</a>. That repository contains several other examples of hyperparameter optimization and model management on platforms like Ray Tune, AWS SageMaker, Azure ML, and Google Cloud AI.</p><p><strong>Also, </strong><a href="https://medium.com/u/7518c982eedd"><strong>John Zedlewski</strong></a><strong> gave a talk on the integration of RAPIDS cuML and MLFlow at Spark+AI Summit on June 24, 2020, at 11 AM PDT. Get the details </strong><a href="https://databricks.com/session_na20/accelerating-mlflow-hyper-parameter-optimization-pipelines-with-rapids"><strong>here</strong></a><strong>.</strong></p><p>As always, if you have feature requests or any problems, please raise an issue on <a href="https://github.com/rapidsai/cloud-ml-examples/issues">the cloud-ml-examples repo</a> or reach out to our <a href="https://join.slack.com/t/rapids-goai/shared_invite/enQtMjE0Njg5NDQ1MDQxLTJiN2FkNTFkYmQ2YjY1OGI4NTc5Y2NlODQ3ZDdiODEwYmRiNTFhMzNlNTU5ZWJhZjA3NTg4NDZkMThkNTkxMGQ">RAPIDS Slack channel</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=753b6fcaf75a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rapids-ai/managing-and-deploying-high-performance-machine-learning-models-on-gpus-with-rapids-and-mlflow-753b6fcaf75a">Managing and Deploying High-Performance Machine Learning Models on GPUs with RAPIDS and MLFlow</a> was originally published in <a href="https://medium.com/rapids-ai">RAPIDS AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAPIDS on Microsoft Azure Machine Learning]]></title>
            <link>https://medium.com/rapids-ai/rapids-on-microsoft-azure-machine-learning-b51d5d5fde2b?source=rss-7518c982eedd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b51d5d5fde2b</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[open-source-software]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[gpu]]></category>
            <dc:creator><![CDATA[John Zedlewski]]></dc:creator>
            <pubDate>Sun, 03 Nov 2019 22:29:41 GMT</pubDate>
            <atom:updated>2019-11-04T15:05:21.116Z</atom:updated>
            <content:encoded><![CDATA[<p><em>(Code and original text by </em><a href="https://medium.com/u/51ce839bf0f"><em>Matthew Jones</em></a><em>)</em></p><p>A Guide to Machine Learning at Scale</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*kUpJcFhG370Yswi-bde_SQ.png" /></figure><h3>Some Preamble</h3><p>On this blog, we talk a lot about <a href="https://rapids.ai/">RAPIDS</a>, a collection of GPU-accelerated data science libraries— what it is, how it works, and the principles driving its rapid development. Today, I won’t be addressing any of these items; instead, I’m going to show you how to deploy RAPIDS at scale using <a href="https://azure.microsoft.com/en-us/services/machine-learning-service/">Azure Machine Learning service</a>. If doing this just so happens to illustrate what RAPIDS is all about (bringing the compute to <em>your</em> problem), then I’d consider that doubly valuable.</p><h3>Starting at the End — a Distributed ML Workload</h3><p>I’m not very good at teasing things along; so, I’m just going to show you what all of this looks like after we’ve set it up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*y1sFBykg-roI9CCJpcEaKg.gif" /></figure><p>Here, you see a Jupyter notebook alongside the Dask Dashboard. It’s visualizing RAPIDS code processing 10s of millions of records from an 80 GB dataset of New York taxi trips to build a predictive model of fare prices. That all runs on an Azure Machine Learning service cluster with NVIDIA V100 GPUs that can be scaled up to any size you need with a single flag.</p><p>The rest of this article will walk through exactly how you can set up similar, GPU-accelerated, multi-node workflows using Azure Machine Learning.</p><h3>The Procedure</h3><p>Let’s start with a quick overview. First, you’ll use the Azure portal to set up the necessary resources. If you’re not familiar with the Azure portal, the links below will provide a step-by-step walkthrough.</p><ol><li>Create your <a href="#0fe8">Resource Group</a></li><li>Within your Resource Group, <a href="#5d28">create an Azure Machine Learning service Workspace</a></li><li>Within your Workspace, download the <a href="#fee3">Configuration json file</a></li><li>Within your Workspace, check your Usage + Quota to ensure you have enough quota to launch your desired cluster size</li></ol><p>Then, from your local machine, you’ll run our helper scripts to get the cluster running:</p><ol><li>Clone the demonstration code and helper scripts</li><li>Run the utility script to initialize the <strong>Azure Machine Learning service workspace</strong></li><li>Open your web-browser and play with the demonstration notebook</li></ol><h3>Diving into the Workload</h3><p>On your local machine, clone the <a href="https://github.com/rapidsai/notebooks-contrib">RAPIDS notebooks-contrib GitHub repository</a> containing demonstration code and helper scripts which streamline launching a RAPIDS cluster on Azure Machine Learning service. In your terminal, navigate to the <em>blog_notebooks/azureml </em>subdirectory from that repo. This directory includes:</p><ol><li>Scripts that you run on your local machine</li></ol><ul><li><a href="https://github.com/mt-jones/RAPIDS-AzureML/blob/master/start_azureml.py"><strong>start_azureml.py</strong></a> is the main utility that creates a <em>Compute</em> target, and an associated <em>Experiment</em> within a <em>Workspace</em> using the <a href="https://docs.microsoft.com/en-us/python/api/overview/azure/ml/intro?view=azure-ml-py"><em>Azure Machine Learning SDK for Python</em></a>. This can also optionally upload the input dataset to your Azure storage for faster processing times in the cloud.</li></ul><p>2. Scripts that the cluster automatically runs at startup</p><ul><li><a href="https://github.com/mt-jones/RAPIDS-AzureML/blob/master/rapids/rapids-0.9.yml"><strong>rapids-0.9.yml</strong></a> is a file specifying the versions of all the RAPIDS packages that the cluster should download as it creates a scalable VM</li><li><a href="https://github.com/mt-jones/RAPIDS-AzureML/blob/master/rapids/init_dask.py"><strong>init_dask.py</strong></a> is a Python script that each node within the cluster will execute to establish the Dask cluster</li></ul><p>Typical usage of this repository will look like this:</p><ol><li>Navigate to the root directory of <a href="https://github.com/mt-jones/RAPIDS-AzureML"><strong>RAPIDS-AzureML</strong></a></li><li>Issue the following command at the command-line:</li></ol><pre>./start_azureml.py \<br> --config=<strong>CONFIG_PATH</strong> \<br> --vm_size=<strong>VM_SIZE \<br> --</strong>node_count=<strong>N</strong></pre><p>● <strong>CONFIG_PATH</strong> is the path to your <a href="#_ou3kvsyva1jy">Configuration</a> file</p><p>● <strong>VM_SIZE</strong> is the size of the virtual machine you’d like the <em>Compute</em> target to possess (e.g. “Standard_NC12s_v3&quot; will build a cluster of 12-virtual-core nodes, with two V100 GPUs each)</p><p>● <strong>N</strong> is the number of nodes (virtual machines) you’d like to deploy</p><p>There are many more options to this utility script. You may issue</p><pre>./start_azureml.py --help</pre><p>to see more.</p><p>When this runs, it will build a new container image, install all of the necessary packages, and add it to your registry. <em>This may take half an hour or more</em>, but don’t worry, this build step is only necessary the first time you run the script. Azure will cache the resulting image for quick re-use.</p><p>The script uses the Azure Machine Learning SDK to launch a cluster, scale it up to the desired number of nodes, and link them all into a Dask cluster. To follow along with the process, you can use the Azure portal to view the logs and output as <a href="#59c6">documented below</a>. If the launch is taking a particularly long time, this portal is the best place to debug any issues. In some cases, an Azure region may be so busy that there are no available GPU instances, so the cluster will be unable to scale. If you see that issue frequently, you may want to try another region.</p><p>The last step is to open your web-browser, and navigate to <a href="http://localhost:8888/"><strong>http://localhost:8888/</strong></a> where an SSH tunnel has been created so that you can access Jupyter notebooks running RAPIDS from your local machine.</p><p>These scripts currently assume you are running from a UNIX-like environment (e.g. Linux, Mac OS, or Windows Subsystem for Linux) with an ssh client installed.</p><h3>The Notebook</h3><p>The notebook is based on the NYC Taxi demonstration from <a href="https://github.com/rapidsai/notebooks-contrib/blob/master/intermediate_notebooks/E2E/taxi/NYCTaxi-E2E.ipynb">RAPIDSAI Notebooks</a>. It starts with three years of taxi trip data (2014, 2015, 2016). Half-way through the year 2016, the structure (schema) of the data changed, so our ETL scripts need to handle that as well.</p><p>The above poses several questions: How do we (1) create an aggregate DataFrame with all data from these years, (2) use this data to create new features which can be, (3), leveraged to train a simple Gradient Boosted Decision Tree (GBDT) using XGBoost? Moreover, what does this process look like with RAPIDS?</p><p>The short answers to these questions are easy: the code looks a lot like Pandas, and the time it takes to execute depends on how many GPUs are available within your cluster, but can be as quick as a few seconds on a multi-node cluster.</p><p>The parallelization all builds on <a href="https://dask.org/">Dask</a> and uses a typical Dask approach:</p><ol><li>Initialize the client</li><li>Define a set of functions</li><li>Ask the client to load in the data</li><li>Ask the client to run the functions on the data</li></ol><p>The Dask client will construct a computational graph that it will eventually execute. Dask is lazy: it doesn’t like to execute until it knows as much as possible about what you’d like it to do (or until it absolutely has to execute).</p><p>The majority of this notebook will be familiar to Pandas users since the underlying libraries maintain the same APIs as Pandas wherever possible. The notebook also uses the Pandas-style <em>query</em> API to efficiently perform complex filtering ops. For a more detailed look into dataframe APIs in Dask, <a href="https://docs.dask.org/en/latest/dataframe-api.html">see the Dask documentation.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*OWwFkYHuf6BLt76aDFhHBQ.png" /><figcaption>Using cuDF’s query API to filter dataset</figcaption></figure><p>In order to get a solid accuracy measurement in the prediction phase of this workload, we needed to incorporate the calculation of Haversine distance. The RAPIDS cuDF library does not come baked with this function; in the near future, many geo-spatial algorithms will be introduced in the new library called <a href="https://medium.com/rapids-ai/releasing-cuspatial-to-accelerate-geospatial-and-spatiotemporal-processing-b686d8b32a9">cuSpatial</a>. For now, RAPIDS allows you to <em>define a new, GPU-accelerated function without using a low-level library like CUDA or a similarly flavored Python variant</em>. Not only can you write custom functions that are ported to the GPU for you, but those functions are then <em>parallelized across an arbitrary cluster size</em> for you. Moreover, the code we ended up writing looks like Python. No special decorators, or fancy imports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*UmhldQXkAwKraOQlbZf3VQ.png" /><figcaption>GPU-accelerated Haversine distance calculation</figcaption></figure><p>Training using XGBoost on GPU is also not complicated. It matches the standard XGBoost API and requires only a single parameter change — the <em>tree_method </em>should be set to <em>gpu_hist</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*IadJryMOdTILITb4LreTGQ.png" /><figcaption>GPU-accelerated XGBoost training</figcaption></figure><h3>Evaluating the model and wrapping up</h3><p>Now that we’ve built our model, let’s look at how accurately it predicts fare prices. Prediction can also be carried out in parallel on multiple nodes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*e3yiqmTWNYevEny4BPOQOw.png" /><figcaption>Prediction and metric calculation</figcaption></figure><p>Overall, our model predicts prices with a root mean square error of only about 2.0 off the true fare prices. Try launching the notebook on your own cluster to see if you can beat that score with a bit of feature engineering and XGBoost optimization. <strong>Don’t forget to use the Azure portal to shut down your compute nodes when you’re done with the experiment!</strong></p><p>Now that you’ve walked through one example notebook, you can reuse the setup scripts with your own workloads. Just add your own notebook to the <em>rapids</em> folder before running <em>start_azureml.py</em> and give it a shot.</p><p>This is just a first step for RAPIDS and Azure Machine Learning Service. We’ll be updating these scripts over time, including adding support for the new RAPIDS 0.10 release. If you find the code useful or have more questions, please reach out to us on Twitter <a href="https://twitter.com/rapidsai">@rapidsai</a>, or via our <a href="https://join.slack.com/t/rapids-goai/shared_invite/enQtMjE0Njg5NDQ1MDQxLTJiN2FkNTFkYmQ2YjY1OGI4NTc5Y2NlODQ3ZDdiODEwYmRiNTFhMzNlNTU5ZWJhZjA3NTg4NDZkMThkNTkxMGQ">RAPIDS Slack instance</a>.</p><h3>Appendix: Azure Machine Learning Service Configuration and Details</h3><p>Azure hosts a number of services under its <em>Marketplace</em>, including Azure Machine Learning service. These services are categorized. We’re interested in the <em>AI + Machine Learning</em> category. In particular, the <strong>Machine Learning service workspace</strong>. Everything we deploy will live in a Machine Learning service workspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*FCQ4X8cNPmsNG3hFTyHONA.png" /><figcaption>Microsoft Azure marketplace</figcaption></figure><h3>Resource Groups</h3><p>After you’ve logged into the Microsoft Azure portal online, you will see a homepage. It lists popular Azure services, useful links, and your most recent resources. While all of this is useful, we’re only interested in <em>Resource Groups</em>, and <em>how to create them</em> for the purpose of demonstrating RAPIDS at the scale of Azure Machine Learning service. The procedure for <em>creating a resource group</em> is simple.</p><ol><li>Navigate to the <strong>Resource groups </strong>page</li></ol><p>a) You can do this by clicking <em>Resource groups</em> on the home page</p><p>b)… or you can click <em>Create a resource</em> above and search for <em>Resource group</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KsKWQUpY32OxQwoLZ53Org.png" /></figure><p>2. Click <strong>Create</strong>, and you’ll see this page</p><p>a) You’ll need to select a <em>Subscription</em> with GPU resources available</p><p>b) You’ll need to select a <em>Region</em> with GPU resources available</p><p>c)… If you’re not sure, check out <a href="https://docs.microsoft.com/en-us/azure/virtual-machines/linux/sizes-gpu">this page on GPU optimized VM sizes</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/0*zsNJSS67FWlXXmsL" /><figcaption>Creating a resource group</figcaption></figure><p>3. Next, we’ll look at how to initialize the <strong>Machine Learning service workspace</strong> in the <a href="#_eilzgljewx3f">Workspaces</a> section.</p><h3>Workspaces</h3><p>Creating a <strong>Machine Learning service workspace</strong> is easy. To do so, we’ll follow these steps:</p><ol><li>Navigate to your <strong>Resource groups</strong> page. Be sure to select the correct subscription!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ai0JG9-HK9VDTDrAIi_LvQ.png" /></figure><p>2. Select the <em>Resource group</em> you just created, and click <em>Add</em> … I named mine <em>RAPIDS-AML</em></p><p>a)<strong> The blue box</strong> indicates where the <em>Add</em> button should be</p><p>b)<strong> The green box</strong> shows you what the resource collection will look like after we’ve added the <strong>Machine Learning service workspace</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bxV12Bx6vv_WHedqEPLmqw.png" /></figure><p>3. Selecting <em>Add</em>, takes us to the <strong>Marketplace</strong> I mentioned at the <a href="#_b1zlj927oqce">beginning of Getting Familiar with Azure Machine Learning service</a>. Now that we have a <em>Resource group</em>, we can add to it the <strong>Machine Learning service workspace</strong> by clicking on the service icon in the <strong>Marketplace</strong> and creating the service.</p><p>a) Be sure to select the correct <em>Subscription</em>!</p><p>b) Don’t forget to set the <em>Location</em> to a region where you have adequate GPU quota!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*L1d5Num60pRMVNoM45bVYw.png" /></figure><h3>Configuration</h3><p>In order to use the <a href="https://docs.microsoft.com/en-us/python/api/overview/azure/ml/intro?view=azure-ml-py"><em>Azure Machine Learning SDK for Python</em></a> to maximum effect, we need a file that encapsulates the information about a resource in a cleanly accessible format. Enter <strong>config.json</strong>. This file contains a dictionary list with key-values for the following:</p><p>● <strong>“subscription_id”</strong> — the <em>Subscription</em></p><p>● <strong>“resource_group”</strong> — the <em>Resource group</em></p><p>● <strong>“workspace_name”</strong> — the <em>Workspace</em></p><p>To download this file, select the <em>Workspace</em> with which you’re interested in working, and then click a button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0D3TjjdgwQK3vOyLrgYT2A.png" /><figcaption>Downloading config.json</figcaption></figure><h3>Viewing logs for your experiment</h3><p>To see real-time output from your experiment, including any error messages, select the experiment name from your Azure Machine Learning workspace. You will see a table at the bottom listing runs from this experiment. Click on the link to the latest run to see its detail page. From there, you can select the Logs tab (shown below) and use the tree of log files to navigate to the one you want to view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DW_l4uOgld4ef0gUdYMwFA.png" /></figure><h3>For more info on Azure Machine Learning and RAPIDS</h3><p>RAPIDS and Azure are each broad ecosystems, so this blog is just scratching the surface. If you want to learn more, here are a few resources we’d recommend:</p><p>● Azure Machine Learning service provides <a href="https://docs.microsoft.com/en-us/azure/machine-learning/">extensive documentation</a>.</p><p>● RAPIDS documentation is always up-to-date on <a href="https://docs.rapids.ai/">docs.rapids.ai</a>,</p><p>● You can get started learning XGBoost on <a href="https://rapids.ai/xgboost">the RAPIDS XGBoost landing page</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b51d5d5fde2b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rapids-ai/rapids-on-microsoft-azure-machine-learning-b51d5d5fde2b">RAPIDS on Microsoft Azure Machine Learning</a> was originally published in <a href="https://medium.com/rapids-ai">RAPIDS AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAPIDS Forest Inference Library: Prediction at 100 million rows per second]]></title>
            <link>https://medium.com/rapids-ai/rapids-forest-inference-library-prediction-at-100-million-rows-per-second-19558890bc35?source=rss-7518c982eedd------2</link>
            <guid isPermaLink="false">https://medium.com/p/19558890bc35</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[open-source-software]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[John Zedlewski]]></dc:creator>
            <pubDate>Thu, 29 Aug 2019 21:47:48 GMT</pubDate>
            <atom:updated>2019-08-30T04:07:50.906Z</atom:updated>
            <content:encoded><![CDATA[<p>By <a href="https://medium.com/u/8c1b5351d926">Andrey Adinets</a> and <a href="https://medium.com/u/7518c982eedd">John Zedlewski</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*X2I74QzcjRmaN0m8IXT39A.jpeg" /></figure><h3>Introduction</h3><p>Random forests (RF) and gradient-boosted decision trees (GBDTs) have become workhorse models of applied machine learning. XGBoost and LightGBM, popular packages implementing GBDT models, consistently rank among the most commonly used tools by data scientists on the Kaggle platform. We see similar interest in forest-based models in industry, where they are applied to problems ranging from inventory forecasting, to ad ranking, to medical diagnostics.</p><p>Using <a href="https://rapidsai.github.io/projects/cuml/en/0.9.0/api.html#cuml.ensemble.RandomForestClassifier">cuML’s random forest module</a>, <a href="https://xgboost.ai/">XGBoost</a>, or <a href="https://lightgbm.readthedocs.io/en/latest/">LightGBM</a>, data scientists have access to several high performance, GPU-accelerated <em>training </em>for forest models. But many users have found that carrying out inference (prediction) is now becoming a bottleneck. This can be an issue in both low-latency cases, where you need to apply a forest model to each instance arriving in a streaming context, or in high-throughput cases, where you run a forest model over millions or billions of samples from a database.</p><p>The new, open source Forest Inference Library (FIL) in RAPIDS cuML 0.9 can eliminate these bottlenecks by allowing users to accelerate GBDT and RF inference with GPUs. Users can train models as usual in XGBoost or LightGBM, save them to disk, then use FIL to reload those models and apply them to new data. Using FIL, a single V100 GPU can deliver up to 35x more inference throughput than a CPU-only node with 40 cores.</p><p>In this blog, we’ll dive into the details of what makes FIL fast, what features are improving in future releases, and how you can incorporate FIL into your pipelines.</p><h3>What is a Decision Tree?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/0*3QdrkilCOcWZ39zL" /><figcaption>A simple decision tree</figcaption></figure><p>Let’s start with a refresher on how a decision forest model, or forest for short, works. While RF and GBDT algorithms differ in the way they train the models, they both produce a decision forest as their output. A decision forest is a collection of decision trees. Each decision tree is a binary tree, in which every node has either 0 children (a leaf node) or 2 children (an inner node).</p><p>Each inner node references one of the features, or columns, of the data, and contains a threshold for comparison and a comparison operator. If, for a particular data sample, the comparison of its feature value is true, the path to one of the child nodes is taken; if it is false, the path to the other child node is taken. One of the paths is also marked default; it is taken if the feature value for the data sample is not defined.</p><p>Each leaf node of a decision tree contains an output value. For a particular data sample, a path from the root always reaches a specific leaf. The output value of that leaf is that the value that is produced by the decision tree for that sample. For ML applications, it is useful to view a tree as a piecewise-constant function of the data sample.</p><h3>What is a Decision Forest?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/0*SLvoamPqVzpUryW6" /><figcaption>A decision forest</figcaption></figure><p>A decision forest is just a collection of decision trees with an operation that defines how the output of the forest is defined in terms of the outputs of individual trees. The exact operation can differ, but the most widely used choices are summation, averaging and voting. Summation is typically used with GBDT-trained forests, whereas averaging and voting are used with RF-trained forests. Averaging is typically used for regression problems, whereas voting is used for classification, where the output of each tree is the class of the data sample.</p><p>For regression, the raw forest output is typically used, i.e. the sum of tree outputs for GBDT and the average for RF. For binary classification, additional transformations may be required. For example, with GBDT, the forest output is often fed into the sigmoid function <em>σ(x) = 1 / (1 + exp(-x))</em> to obtain the probability of the data sample belonging to class 1. Comparing the probability with a predetermined threshold is then used to get the class. For RF, voting produces the class of the data sample directly.</p><h3>Using FIL</h3><p>FIL is built on a C++ and CUDA core library, but most users will access it through the Python interface. You can find the full documentation <a href="https://rapidsai.github.io/projects/cuml/en/0.9.0/api.html#cuml.ForestInference">on the cuML docs site</a>, but the basic steps are pretty straightforward:</p><p><strong>(1) Install cuML 0.9 or later (which contains FIL)</strong></p><p>You can install cuML with the conda package manager, by building from source, or by using the built RAPIDS Docker containers. Easy installation instructions are always available <a href="https://rapids.ai/start.html#rapids-release-selector">on the rapids.ai getting started page</a>.</p><p><strong>(2) Build and save your model with XGBoost or LightGBM</strong></p><p>With either the <a href="https://xgboost.readthedocs.io/en/latest/python/python_intro.html#training">XGBoost </a>or <a href="https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.Booster.html#lightgbm.Booster.save_model">LightGBM </a>Python APIs, just call the save_model(&lt;filename&gt;) method on your model after training.</p><p><strong>(3) Load your model into FIL</strong></p><p>The ForestInference.load() method takes in a model filename and returns an FIL instance. This uses the open source treelite library to parse the package-specific saved model format and convert it to FIL’s internal tree representation.</p><p><strong>(4) Use the FIL instance to infer on your data</strong></p><p>FIL can take either data stored in CPU memory (e.g. numpy arrays) or GPU-based arrays. As with the rest of cuML, these GPU arrays can come from any library that supports the __cuda_array_interface__ API, including cuDF, Numba, cuPY, and others. You can eliminate data conversion work by passing in a row-major, FP32 GPU array.</p><p><strong>Bringing it all together</strong></p><p>The whole process only takes a few lines of code, as you can see in the example below:</p><pre>from cuml import ForestInference<br>import sklearn.datasets</pre><pre># Load the classifier previously saved with xgboost model_save()<br>model_path = ‘xgb.model’ <br>fm = ForestInference.load(model_path, output_class=True)</pre><pre># Generate random sample data<br>X_test, y_test = sklearn.datasets.make_classification()</pre><pre># Generate predictions (as a gpu array)<br>fil_preds_gpu = fm.predict(X_test.astype(‘float32’))</pre><p>For more detailed examples, check out <a href="https://github.com/rapidsai/notebooks/blob/branch-0.10/cuml/forest_inference_demo.ipynb">the FIL example notebook</a> and the FIL tests in cuML.</p><h3>FIL Design</h3><p>FIL is a part of cuML library dedicated specifically to forest inference. As such, itself it provides only forest inference, but no way of training forest models. Because of this, it needs to import forest models trained using other frameworks.</p><p>There is currently no standard file format to store forest-based models; every framework tends to define its own format. In order to support multiple input file formats, FIL imports data using the open source <a href="https://treelite.readthedocs.io/en/latest/">treelite</a> library. This enables FIL to support models trained in popular frameworks, such as <a href="https://xgboost.readthedocs.io/en/latest/">XGBoost</a> and <a href="https://lightgbm.readthedocs.io/en/latest/">LightGBM</a> (without categorical data).</p><p>The current version of FIL uses only dense trees internally. A dense tree of depth <em>d</em> is a tree in which the distance from the root to any of the leaves is equal to <em>d</em>. Such a tree contains exactly 2 ⋅ 2ᵈ + 1 nodes. In this way, the index of the child nodes can be computed from the index of the current node, and so need not be stored in the node itself. Thus, a forest of sparse trees can be imported into FIL by converting it into the dense layout. The dense tree structure provides a clean design and high performance, but it increases memory consumption for deep trees.</p><p>FIL provides several inference algorithms, as different algorithms can be optimal for different forests. However, all algorithms follow the same basic scheme. At the core of the algorithm is computing the sum of predictions of each tree, which needs to be done for each input data sample.</p><p>This stage for the basic scheme is shown in the figure below. One data sample is assigned to one thread block, and all threads in a block cooperate in computing the prediction for that data sample. First, the threads load the data sample. The trees are distributed cyclically among the threads in a block. Each thread computes the sum of predictions of the trees assigned to it, and then all threads perform a collective reduction to compute the sum of predictions, which is written into the global memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/0*RjcM5MTeIAYN1qKW" /><figcaption>Work distribution among threads in a block in FIL</figcaption></figure><p>Using a single data sample per thread block enables FIL to reduce the amount of shared memory required per block, and thus provides support for larger numbers of columns. For instance, for a single row with 256 columns, only 1 KiB of shared memory are required if each element is a 32-bit float. In contrast, with 1 thread per data sample and 128 threads per block, even 96 KiB of shared memory per block are not enough to store the complete data sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/0*QeS3zbHmRtWNnL-x" /><figcaption>Tree layout used in the NAIVE algorithm.</figcaption></figure><p>The NAIVE algorithm of FIL is the simplest implementation of the basic scheme described above. It also uses an often-used tree layout, in which the nodes of each tree is stored adjacent to each other, in the breadth-first, left-to-right order. Different trees of the forest are then stored next to each other.</p><p>The forest layout in the NAIVE algorithm is often-used, but not ideal from the GPU perspective. Recall that in FIL, neighboring trees are assigned to neighboring threads. Thus, for the NAIVE layout, the threads access tree data in a non-coalesced fashion, which results in suboptimal memory performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*qxTCHfepkF2NsXpJ" /><figcaption>Tree layout used in TREE_REORG and BATCH_TREE_REORG algorithms.</figcaption></figure><p>The TREE_REORG algorithm addresses this problem by using a different tree layout. For each tree, the nodes are still stored in the breadth-first, left-to-right order. However, instead of storing the nodes of the same tree adjacently, it uses a different layout. In this layout, the roots of all trees (node 0) are stored first, followed by left children of the roots of all trees (node 1), followed by the right children of the roots of all trees (node 2), and so on. This is possible, as all the layout used to store all trees is dense, and contains the same number of nodes. In this way, if the neighboring threads take the same path through the neighboring trees, they access the tree data at adjacent addresses, in a coalesced fashion. This mostly helps at small node depths; at larger node depths, the paths of threads through the trees diverge anyway, and the effect of the TREE_REORG layout diminishes.</p><p>The BATCH_TREE_REORG algorithm uses the same tree layout as TREE_REORG, but in addition to that, assigns more than one data sample to each thread block. This number remains small (&lt;= 4), and the trees are still distributed cyclically among the threads. However, each thread performs inference on all trees assigned to it, and on all samples assigned to the thread block.</p><p>After the forest inference proper, additional transformations are performed. They are performed in a separate kernel, and include a combination of any of the following steps:</p><ol><li>Averaging, i.e. dividing the sum of predictions by the number of trees; this is required to support RF.</li><li>Adding global_bias, which is often used in GBDT models.</li><li>Applying the sigmoid function to the output of the previous step.</li><li>Thresholding, i.e. comparing the output of the previous step to the specified threshold, and outputting 0 or 1 based on the result of the comparison.</li></ol><p>These additional transformations are required to support typical use cases of forest models, and the exact set of additional steps depends on the use case. For example, for GBDT regression, no additional steps are often required, while GBDT classification will actually use the steps 2, 3 and 4. RF classification is typically performed using voting, which is implemented in FIL as a combination of averaging and thresholding, i.e. steps 1 and 4.</p><h3>Performance Analysis</h3><p>Performance in FIL depends primarily on three factors:</p><ul><li>Number of trees (runtime is roughly linear in number of trees)</li><li>Storage format of input data (row-major GPU arrays are fastest, column-major arrays will need potentially-expensive conversion)</li><li>Batch size of input data (larger batches are slower but cost less on a per-row basis, as startup costs are amortized)</li><li>Tree depth (deeper is slower)</li></ul><p>Increasing the number of columns and also increases runtime, but this is typically not as significant as the factors above.</p><p>To analyze performance in more detail, we trained XGBoost classifiers on several real-world datasets from the <a href="https://github.com/NVIDIA/gbm-bench">GBM-Bench suite</a>.</p><ul><li>Higgs (28 columns, 11M rows)</li><li>Airline (13 columns, 115M rows)</li><li>Bosch (968 columns, 1.184M rows)</li><li>Epsilon (2000 columns, 500K rows)</li></ul><p>We compared FIL (0.9) with XGBoost (version 0.90.rapidsdev1), running on an NVIDIA DGX-1 server with a V100–32GB GPU and dual Xeon E5–2698v4 @ 2.20gHz CPUs. Where applicable, we also compare against treelite 0.9, a CPU-based implementation of forest inference that is particularly fast at small batch inference. XGBoost and treelite are set to run in parallel over all CPU cores. Before running inference, we converted the input data to the framework’s preferred input format: DMatrix for XGBoost, a row-major CPU array for treelite, and a row-major GPU array for FIL.</p><p>There is a huge matrix of possible parameters to compare, but for the purposes of this blog, we wanted to call out just a few slices of data that can help users better understand FIL and its performance implications.</p><h3>Comparing across datasets</h3><p>We start by looking at one target FIL application — high throughput inference for a reasonably-large model. In this case, we use a 1000-tree GBDT trained by XGBoost on several different datasets with max tree depth of 10, inferring on 1 million rows. For now, we’ll just include the default FIL algorithm (TREE_REORG).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/0*90sg0tb5_Md4DJAp" /><figcaption>CPU and GPU performance across datasets</figcaption></figure><p>For this problem size, FIL is consistently the fastest, exceeding the throughput of XGBoost on CPU or treelite by over 28x. On the airline dataset, a single V100 GPU can infer 15M rows per second, or well over 100M rows per second on an 8-GPU DGX-1 box.</p><p>XGBoost’s GPU-based inference is competitive with FIL in some cases, but it struggles on the very wide datasets (Bosch and epsilon). XGBoost uses a fixed thread block size with each thread processing all trees for a single row. With small column counts, this enables storing more rows in shared memory. However, when the column count becomes large, it doesn’t have enough shared memory, and falls back to reading data from global memory. With the shared memory size of 48KiB and 128 threads, this happens when the number of columns exceeds 96. This leads to a significant performance drop of XGBoost prediction on wide datasets.</p><h3>Comparing FIL Algorithms</h3><p>As noted earlier, FIL supports three different algorithms: NAIVE, TREE_REORG, and BATCH_TREE_REORG, so it’s worth comparing them in turn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*_selmFnr3RFqy3GU" /><figcaption>Small-batch comparison of FIL algorithms</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/0*lvakCEFN8PUSNaoy" /><figcaption>Large-batch comparison of FIL algorithms</figcaption></figure><p>In these examples, we see a fairly typical pattern. For small batches (&lt;=100 rows), inference is dominated by startup time, and all of the algorithms are roughly similar. For larger batches, NAIVE is significantly worse, and both BATCH_REORG and TREE_REORG have better performance. For the remainder of this blog, we’ll omit NAIVE, as it is typically not the preferred algorithm for large batch sizes.</p><h3>Impact of tree depth</h3><p>To measure the impact of tree depth on inference time, we can zoom in and focus only on models trained on the Higgs dataset. We can see that increasing depth does not have much impact beyond roughly a depth of 8 in this example. However, the deeper trees do consume significantly more GPU memory in FIL’s dense format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*syksbrpgDKQ6frQK" /><figcaption>Inference time scaling with increasing tree depth</figcaption></figure><h3>Scaling — number of rows</h3><p>Forest inference can be useful in both small-batch/online and large-batch/high throughput cases. The graph below shows how inference time per row scales as the batch size increases for various inference platforms, again using an example with 1000 trees and a max depth of 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KAOl-8S4gIzFyhly" /><figcaption>Inference time scaling as batch size increases</figcaption></figure><p>Runtime per row for the GPU-based implementations continues to improve as batch sizes grow, while the CPU-based implementations plateau at around 2.8 usec/row. Treelite outperforms other algorithms at batch size of 100, as it minimizes startup costs.</p><h3>Tips for maximizing FIL performance</h3><p>Based on these analyses and extensive internal testing, we’ve found a couple of guidelines that forest inference users should consider.</p><ul><li>If possible, provide FIL input data in as a row-major (also called ‘C’ order) GPU array. Other formats are supported but will require conversion internally</li><li>When building a model, consider that increasing tree depth will increase GPU memory consumption</li><li>Inferring on larger batch sizes can decrease cost-per-row significantly</li><li>If the input data is very sparse (almost all zeros or missing data), XGBoost’s DMatrix format may be more efficient than FIL’s dense format</li><li>The FIL_TREE_REORG and FIL_BATCH_TREE_REORG algorithms have similar, typically-efficient performance. You may get incremental gains by measuring which performs best for your particular algorithm.</li></ul><h3>Future Work</h3><p>FIL is currently most efficient for workloads with either large batches, wide column counts, or both, as those workloads allow us to fully utilize the GPU. Future versions of FIL will continue to improve performance on “narrow” (few column) and low batch workloads.</p><p>While FIL supports importing sparse trees, it uses the dense layout internally, which is not sustainable for very deep trees. In an upcoming version of FIL, we will add optional support for sparse trees, which will reduce memory consumption for deep trees. Next, FIL will add support for multi-class classification. We’re also evaluating native support for categorical variables in models (without a need to one-hot-encode the variable). Finally, for users who need to transfer data from CPU memory, we’re exploring options to overlap this transfer with compute time.</p><p>Apart from that, there are some further directions worth looking into. One such direction would be supporting sparse data efficiently. While FIL currently treats NaNs in missing data, a specific input format, e.g. compressed sparse rows (CSR) would be required for efficient handling of very sparse data. Another direction of work could be using reduced precision, e.g. 16-bit floats, in either the input data or the model.</p><p>These upcoming features are based on feedback from early testers, but we want your input too! If you have a feature request for FIL or find a problem, please file an issue on cuML at <a href="https://github.com/rapidsai/cuml/issues">https://github.com/rapidsai/cuml/issues</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19558890bc35" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rapids-ai/rapids-forest-inference-library-prediction-at-100-million-rows-per-second-19558890bc35">RAPIDS Forest Inference Library: Prediction at 100 million rows per second</a> was originally published in <a href="https://medium.com/rapids-ai">RAPIDS AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>