client.py 13 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
17 18 19 20 21 22
"""RPC client tools"""
from __future__ import absolute_import

import os
import socket
import struct
23
import time
24 25

from . import base
26 27
from ..contrib import util
from .._ffi.base import TVMError
28
from .._ffi import function
29 30
from .._ffi import ndarray as nd
from ..module import load as _load_module
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72


class RPCSession(object):
    """RPC Client session module

    Do not directly create the obhect, call connect
    """
    # pylint: disable=invalid-name
    def __init__(self, sess):
        self._sess = sess
        self._tbl_index = base._SessTableIndex(sess)
        self._remote_funcs = {}

    def get_function(self, name):
        """Get function from the session.

        Parameters
        ----------
        name : str
            The name of the function

        Returns
        -------
        f : Function
            The result function.
        """
        return self._sess.get_function(name)

    def context(self, dev_type, dev_id=0):
        """Construct a remote context.

        Parameters
        ----------
        dev_type: int or str

        dev_id: int, optional

        Returns
        -------
        ctx: TVMContext
            The corresponding encoded remote context.
        """
73
        ctx = nd.context(dev_type, dev_id)
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
        encode = (self._tbl_index + 1) * base.RPC_SESS_MASK
        ctx.device_type += encode
        ctx._rpc_sess = self
        return ctx

    def upload(self, data, target=None):
        """Upload file to remote runtime temp folder

        Parameters
        ----------
        data : str or bytearray
            The file name or binary in local to upload.

        target : str, optional
            The path in remote
        """
        if isinstance(data, bytearray):
            if not target:
                raise ValueError("target must present when file is a bytearray")
            blob = data
        else:
            blob = bytearray(open(data, "rb").read())
            if not target:
                target = os.path.basename(data)

        if "upload" not in self._remote_funcs:
            self._remote_funcs["upload"] = self.get_function(
101
                "tvm.rpc.server.upload")
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
        self._remote_funcs["upload"](target, blob)

    def download(self, path):
        """Download file from remote temp folder.

        Parameters
        ----------
        path : str
            The relative location to remote temp folder.

        Returns
        -------
        blob : bytearray
            The result blob from the file.
        """
        if "download" not in self._remote_funcs:
            self._remote_funcs["download"] = self.get_function(
119
                "tvm.rpc.server.download")
120 121
        return self._remote_funcs["download"](path)

122 123 124 125 126 127 128 129 130 131 132 133 134
    def remove(self, path):
        """Remove file from remote temp folder.

        Parameters
        ----------
        path: str
            The relative location to remote temp folder.
        """
        if "remove" not in self._remote_funcs:
            self._remote_funcs["remove"] = self.get_function(
                "tvm.rpc.server.remove")
        self._remote_funcs["remove"](path)

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
    def load_module(self, path):
        """Load a remote module, the file need to be uploaded first.

        Parameters
        ----------
        path : str
            The relative location to remote temp folder.

        Returns
        -------
        m : Module
            The remote module containing remote function.
        """
        return base._LoadRemoteModule(self._sess, path)

150 151 152 153 154 155 156 157 158 159 160 161
    def cpu(self, dev_id=0):
        """Construct CPU device."""
        return self.context(1, dev_id)

    def gpu(self, dev_id=0):
        """Construct GPU device."""
        return self.context(2, dev_id)

    def cl(self, dev_id=0):
        """Construct OpenCL device."""
        return self.context(4, dev_id)

162 163 164 165
    def vulkan(self, dev_id=0):
        """Construct Vulkan device."""
        return self.context(7, dev_id)

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
    def metal(self, dev_id=0):
        """Construct Metal device."""
        return self.context(8, dev_id)

    def opengl(self, dev_id=0):
        """Construct OpenGL device."""
        return self.context(11, dev_id)

    def ext_dev(self, dev_id=0):
        """Construct extension device."""
        return self.context(12, dev_id)


class LocalSession(RPCSession):
    """RPCSession interface backed by local environment.

    This class can be used to implement functions that
    need to be ran both locally and remotely.
    """
    def __init__(self):
        # pylint: disable=super-init-not-called
        self.context = nd.context
        self.get_function = function.get_global_func
        self._temp = util.tempdir()

    def upload(self, data, target=None):
        if isinstance(data, bytearray):
            if not target:
                raise ValueError("target must present when file is a bytearray")
            blob = data
        else:
            blob = bytearray(open(data, "rb").read())
            if not target:
                target = os.path.basename(data)
        with open(self._temp.relpath(target), "wb") as f:
            f.write(blob)

    def download(self, path):
        return bytearray(open(self._temp.relpath(path), "rb").read())

    def load_module(self, path):
        return _load_module(self._temp.relpath(path))

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227

class TrackerSession(object):
    """Tracker client session.

    Parameters
    ----------
    addr : tuple
        The address tuple
    """
    def __init__(self, addr):
        self._addr = addr
        self._sock = None
        self._connect()

    def __del__(self):
        self.close()

    def _connect(self):
        self._sock = base.connect_with_retry(self._addr)
tqchen committed
228 229
        self._sock.sendall(struct.pack("<i", base.RPC_TRACKER_MAGIC))
        magic = struct.unpack("<i", base.recvall(self._sock, 4))[0]
230 231 232 233 234 235 236 237 238
        if magic != base.RPC_TRACKER_MAGIC:
            raise RuntimeError("%s is not RPC Tracker" % str(self._addr))

    def close(self):
        """Close the tracker connection."""
        if self._sock:
            self._sock.close()
            self._sock = None

