A custom iterator for loading files in batches.
| 71 | |
| 72 | |
| 73 | class Iterator(xgboost.DataIter): |
| 74 | """A custom iterator for loading files in batches.""" |
| 75 | |
| 76 | def __init__(self, device: str, file_paths: List[Tuple[str, str]]) -> None: |
| 77 | self.device = device |
| 78 | |
| 79 | self._file_paths = file_paths |
| 80 | self._it = 0 |
| 81 | # XGBoost will generate some cache files under the current directory with the |
| 82 | # prefix "cache" |
| 83 | super().__init__(cache_prefix=os.path.join(".", "cache")) |
| 84 | |
| 85 | def load_file(self) -> Tuple[np.ndarray, np.ndarray]: |
| 86 | """Load a single batch of data.""" |
| 87 | X_path, y_path = self._file_paths[self._it] |
| 88 | # When the `ExtMemQuantileDMatrix` is used, the device must match. GPU cannot |
| 89 | # consume CPU input data and vice-versa. |
| 90 | if self.device == "cpu": |
| 91 | X = np.load(X_path) |
| 92 | y = np.load(y_path) |
| 93 | else: |
| 94 | import cupy as cp |
| 95 | |
| 96 | X = cp.load(X_path) |
| 97 | y = cp.load(y_path) |
| 98 | |
| 99 | assert X.shape[0] == y.shape[0] |
| 100 | return X, y |
| 101 | |
| 102 | def next(self, input_data: Callable) -> bool: |
| 103 | """Advance the iterator by 1 step and pass the data to XGBoost. This function |
| 104 | is called by XGBoost during the construction of ``DMatrix`` |
| 105 | |
| 106 | """ |
| 107 | if self._it == len(self._file_paths): |
| 108 | # return False to let XGBoost know this is the end of iteration |
| 109 | return False |
| 110 | |
| 111 | # input_data is a keyword-only function passed in by XGBoost and has the similar |
| 112 | # signature to the ``DMatrix`` constructor. |
| 113 | X, y = self.load_file() |
| 114 | input_data(data=X, label=y) |
| 115 | self._it += 1 |
| 116 | return True |
| 117 | |
| 118 | def reset(self) -> None: |
| 119 | """Reset the iterator to its beginning""" |
| 120 | self._it = 0 |
| 121 | |
| 122 | |
| 123 | def setup_numa() -> None: |