Experimental support for distributed training with external memory
as
mp
import
os
import
sys
import
tempfile
import
traceback
from
functools
import
,
,
from
typing
import
,
,
,
,
,
import
numpy
as
np
import
xgboost
from
loky
import
get_reusable_executor
from
sklearn.datasets
import
from
xgboost
import
collective
as
coll
from
xgboost.tracker
import
RabitTracker
if
:
from
cuda.bindings.runtime
import
cudaError_t
def
_checkcu
(
status
:
"cudaError_t"
)
->
None
:
import
cuda.bindings.runtime
as
cudart
if
status
!=
cudart
.
cudaError_t
.
cudaSuccess
:
raise
RuntimeError
(
cudart
.
cudaGetErrorString
(
status
))
def
device_mem_total
()
->
int
:
"""The total number of bytes of memory this GPU has."""
import
cuda.bindings.runtime
as
cudart
status
,
_
,
total
=
cudart
.
cudaMemGetInfo
()
_checkcu
(
status
)
return
total
def
make_batches
(
n_samples_per_batch
:
int
,
n_features
:
int
,
n_batches
:
int
,
tmpdir
:
str
,
rank
:
int
)
->
[
[
str
,
str
]]:
"""Create multiple batches of synthetic data and return their file paths."""
files
:
[
[
str
,
str
]]
=
[]
rng
=
(
rank
)
for
i
in
range
(
n_batches
):
X
,
y
=
(
n_samples_per_batch
,
n_features
,
random_state
=
rng
)
X_path
=
(
tmpdir
,
f
"X-r
{
rank
}
-
{
i
}
.npy"
)
y_path
=
(
tmpdir
,
f
"y-r
{
rank
}
-
{
i
}
.npy"
)
(
X_path
,
X
)
(
y_path
,
y
)
files
.
append
((
X_path
,
y_path
))
return
files
class
Iterator
(
xgboost
.
DataIter
):
"""A custom iterator for loading files in batches."""
def
__init__
(
self
,
device
:
str
,
file_paths
:
[
[
str
,
str
]])
->
None
:
self
.
device
=
device
self
.
_file_paths
=
file_paths
self
.
_it
=
0
super
()
.
__init__
(
cache_prefix
=
(
"."
,
"cache"
))
def
load_file
(
self
)
->
[
,
]:
"""Load a single batch of data."""
X_path
,
y_path
=
self
.
_file_paths
[
self
.
_it
]
if
self
.
device
==
"cpu"
:
X
=
(
X_path
)
y
=
(
y_path
)
else
:
import
cupy
as
cp
X
=
cp
.
load
(
X_path
)
y
=
cp
.
load
(
y_path
)
assert
X
.
shape
[
0
]
==
y
.
shape
[
0
]
return
X
,
y
def
next
(
self
,
input_data
:
)
->
bool
:
"""Advance the iterator by 1 step and pass the data to XGBoost. This function
is called by XGBoost during the construction of ``DMatrix``
"""
if
self
.
_it
==
len
(
self
.
_file_paths
):
return
False
X
,
y
=
self
.
load_file
()
input_data
(
data
=
X
,
label
=
y
)
self
.
_it
+=
1
return
True
def
reset
(
self
)
->
None
:
"""Reset the iterator to its beginning"""
self
.
_it
=
0
def
setup_numa
()
->
None
:
"""Set correct NUMA binding for GPU-based external memory training."""
from
pyhwloc
import
from_this_system
from
pyhwloc.cuda_runtime
import
get_device
from
pyhwloc.topology
import
MemBindFlags
,
MemBindPolicy
,
TypeFilter
devices
=
(
"CUDA_VISIBLE_DEVICES"
,
None
)
assert
devices
is
not
None
,
"CUDA_VISIBLE_DEVICES must be set."
with
from_this_system
()
.
set_io_types_filter
(
TypeFilter
.
KEEP_ALL
)
as
topo
:
dev
=
get_device
(
topo
,
device
=
0
)
cpuset
=
dev
.
get_affinity
()
topo
.
set_cpubind
(
cpuset
)
topo
.
set_membind
(
cpuset
,
MemBindPolicy
.
BIND
,
MemBindFlags
.
STRICT
)
def
setup_async_pool
()
->
None
:
"""Setup CUDA async pool. As an alternative, the RMM plugin can be used as well.
This is the same as using the `CudaAsyncMemoryResource` from RMM, but without the
RMM dependency.
.. versionadded:: 3.2.0
"""
import
cuda.bindings.runtime
as
cudart
from
cuda.bindings
import
driver
from
cupy.cuda
import
MemoryAsyncPool
status
,
dft_pool
=
cudart
.
cudaDeviceGetDefaultMemPool
(
0
)
_checkcu
(
status
)
total
=
device_mem_total
()
v
=
driver
.
cuuint64_t
(
int
(
total
*
0.9
))
(
status
,)
=
cudart
.
cudaMemPoolSetAttribute
(
dft_pool
,
cudart
.
cudaMemPoolAttr
.
cudaMemPoolAttrReleaseThreshold
,
v
,
)
_checkcu
(
status
)
import
cupy
as
cp
cp
.
cuda
.
set_allocator
(
MemoryAsyncPool
()
.
malloc
)
R
=
(
"R"
)
P
=
(
"P"
)
def
try_run
(
fn
:
[
P
,
R
])
->
[
P
,
R
]:
"""Loky aborts the process without printing out any error message if there's an
exception.
"""
@wraps
(
fn
)
def
inner
(
*
args
:
P
.
args
,
**
kwargs
:
P
.
kwargs
)
->
R
:
try
:
return
fn
(
*
args
,
**
kwargs
)
except
Exception
as
e
:
print
(
(),
file
=
)
raise
RuntimeError
(
"Running into exception in worker."
)
from
e
return
inner
@try_run
def
hist_train
(
worker_idx
:
int
,
tmpdir
:
str
,
device
:
str
,
rabit_args
:
dict
,
)
->
None
:
"""The hist tree method can use a special data structure `ExtMemQuantileDMatrix` for
faster initialization and lower memory usage.
"""
with
(
coll
.
CommunicatorContext
(
**
rabit_args
),
xgboost
.
config_context
(
use_cuda_async_pool
=
device
==
"cuda"
,
),
):
print
(
"Worker: "
,
worker_idx
)
files
=
make_batches
(
n_samples_per_batch
=
4096
,
n_features
=
16
,
n_batches
=
17
,
tmpdir
=
tmpdir
,
rank
=
coll
.
get_rank
(),
)
n_threads
=
()
assert
n_threads
is
not
None
n_threads
=
max
(
n_threads
//
coll
.
get_world_size
(),
1
)
it
=
Iterator
(
device
,
files
)
Xy
=
xgboost
.
ExtMemQuantileDMatrix
(
it
,
missing
=
,
enable_categorical
=
False
,
nthread
=
n_threads
)
if
device
==
"cuda"
:
assert
(
int
(
[
"CUDA_VISIBLE_DEVICES"
]
.
split
(
","
)[
0
])
<
coll
.
get_world_size
()
)
booster
=
xgboost
.
train
(
{
"tree_method"
:
"hist"
,
"max_depth"
:
4
,
"device"
:
it
.
device
,
"nthread"
:
n_threads
,
},
Xy
,
evals
=
[(
Xy
,
"Train"
)],
num_boost_round
=
10
,
)
booster
.
predict
(
Xy
)
def
launch_workers
(
tmpdir
:
str
,
args
:
)
->
None
:
"""Client function to launch workers."""
n_workers
=
2
tracker
=
RabitTracker
(
host_ip
=
"127.0.0.1"
,
n_workers
=
n_workers
)
tracker
.
start
()
rabit_args
=
tracker
.
worker_args
()
def
initializer
(
device
:
str
)
->
None
:
if
device
==
"cuda"
:
_
,
sidx
=
()
.
name
.
split
(
"-"
)
idx
=
int
(
sidx
)
-
1
devices
=
","
.
join
([
str
(
idx
),
str
((
idx
+
1
)
%
n_workers
)])
[
"CUDA_VISIBLE_DEVICES"
]
=
devices
setup_numa
()
setup_async_pool
()
with
get_reusable_executor
(
max_workers
=
n_workers
,
initargs
=
(
args
.
device
,),
initializer
=
initializer
,
)
as
pool
:
fn
=
(
(
hist_train
,
tmpdir
=
tmpdir
,
device
=
args
.
device
,
rabit_args
=
rabit_args
,
),
hist_train
,
)
pool
.
map
(
fn
,
range
(
n_workers
))
def
main
()
->
None
:
"""Demo for distributed training from scratch."""
parser
=
()
parser
.
add_argument
(
"--device"
,
choices
=
[
"cpu"
,
"cuda"
],
default
=
"cpu"
)
args
=
parser
.
parse_args
()
with
()
as
tmpdir
:
launch_workers
(
tmpdir
,
args
)
if
__name__
==
"__main__"
:
main
()