{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Experimental support for distributed training with external memory\n\n    .. versionadded:: 3.0.0\n\nSee :doc:`the tutorial </tutorials/external_memory>` for more details. To run the\nexample, following packages in addition to XGBoost native dependencies are required:\n\n- scikit-learn\n- loky\n\nIf `device` is `cuda`, following are also needed:\n\n- cupy\n- cuda-python\n- pyhwloc\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import argparse\nimport multiprocessing as mp\nimport os\nimport sys\nimport tempfile\nimport traceback\nfrom functools import partial, update_wrapper, wraps\nfrom typing import TYPE_CHECKING, Callable, List, ParamSpec, Tuple, TypeVar\n\nimport numpy as np\nimport xgboost\nfrom loky import get_reusable_executor\nfrom sklearn.datasets import make_regression\nfrom xgboost import collective as coll\nfrom xgboost.tracker import RabitTracker\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, _, total = cudart.cudaMemGetInfo()\n    _checkcu(status)\n    return total\n\n\ndef make_batches(\n    n_samples_per_batch: int, n_features: int, n_batches: int, tmpdir: str, rank: int\n) -> List[Tuple[str, str]]:\n    \"\"\"Create multiple batches of synthetic data and return their file paths.\"\"\"\n    files: List[Tuple[str, str]] = []\n    rng = np.random.RandomState(rank)\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, f\"X-r{rank}-{i}.npy\")\n        y_path = os.path.join(tmpdir, f\"y-r{rank}-{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__(self, device: str, file_paths: List[Tuple[str, str]]) -> 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            import cupy as cp\n\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 setup_numa() -> None:\n    \"\"\"Set correct NUMA binding for GPU-based external memory training.\"\"\"\n    from pyhwloc import from_this_system\n    from pyhwloc.cuda_runtime import get_device\n    from pyhwloc.topology import MemBindFlags, MemBindPolicy, TypeFilter\n\n    devices = os.getenv(\"CUDA_VISIBLE_DEVICES\", None)\n    assert devices is not None, \"CUDA_VISIBLE_DEVICES must be set.\"\n\n    with from_this_system().set_io_types_filter(TypeFilter.KEEP_ALL) as topo:\n        # Get CPU affinity for this GPU. Device ordinal 0 is used because\n        # CUDA_VISIBLE_DEVICES has already reordered the devices.\n        dev = get_device(topo, device=0)\n        cpuset = dev.get_affinity()\n\n        # Set CPU binding\n        topo.set_cpubind(cpuset)\n        # Set memory binding with STRICT policy - ensures all memory allocations come\n        # from the local NUMA node. hwloc determines the NUMA nodes from cpuset.\n        topo.set_membind(cpuset, MemBindPolicy.BIND, MemBindFlags.STRICT)\n\n\ndef setup_async_pool() -> None:\n    \"\"\"Setup CUDA async pool. As an alternative, the RMM plugin can be used as well.\n    This is the same as using the `CudaAsyncMemoryResource` from RMM, but without the\n    RMM dependency.\n\n    .. versionadded:: 3.2.0\n\n    \"\"\"\n    import cuda.bindings.runtime as cudart\n    from cuda.bindings import driver\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    import cupy as cp\n\n    cp.cuda.set_allocator(MemoryAsyncPool().malloc)\n\n\nR = TypeVar(\"R\")\nP = ParamSpec(\"P\")\n\n\ndef try_run(fn: Callable[P, R]) -> Callable[P, R]:\n    \"\"\"Loky aborts the process without printing out any error message if there's an\n    exception.\n\n    \"\"\"\n\n    @wraps(fn)\n    def inner(*args: P.args, **kwargs: P.kwargs) -> R:\n        try:\n            return fn(*args, **kwargs)\n        except Exception as e:\n            print(traceback.format_exc(), file=sys.stderr)\n            raise RuntimeError(\"Running into exception in worker.\") from e\n\n    return inner\n\n\n@try_run\ndef hist_train(\n    worker_idx: int,\n    tmpdir: str,\n    device: str,\n    rabit_args: dict,\n) -> None:\n    \"\"\"The hist tree method can use a special data structure `ExtMemQuantileDMatrix` for\n    faster initialization and lower memory usage.\n\n    \"\"\"\n\n    # Make sure XGBoost is using the configured memory pool for all allocations.\n    with (\n        coll.CommunicatorContext(**rabit_args),\n        xgboost.config_context(\n            use_cuda_async_pool=device == \"cuda\",\n        ),\n    ):\n        print(\"Worker: \", worker_idx)\n        # Generate the data for demonstration. The synthetic data is sharded by workers.\n        files = make_batches(\n            n_samples_per_batch=4096,\n            n_features=16,\n            n_batches=17,\n            tmpdir=tmpdir,\n            rank=coll.get_rank(),\n        )\n        # Since we are running two workers on a single node, we should divide the number\n        # of threads between workers.\n        n_threads = os.cpu_count()\n        assert n_threads is not None\n        n_threads = max(n_threads // coll.get_world_size(), 1)\n        it = Iterator(device, files)\n        Xy = xgboost.ExtMemQuantileDMatrix(\n            it, missing=np.nan, enable_categorical=False, nthread=n_threads\n        )\n        # Check the device is correctly set.\n        if device == \"cuda\":\n            # Check the first device\n            assert (\n                int(os.environ[\"CUDA_VISIBLE_DEVICES\"].split(\",\")[0])\n                < coll.get_world_size()\n            )\n        booster = xgboost.train(\n            {\n                \"tree_method\": \"hist\",\n                \"max_depth\": 4,\n                \"device\": it.device,\n                \"nthread\": n_threads,\n            },\n            Xy,\n            evals=[(Xy, \"Train\")],\n            num_boost_round=10,\n        )\n        booster.predict(Xy)\n\n\ndef launch_workers(tmpdir: str, args: argparse.Namespace) -> None:\n    \"\"\"Client function to launch workers.\"\"\"\n    n_workers = 2\n\n    tracker = RabitTracker(host_ip=\"127.0.0.1\", n_workers=n_workers)\n    tracker.start()\n    rabit_args = tracker.worker_args()\n\n    def initializer(device: str) -> None:\n        # Set CUDA device before launching child processes.\n        if device == \"cuda\":\n            # name: LokyProcess-1\n            _, sidx = mp.current_process().name.split(\"-\")\n            idx = int(sidx) - 1  # 1-based indexing from loky\n            # Assuming two workers for demo.\n            devices = \",\".join([str(idx), str((idx + 1) % n_workers)])\n            # P0: CUDA_VISIBLE_DEVICES=0,1\n            # P1: CUDA_VISIBLE_DEVICES=1,0\n            os.environ[\"CUDA_VISIBLE_DEVICES\"] = devices\n            setup_numa()\n            setup_async_pool()\n\n    with get_reusable_executor(\n        max_workers=n_workers,\n        initargs=(args.device,),\n        initializer=initializer,\n    ) as pool:\n        # Poor man's currying\n        fn = update_wrapper(\n            partial(\n                hist_train,\n                tmpdir=tmpdir,\n                device=args.device,\n                rabit_args=rabit_args,\n            ),\n            hist_train,\n        )\n        pool.map(fn, range(n_workers))\n\n\ndef main() -> None:\n    \"\"\"Demo for distributed training from scratch.\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--device\", choices=[\"cpu\", \"cuda\"], default=\"cpu\")\n    args = parser.parse_args()\n    with tempfile.TemporaryDirectory() as tmpdir:\n        launch_workers(tmpdir, args)\n\n\nif __name__ == \"__main__\":\n    main()"
      ]
    }
  ],
  "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
}