|
| 1 | +""" |
| 2 | +Learning to rank with the Dask Interface |
| 3 | +======================================== |
| 4 | +
|
| 5 | + .. versionadded:: 3.0.0 |
| 6 | +
|
| 7 | +This is a demonstration of using XGBoost for learning to rank tasks using the |
| 8 | +MSLR_10k_letor dataset. For more infomation about the dataset, please visit its |
| 9 | +`description page <https://www.microsoft.com/en-us/research/project/mslr/>`_. |
| 10 | +
|
| 11 | +See :ref:`ltr-dist` for a general description for distributed learning to rank and |
| 12 | +:ref:`ltr-dask` for Dask-specific features. |
| 13 | +
|
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import argparse |
| 19 | +import os |
| 20 | +from contextlib import contextmanager |
| 21 | +from typing import Generator |
| 22 | + |
| 23 | +import dask |
| 24 | +import numpy as np |
| 25 | +from dask import dataframe as dd |
| 26 | +from distributed import Client, LocalCluster, wait |
| 27 | +from sklearn.datasets import load_svmlight_file |
| 28 | + |
| 29 | +from xgboost import dask as dxgb |
| 30 | + |
| 31 | + |
| 32 | +def load_mslr_10k( |
| 33 | + device: str, data_path: str, cache_path: str |
| 34 | +) -> tuple[dd.DataFrame, dd.DataFrame, dd.DataFrame]: |
| 35 | + """Load the MSLR10k dataset from data_path and save parquet files in the cache_path.""" |
| 36 | + root_path = os.path.expanduser(args.data) |
| 37 | + cache_path = os.path.expanduser(args.cache) |
| 38 | + |
| 39 | + # Use only the Fold1 for demo: |
| 40 | + # Train, Valid, Test |
| 41 | + # {S1,S2,S3}, S4, S5 |
| 42 | + fold = 1 |
| 43 | + |
| 44 | + if not os.path.exists(cache_path): |
| 45 | + os.mkdir(cache_path) |
| 46 | + fold_path = os.path.join(root_path, f"Fold{fold}") |
| 47 | + train_path = os.path.join(fold_path, "train.txt") |
| 48 | + valid_path = os.path.join(fold_path, "vali.txt") |
| 49 | + test_path = os.path.join(fold_path, "test.txt") |
| 50 | + |
| 51 | + X_train, y_train, qid_train = load_svmlight_file( |
| 52 | + train_path, query_id=True, dtype=np.float32 |
| 53 | + ) |
| 54 | + columns = [f"f{i}" for i in range(X_train.shape[1])] |
| 55 | + X_train = dd.from_array(X_train.toarray(), columns=columns) |
| 56 | + y_train = y_train.astype(np.int32) |
| 57 | + qid_train = qid_train.astype(np.int32) |
| 58 | + |
| 59 | + X_train["y"] = dd.from_array(y_train) |
| 60 | + X_train["qid"] = dd.from_array(qid_train) |
| 61 | + X_train.to_parquet(os.path.join(cache_path, "train"), engine="pyarrow") |
| 62 | + |
| 63 | + X_valid, y_valid, qid_valid = load_svmlight_file( |
| 64 | + valid_path, query_id=True, dtype=np.float32 |
| 65 | + ) |
| 66 | + X_valid = dd.from_array(X_valid.toarray(), columns=columns) |
| 67 | + y_valid = y_valid.astype(np.int32) |
| 68 | + qid_valid = qid_valid.astype(np.int32) |
| 69 | + |
| 70 | + X_valid["y"] = dd.from_array(y_valid) |
| 71 | + X_valid["qid"] = dd.from_array(qid_valid) |
| 72 | + X_valid.to_parquet(os.path.join(cache_path, "valid"), engine="pyarrow") |
| 73 | + |
| 74 | + X_test, y_test, qid_test = load_svmlight_file( |
| 75 | + test_path, query_id=True, dtype=np.float32 |
| 76 | + ) |
| 77 | + |
| 78 | + X_test = dd.from_array(X_test.toarray(), columns=columns) |
| 79 | + y_test = y_test.astype(np.int32) |
| 80 | + qid_test = qid_test.astype(np.int32) |
| 81 | + |
| 82 | + X_test["y"] = dd.from_array(y_test) |
| 83 | + X_test["qid"] = dd.from_array(qid_test) |
| 84 | + X_test.to_parquet(os.path.join(cache_path, "test"), engine="pyarrow") |
| 85 | + |
| 86 | + df_train = dd.read_parquet( |
| 87 | + os.path.join(cache_path, "train"), calculate_divisions=True |
| 88 | + ) |
| 89 | + df_valid = dd.read_parquet( |
| 90 | + os.path.join(cache_path, "valid"), calculate_divisions=True |
| 91 | + ) |
| 92 | + df_test = dd.read_parquet( |
| 93 | + os.path.join(cache_path, "test"), calculate_divisions=True |
| 94 | + ) |
| 95 | + |
| 96 | + return df_train, df_valid, df_test |
| 97 | + |
| 98 | + |
| 99 | +def ranking_demo(client: Client, args: argparse.Namespace) -> None: |
| 100 | + """Learning to rank with data sorted locally.""" |
| 101 | + df_tr, df_va, _ = load_mslr_10k(args.device, args.data, args.cache) |
| 102 | + |
| 103 | + X_train: dd.DataFrame = df_tr[df_tr.columns.difference(["y", "qid"])] |
| 104 | + y_train = df_tr[["y", "qid"]] |
| 105 | + Xy_train = dxgb.DaskQuantileDMatrix(client, X_train, y_train.y, qid=y_train.qid) |
| 106 | + |
| 107 | + X_valid: dd.DataFrame = df_va[df_va.columns.difference(["y", "qid"])] |
| 108 | + y_valid = df_va[["y", "qid"]] |
| 109 | + Xy_valid = dxgb.DaskQuantileDMatrix( |
| 110 | + client, X_valid, y_valid.y, qid=y_valid.qid, ref=Xy_train |
| 111 | + ) |
| 112 | + # Upon training, you will see a performance warning about sorting data based on |
| 113 | + # query groups. |
| 114 | + dxgb.train( |
| 115 | + client, |
| 116 | + {"objective": "rank:ndcg", "device": args.device}, |
| 117 | + Xy_train, |
| 118 | + evals=[(Xy_train, "Train"), (Xy_valid, "Valid")], |
| 119 | + num_boost_round=100, |
| 120 | + ) |
| 121 | + |
| 122 | + |
| 123 | +def ranking_wo_split_demo(client: Client, args: argparse.Namespace) -> None: |
| 124 | + """Learning to rank with data partitioned according to query groups.""" |
| 125 | + df_tr, df_va, df_te = load_mslr_10k(args.device, args.data, args.cache) |
| 126 | + |
| 127 | + X_tr = df_tr[df_tr.columns.difference(["y", "qid"])] |
| 128 | + X_va = df_va[df_va.columns.difference(["y", "qid"])] |
| 129 | + |
| 130 | + # `allow_group_split=False` makes sure data is partitioned according to the query |
| 131 | + # groups. |
| 132 | + ltr = dxgb.DaskXGBRanker(allow_group_split=False, device=args.device) |
| 133 | + ltr.client = client |
| 134 | + ltr = ltr.fit( |
| 135 | + X_tr, |
| 136 | + df_tr.y, |
| 137 | + qid=df_tr.qid, |
| 138 | + eval_set=[(X_tr, df_tr.y), (X_va, df_va.y)], |
| 139 | + eval_qid=[df_tr.qid, df_va.qid], |
| 140 | + verbose=True, |
| 141 | + ) |
| 142 | + |
| 143 | + df_te = df_te.persist() |
| 144 | + wait([df_te]) |
| 145 | + |
| 146 | + X_te = df_te[df_te.columns.difference(["y", "qid"])] |
| 147 | + predt = ltr.predict(X_te) |
| 148 | + y = client.compute(df_te.y) |
| 149 | + wait([predt, y]) |
| 150 | + |
| 151 | + |
| 152 | +@contextmanager |
| 153 | +def gen_client(device: str) -> Generator[Client, None, None]: |
| 154 | + match device: |
| 155 | + case "cuda": |
| 156 | + from dask_cuda import LocalCUDACluster |
| 157 | + |
| 158 | + with LocalCUDACluster() as cluster: |
| 159 | + with Client(cluster) as client: |
| 160 | + with dask.config.set( |
| 161 | + { |
| 162 | + "array.backend": "cupy", |
| 163 | + "dataframe.backend": "cudf", |
| 164 | + } |
| 165 | + ): |
| 166 | + yield client |
| 167 | + case "cpu": |
| 168 | + with LocalCluster() as cluster: |
| 169 | + with Client(cluster) as client: |
| 170 | + yield client |
| 171 | + |
| 172 | + |
| 173 | +if __name__ == "__main__": |
| 174 | + parser = argparse.ArgumentParser( |
| 175 | + description="Demonstration of learning to rank using XGBoost." |
| 176 | + ) |
| 177 | + parser.add_argument( |
| 178 | + "--data", |
| 179 | + type=str, |
| 180 | + help="Root directory of the MSLR-WEB10K data.", |
| 181 | + required=True, |
| 182 | + ) |
| 183 | + parser.add_argument( |
| 184 | + "--cache", |
| 185 | + type=str, |
| 186 | + help="Directory for caching processed data.", |
| 187 | + required=True, |
| 188 | + ) |
| 189 | + parser.add_argument("--device", choices=["cpu", "cuda"], default="cpu") |
| 190 | + parser.add_argument( |
| 191 | + "--no-split", |
| 192 | + action="store_true", |
| 193 | + help="Flag to indicate query groups should not be split.", |
| 194 | + ) |
| 195 | + args = parser.parse_args() |
| 196 | + |
| 197 | + with gen_client(args.device) as client: |
| 198 | + if args.no_split: |
| 199 | + ranking_wo_split_demo(client, args) |
| 200 | + else: |
| 201 | + ranking_demo(client, args) |
0 commit comments