{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Example of training with Dask on GPU\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import dask\nimport dask_cudf\nfrom dask import array as da\nfrom dask import dataframe as dd\nfrom dask.distributed import Client\nfrom dask_cuda import LocalCUDACluster\n\nfrom xgboost import dask as dxgb\nfrom xgboost.dask import DaskDMatrix\n\n\ndef using_dask_matrix(client: Client, X: da.Array, y: da.Array) -> da.Array:\n    # DaskDMatrix acts like normal DMatrix, works as a proxy for local DMatrix scatter\n    # around workers.\n    dtrain = DaskDMatrix(client, X, y)\n\n    # Use train method from xgboost.dask instead of xgboost.  This distributed version\n    # of train returns a dictionary containing the resulting booster and evaluation\n    # history obtained from evaluation metrics.\n    output = dxgb.train(\n        client,\n        # Make sure the device is set to CUDA.\n        {\"tree_method\": \"hist\", \"device\": \"cuda\"},\n        dtrain,\n        num_boost_round=4,\n        evals=[(dtrain, \"train\")],\n    )\n    bst = output[\"booster\"]\n    history = output[\"history\"]\n\n    # you can pass output directly into `predict` too.\n    prediction = dxgb.predict(client, bst, dtrain)\n    print(\"Evaluation history:\", history)\n    return prediction\n\n\ndef using_quantile_device_dmatrix(client: Client, X: da.Array, y: da.Array) -> da.Array:\n    \"\"\"`DaskQuantileDMatrix` is a data type specialized for `hist` tree methods for\n     reducing memory usage.\n\n    .. versionadded:: 1.2.0\n\n    \"\"\"\n    # `DaskQuantileDMatrix` is used instead of `DaskDMatrix`, be careful that it can not\n    # be used for anything else other than training unless a reference is specified. See\n    # the `ref` argument of `DaskQuantileDMatrix`.\n    dtrain = dxgb.DaskQuantileDMatrix(client, X, y)\n    output = dxgb.train(\n        client,\n        # Make sure the device is set to CUDA.\n        {\"tree_method\": \"hist\", \"device\": \"cuda\"},\n        dtrain,\n        num_boost_round=4,\n        evals=[(dtrain, \"train\")],\n    )\n\n    prediction = dxgb.predict(client, output, X)\n    return prediction\n\n\nif __name__ == \"__main__\":\n    # `LocalCUDACluster` is used for assigning GPU to XGBoost processes.  Here\n    # `n_workers` represents the number of GPUs since we use one GPU per worker process.\n    with LocalCUDACluster(n_workers=2, threads_per_worker=4) as cluster:\n        # Create client from cluster, set the backend to GPU array (cupy).\n        with Client(cluster) as client, dask.config.set({\"array.backend\": \"cupy\"}):\n            # Generate some random data for demonstration\n            rng = da.random.default_rng(1)\n\n            m = 2**18\n            n = 100\n            X = rng.uniform(size=(m, n), chunks=(128**2, -1))\n            y = X.sum(axis=1)\n\n            X = dd.from_dask_array(X)\n            y = dd.from_dask_array(y)\n            # XGBoost can take arrays. This is to show that DataFrame uses the GPU\n            # backend as well.\n            assert isinstance(X, dask_cudf.DataFrame)\n            assert isinstance(y, dask_cudf.Series)\n\n            print(\"Using DaskQuantileDMatrix\")\n            from_ddqdm = using_quantile_device_dmatrix(client, X, y).compute()\n            print(\"Using DMatrix\")\n            from_dmatrix = using_dask_matrix(client, X, y).compute()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.17"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}