{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Experimental support for external memory\n\nThis is similar to the one in `quantile_data_iterator.py`, but for external memory\ninstead of Quantile DMatrix.  The feature is not ready for production use yet.\n\n    .. versionadded:: 1.5.0\n\n\nSee :doc:`the tutorial </tutorials/external_memory>` for more details.\n\n    .. versionchanged:: 3.0.0\n\n        Added :py:class:`~xgboost.ExtMemQuantileDMatrix`.\n\nTo run the example, following packages in addition to XGBoost native dependencies are\nrequired:\n\n- scikit-learn\n\nIf `device` is `cuda`, following are also needed:\n\n- cupy\n- rmm\n- cuda-python\n\n.. seealso::\n\n  `sphx_glr_python_examples_distributed_extmem_basic.py`\n\nNot shown in this example, but you should pay attention to NUMA configuration as\ndiscussed in the tutorial.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import argparse\nimport os\nimport tempfile\nfrom typing import TYPE_CHECKING, Callable, List, Literal, Tuple\n\nimport numpy as np\nfrom sklearn.datasets import make_regression\n\nimport xgboost\n\nif TYPE_CHECKING:\n    from cuda.bindings.runtime import cudaError_t\n\n\ndef _checkcu(status: \"cudaError_t\") -> None:\n    import cuda.bindings.runtime as cudart\n\n    if status != cudart.cudaError_t.cudaSuccess:\n        raise RuntimeError(cudart.cudaGetErrorString(status))\n\n\ndef device_mem_total() -> int:\n    \"\"\"The total number of bytes of memory this GPU has.\"\"\"\n    import cuda.bindings.runtime as cudart\n\n    status, free, total = cudart.cudaMemGetInfo()\n    _checkcu(status)\n    return total\n\n\ndef make_batches(\n    n_samples_per_batch: int,\n    n_features: int,\n    n_batches: int,\n    tmpdir: str,\n) -> List[Tuple[str, str]]:\n    files: List[Tuple[str, str]] = []\n    rng = np.random.RandomState(1994)\n    for i in range(n_batches):\n        X, y = make_regression(n_samples_per_batch, n_features, random_state=rng)\n        X_path = os.path.join(tmpdir, \"X-\" + str(i) + \".npy\")\n        y_path = os.path.join(tmpdir, \"y-\" + str(i) + \".npy\")\n        np.save(X_path, X)\n        np.save(y_path, y)\n        files.append((X_path, y_path))\n    return files\n\n\nclass Iterator(xgboost.DataIter):\n    \"\"\"A custom iterator for loading files in batches.\"\"\"\n\n    def __init__(\n        self, device: Literal[\"cpu\", \"cuda\"], file_paths: List[Tuple[str, str]]\n    ) -> None:\n        self.device = device\n\n        self._file_paths = file_paths\n        self._it = 0\n        # XGBoost will generate some cache files under the current directory with the\n        # prefix \"cache\"\n        super().__init__(cache_prefix=os.path.join(\".\", \"cache\"))\n\n    def load_file(self) -> Tuple[np.ndarray, np.ndarray]:\n        \"\"\"Load a single batch of data.\"\"\"\n        X_path, y_path = self._file_paths[self._it]\n        # When the `ExtMemQuantileDMatrix` is used, the device must match. GPU cannot\n        # consume CPU input data and vice-versa.\n        if self.device == \"cpu\":\n            X = np.load(X_path)\n            y = np.load(y_path)\n        else:\n            X = cp.load(X_path)\n            y = cp.load(y_path)\n\n        assert X.shape[0] == y.shape[0]\n        return X, y\n\n    def next(self, input_data: Callable) -> bool:\n        \"\"\"Advance the iterator by 1 step and pass the data to XGBoost.  This function\n        is called by XGBoost during the construction of ``DMatrix``\n\n        \"\"\"\n        if self._it == len(self._file_paths):\n            # return False to let XGBoost know this is the end of iteration\n            return False\n\n        # input_data is a keyword-only function passed in by XGBoost and has the similar\n        # signature to the ``DMatrix`` constructor.\n        X, y = self.load_file()\n        input_data(data=X, label=y)\n        self._it += 1\n        return True\n\n    def reset(self) -> None:\n        \"\"\"Reset the iterator to its beginning\"\"\"\n        self._it = 0\n\n\ndef hist_train(it: Iterator) -> None:\n    \"\"\"The hist tree method can use a special data structure `ExtMemQuantileDMatrix` for\n    faster initialization and lower memory usage (recommended).\n\n    .. versionadded:: 3.0.0\n\n    \"\"\"\n    # For non-data arguments, specify it here once instead of passing them by the `next`\n    # method.\n    Xy = xgboost.ExtMemQuantileDMatrix(it, missing=np.nan, enable_categorical=False)\n    booster = xgboost.train(\n        {\"tree_method\": \"hist\", \"max_depth\": 4, \"device\": it.device},\n        Xy,\n        evals=[(Xy, \"Train\")],\n        num_boost_round=10,\n    )\n    booster.predict(Xy)\n\n\ndef approx_train(it: Iterator) -> None:\n    \"\"\"The approx tree method uses the basic `DMatrix` (not recommended).\"\"\"\n\n    # For non-data arguments, specify it here once instead of passing them by the `next`\n    # method.\n    Xy = xgboost.DMatrix(it, missing=np.nan, enable_categorical=False)\n    # ``approx`` is also supported, but less efficient due to sketching. It's\n    # recommended to use `hist` instead.\n    booster = xgboost.train(\n        {\"tree_method\": \"approx\", \"max_depth\": 4, \"device\": it.device},\n        Xy,\n        evals=[(Xy, \"Train\")],\n        num_boost_round=10,\n    )\n    booster.predict(Xy)\n\n\ndef main(tmpdir: str, args: argparse.Namespace) -> None:\n    \"\"\"Entry point for training.\"\"\"\n\n    # generate some random data for demo\n    files = make_batches(\n        n_samples_per_batch=1024, n_features=17, n_batches=31, tmpdir=tmpdir\n    )\n    it = Iterator(args.device, files)\n\n    hist_train(it)\n    approx_train(it)\n\n\ndef setup_async_pool() -> None:\n    \"\"\"Setup CUDA async pool. As an alternative, the RMM plugin can be used as well. See\n    the `setup_rmm`. This is the same as using the `CudaAsyncMemoryResource` from RMM,\n    but without the RMM dependency.\n\n    .. versionadded:: 3.2.0\n\n    \"\"\"\n    import cuda.bindings.driver as driver\n    import cuda.bindings.runtime as cudart\n    from cupy.cuda import MemoryAsyncPool\n\n    status, dft_pool = cudart.cudaDeviceGetDefaultMemPool(0)\n    _checkcu(status)\n\n    total = device_mem_total()\n\n    v = driver.cuuint64_t(int(total * 0.9))\n    (status,) = cudart.cudaMemPoolSetAttribute(\n        dft_pool,\n        cudart.cudaMemPoolAttr.cudaMemPoolAttrReleaseThreshold,\n        v,\n    )\n    _checkcu(status)\n    # Set the allocator for cupy as well.\n    cp.cuda.set_allocator(MemoryAsyncPool().malloc)\n\n\ndef setup_rmm() -> None:\n    \"\"\"Setup RMM for GPU-based external memory training.\n\n    It's important to use RMM with `CudaAsyncMemoryResource` or `ArenaMemoryResource`\n    for GPU-based external memory to improve performance. If XGBoost is not built with\n    RMM support, a warning is raised when constructing the `DMatrix`.\n\n    \"\"\"\n\n    import rmm\n    from rmm.allocators.cupy import rmm_cupy_allocator\n    from rmm.mr import ArenaMemoryResource\n\n    if not xgboost.build_info()[\"USE_RMM\"]:\n        return\n\n    total = device_mem_total()\n\n    mr = rmm.mr.CudaMemoryResource()\n    mr = ArenaMemoryResource(mr, arena_size=int(total * 0.9))\n\n    rmm.mr.set_current_device_resource(mr)\n    # Set the allocator for cupy as well.\n    cp.cuda.set_allocator(rmm_cupy_allocator)\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--device\", choices=[\"cpu\", \"cuda\"], default=\"cpu\")\n    parser.add_argument(\n        \"--memory_pool\",\n        choices=[\"rmm\", \"cuda\"],\n        default=\"rmm\",\n        help=\"Use a memory pool for asynchronous memory allocation in XGBoost.\",\n    )\n    args = parser.parse_args()\n    if args.device == \"cuda\":\n        import cupy as cp\n\n        if args.memory_pool == \"rmm\":\n            setup_rmm()\n        elif args.memory_pool == \"cuda\":\n            setup_async_pool()\n        # Make sure XGBoost is using RMM for all allocations.\n        with xgboost.config_context(\n            use_rmm=args.memory_pool == \"rmm\",\n            use_cuda_async_pool=args.memory_pool == \"cuda\",\n        ):\n            with tempfile.TemporaryDirectory() as tmpdir:\n                main(tmpdir, args)\n    else:\n        with tempfile.TemporaryDirectory() as tmpdir:\n            main(tmpdir, args)"
      ]
    }
  ],
  "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
}