{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Example of forwarding evaluation logs to the client\n\nThe example runs on GPU. Two classes are defined to show how to use Dask builtins to\nforward the logs to the client process.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import logging\n\nimport dask\nimport distributed\nfrom dask import array as da\nfrom dask_cuda import LocalCUDACluster\nfrom distributed import Client\n\nfrom xgboost import dask as dxgb\nfrom xgboost.callback import EvaluationMonitor\n\n\ndef _get_logger() -> logging.Logger:\n    logger = logging.getLogger(\"[xgboost.dask]\")\n    logger.setLevel(logging.INFO)\n    if not logger.hasHandlers():\n        handler = logging.StreamHandler()\n        logger.addHandler(handler)\n    return logger\n\n\nclass ForwardLoggingMonitor(EvaluationMonitor):\n    def __init__(\n        self,\n        client: Client,\n        rank: int = 0,\n        period: int = 1,\n    ) -> None:\n        \"\"\"Print the evaluation result at each iteration. The default monitor in the\n        native interface logs the result to the Dask scheduler process. This class can\n        be used to forward the logging to the client process. Important: see the\n        `client` parameter for more info.\n\n        Parameters\n        ----------\n        client :\n            Distributed client. This must be the top-level client. The class uses\n            :py:meth:`distributed.Client.forward_logging` in conjunction with the Python\n            :py:mod:`logging` module to forward the evaluation results to the client\n            process. It has undefined behaviour if called in a nested task. As a result,\n            client-side logging is not enabled by default.\n\n        \"\"\"\n        client.forward_logging(_get_logger().name)\n\n        super().__init__(\n            rank=rank,\n            period=period,\n            logger=lambda msg: _get_logger().info(msg.strip()),\n        )\n\n\nclass WorkerEventMonitor(EvaluationMonitor):\n    \"\"\"Use :py:meth:`distributed.print` to forward the log. A downside is that not only\n    all clients connected to the cluster can see the log, the logs are also printed on\n    the worker. If you use a local cluster, the log is duplicated.\n\n    \"\"\"\n\n    def __init__(self, rank: int = 0, period: int = 1) -> None:\n        super().__init__(\n            rank=rank, period=period, logger=lambda msg: distributed.print(msg.strip())\n        )\n\n\ndef hist_train(\n    client: Client, X: da.Array, y: da.Array, monitor: EvaluationMonitor\n) -> da.Array:\n    # `DaskQuantileDMatrix` is used instead of `DaskDMatrix`, be careful that it can not\n    # be used for anything else other than as a training DMatrix, unless a reference is\n    # specified. See 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        # Use the monitor to forward the log.\n        callbacks=[monitor],\n        # Disable the internal logging and prefer the client-side `EvaluationMonitor`.\n        verbose_eval=False,\n    )\n    bst = output[\"booster\"]\n    history = output[\"history\"]\n\n    prediction = dxgb.predict(client, bst, X)\n    print(\"Evaluation history:\", history)\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            # Use forwarding, the client must be the top client.\n            monitor: EvaluationMonitor = ForwardLoggingMonitor(client)\n            hist_train(client, X, y, monitor).compute()\n\n            # Use distributed.print, the logs in this demo are duplicated as the same\n            # log is printed in all workers along with the client.\n            monitor = WorkerEventMonitor()\n            hist_train(client, X, y, monitor).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
}