239 240 241 242 243 244 245 246 247 248 249
    def summary(self):
        """Get the summary dict of the tracker."""
        base.sendjson(self._sock, [base.TrackerCode.SUMMARY])
        value = base.recvjson(self._sock)
        if value[0] != base.TrackerCode.SUCCESS:
            raise RuntimeError("Invalid return value %s" % str(value))
        return value[1]

    def text_summary(self):
        """Get a text summary of the tracker."""
        data = self.summary()
250 251 252

        total_ct = {}

253 254 255 256 257 258 259
        res = ""
        res += "Server List\n"
        res += "----------------------------\n"
        res += "server-address\tkey\n"
        res += "----------------------------\n"
        for item in data["server_info"]:
            addr = item["addr"]
260
            res += addr[0] + ":" + str(addr[1]) + "\t"
261
            res += item["key"] + "\n"
262 263 264 265
            key = item['key'].split(':')[1]   # 'server:rasp3b` -> 'rasp3b'
            if key not in total_ct:
                total_ct[key] = 0
            total_ct[key] += 1
266 267
        res += "----------------------------\n"
        res += "\n"
268 269

        # compute max length of device key
270 271 272 273 274
        queue_info = data['queue_info']
        keys = list(queue_info.keys())
        if keys:
            keys.sort()
            max_key_len = max([len(k) for k in keys])
275 276 277 278
        else:
            max_key_len = 0

        res += "Queue Status\n"
279 280 281
        title = ("%%-%ds" % max_key_len + "   total  free  pending\n") % 'key'
        separate_line = '-' * len(title) + '\n'
        res += separate_line + title + separate_line
282
        for k in keys:
283 284 285 286 287 288
            total = total_ct.get(k, 0)
            free, pending = queue_info[k]["free"], queue_info[k]["pending"]
            if total or pending:
                res += ("%%-%ds" % max_key_len + "   %-5d  %-4d  %-7d\n") % \
                       (k, total, free, pending)
        res += separate_line
289 290 291
        return res

    def request(self, key, priority=1, session_timeout=0, max_retry=5):
292 293 294 295 296 297 298 299 300 301 302 303 304 305
        """Request a new connection from the tracker.

        Parameters
        ----------
        key : str
            The type key of the device.

        priority : int, optional
            The priority of the request.

        session_timeout : float, optional
            The duration of the session, allows server to kill
            the connection when duration is longer than this value.
            When duration is zero, it means the request must always be kept alive.
306 307 308

        max_retry : int, optional
            Maximum number of times to retry before give up.
309
        """
310 311
        last_err = None
        for _ in range(max_retry):
312 313 314 315 316 317 318 319 320
            try:
                if self._sock is None:
                    self._connect()
                base.sendjson(self._sock,
                              [base.TrackerCode.REQUEST, key, "", priority])
                value = base.recvjson(self._sock)
                if value[0] != base.TrackerCode.SUCCESS:
                    raise RuntimeError("Invalid return value %s" % str(value))
                url, port, matchkey = value[1]
321
                return connect(url, port, matchkey, session_timeout)
322
            except socket.error as err:
323
                self.close()
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
                last_err = err
            except TVMError as err:
                last_err = err
        raise RuntimeError(
            "Cannot request %s after %d retry, last_error:%s" % (
                key, max_retry, str(last_err)))

    def request_and_run(self,
                        key,
                        func,
                        priority=1,
                        session_timeout=0,
                        max_retry=2):
        """Request a resource from tracker and run the func.

        This function safe-guard rare server node dropout during execution.
        In such case, a new resource will be requested and func will be ran again.

        Parameters
        ----------
        key : str
            The type key of the device.

        func : function of session -> value
            A stateless function

        priority : int, optional
            The priority of the request.

        session_timeout : float, optional
            The duration of the session, allows server to kill
            the connection when duration is longer than this value.
            When duration is zero, it means the request must always be kept alive.

        max_retry : int, optional
            Maximum number of times to retry the function before give up.
        """
        last_err = None
        for _ in range(max_retry):
            try:
                sess = self.request(key,
                                    priority=priority,
                                    session_timeout=session_timeout)
                tstart = time.time()
                return func(sess)
            except TVMError as err:
                duration = time.time() - tstart
                # roughly estimate if the error is due to timeout termination
                if session_timeout and duration >= session_timeout * 0.95:
                    raise RuntimeError(
                        "Session timeout when running %s" % func.__name__)
                last_err = err
        raise RuntimeError(
            "Failed to run on %s after %d retry, last_error:%s" % (
                key, max_retry, str(last_err)))
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430


def connect(url, port, key="", session_timeout=0):
    """Connect to RPC Server

    Parameters
    ----------
    url : str
        The url of the host

    port : int
        The port to connect to

    key : str, optional
        Additional key to match server

    session_timeout : float, optional
        The duration of the session, allows server to kill
        the connection when duration is longer than this value.
        When duration is zero, it means the request must always be kept alive.

    Returns
    -------
    sess : RPCSession
        The connected session.
    """
    try:
        if session_timeout:
            key += " -timeout=%s" % str(session_timeout)
        sess = base._Connect(url, port, key)
    except NameError:
        raise RuntimeError("Please compile with USE_RPC=1")
    return RPCSession(sess)


def connect_tracker(url, port):
    """Connect to a RPC tracker

    Parameters
    ----------
    url : str
        The url of the host

    port : int
        The port to connect to

    Returns
    -------
    sess : TrackerSession
        The connected tracker session.
    """
    return TrackerSession((url, port))