Example of forwarding evaluation logs to the client
xgboost
import
dask
as
dxgb
from
xgboost.callback
import
EvaluationMonitor
def
_get_logger
()
->
:
logger
=
(
"[xgboost.dask]"
)
logger
.
setLevel
(
logging
.
INFO
)
if
not
logger
.
hasHandlers
():
handler
=
()
logger
.
addHandler
(
handler
)
return
logger
class
ForwardLoggingMonitor
(
EvaluationMonitor
):
def
__init__
(
self
,
client
:
,
rank
:
int
=
0
,
period
:
int
=
1
,
)
->
None
:
"""Print the evaluation result at each iteration. The default monitor in the
native interface logs the result to the Dask scheduler process. This class can
be used to forward the logging to the client process. Important: see the
`client` parameter for more info.
Parameters
----------
client :
Distributed client. This must be the top-level client. The class uses
:py:meth:`distributed.Client.forward_logging` in conjunction with the Python
:py:mod:`logging` module to forward the evaluation results to the client
process. It has undefined behaviour if called in a nested task. As a result,
client-side logging is not enabled by default.
"""
client
.
forward_logging
(
_get_logger
()
.
name
)
super
()
.
__init__
(
rank
=
rank
,
period
=
period
,
logger
=
lambda
msg
:
_get_logger
()
.
info
(
msg
.
strip
()),
)
class
WorkerEventMonitor
(
EvaluationMonitor
):
"""Use :py:meth:`distributed.print` to forward the log. A downside is that not only
all clients connected to the cluster can see the log, the logs are also printed on
the worker. If you use a local cluster, the log is duplicated.
"""
def
__init__
(
self
,
rank
:
int
=
0
,
period
:
int
=
1
)
->
None
:
super
()
.
__init__
(
rank
=
rank
,
period
=
period
,
logger
=
lambda
msg
:
(
msg
.
strip
())
)
def
hist_train
(
client
:
,
X
:
,
y
:
,
monitor
:
EvaluationMonitor
)
->
:
dtrain
=
dxgb
.
DaskQuantileDMatrix
(
client
,
X
,
y
)
output
=
dxgb
.
train
(
client
,
{
"tree_method"
:
"hist"
,
"device"
:
"cuda"
},
dtrain
,
num_boost_round
=
4
,
evals
=
[(
dtrain
,
"train"
)],
callbacks
=
[
monitor
],
verbose_eval
=
False
,
)
bst
=
output
[
"booster"
]
history
=
output
[
"history"
]
prediction
=
dxgb
.
predict
(
client
,
bst
,
X
)
print
(
"Evaluation history:"
,
history
)
return
prediction
if
__name__
==
"__main__"
:
with
LocalCUDACluster
(
n_workers
=
2
,
threads_per_worker
=
4
)
as
cluster
:
with
(
cluster
)
as
client
,
({
"array.backend"
:
"cupy"
}):
rng
=
(
1
)
m
=
2
**
18
n
=
100
X
=
rng
.
uniform
(
size
=
(
m
,
n
),
chunks
=
(
128
**
2
,
-
1
))
y
=
X
.
sum
(
axis
=
1
)
monitor
:
EvaluationMonitor
=
ForwardLoggingMonitor
(
client
)
hist_train
(
client
,
X
,
y
,
monitor
)
.
compute
()
monitor
=
WorkerEventMonitor
()
hist_train
(
client
,
X
,
y
,
monitor
)
.
compute
()