from_mxnet_to_webgl.py 16.5 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
Deploy Deep Learning Models to OpenGL and WebGL
===============================================
20 21 22
**Author**: `Zhixun Tan <https://github.com/phisiart>`_

This example shows how to build a neural network with NNVM python frontend and
23 24
generate runtime library for WebGL running in a browser with TVM.
To run this notebook, you need to install tvm and nnvm.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
Notice that you need to build tvm with OpenGL.
"""

######################################################################
# Overview
# --------
# In this tutorial, we will download a pre-trained resnet18 model from Gluon
# Model Zoo, and run image classification in 3 different ways:
#
# - Run locally:
#   We will compile the model into a TVM library with OpenGL device code and
#   directly run it locally.
#
# - Run in a browser through RPC:
#   We will compile the model into a JavaScript TVM library with WebGL device
#   code, and upload it to an RPC server that is hosting JavaScript TVM runtime
#   to run it.
#
# - Export a JavaScript library and run in a browser:
#   We will compile the model into a JavaScript TVM library with WebGL device
#   code, combine it with JavaScript TVM runtime, and pack everything together.
#   Then we will run it directly in a browser.
#
from __future__ import print_function

import numpy as np
import tvm
52
from tvm.contrib.download import download_testdata
53 54 55 56 57
import nnvm.compiler
import nnvm.testing

# This tutorial must be run with OpenGL backend enabled in TVM.
# The NNVM CI does not enable OpenGL yet. But the user can run this script.
58
opengl_enabled = tvm.module.enabled("opengl")
59 60 61 62 63 64 65 66

# To run the local demo, set this flag to True.
run_deploy_local = False

# To run the RPC demo, set this flag to True.
run_deploy_rpc = False

# To run the WebGL deploy demo, set this flag to True.
67
run_deploy_web = False
68 69 70 71 72

######################################################################
# Download a Pre-trained Resnet18 Model
# -------------------------------------
# Here we define 2 functions:
73
#
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
# - A function that downloads a pre-trained resnet18 model from Gluon Model Zoo.
#   The model that we download is in MXNet format, we then transform it into an
#   NNVM computation graph.
#
# - A function that downloads a file that contains the name of all the image
#   classes in this model.
#
def load_mxnet_resnet():
    """Load a pretrained resnet model from MXNet and transform that into NNVM
       format.

    Returns
    -------
    net : nnvm.Symbol
        The loaded resnet computation graph.

    params : dict[str -> NDArray]
        The pretrained model parameters.
92

93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    data_shape: tuple
        The shape of the input tensor (an image).

    out_shape: tuple
        The shape of the output tensor (probability of all classes).
    """

    print("Loading pretrained resnet model from MXNet...")

    # Download a pre-trained mxnet resnet18_v1 model.
    from mxnet.gluon.model_zoo.vision import get_model
    block = get_model('resnet18_v1', pretrained=True)

    # Transform the mxnet model into NNVM.
    # We want a probability so add a softmax operator.
    sym, params = nnvm.frontend.from_mxnet(block)
    sym = nnvm.sym.softmax(sym)

    print("- Model loaded!")
    return sym, params, (1, 3, 224, 224), (1, 1000)

def download_synset():
    """Download a dictionary from class index to name.
    This lets us know what our prediction actually is.

    Returns
    -------
    synset : dict[int -> str]
        The loaded synset.
    """

    print("Downloading synset...")

    url = "https://gist.githubusercontent.com/zhreshold/" + \
          "4d0b62f3d01426887599d4f7ede23ee5/raw/" + \
          "596b27d23537e5a1b5751d2b0481ef172f58b539/" + \
          "imagenet1000_clsid_to_human.txt"
130
    file_name = "imagenet1000_clsid_to_human.txt"
131

132 133
    file_path = download_testdata(url, file_name, module='data')
    with open(file_path) as f:
134
        synset = eval(f.read())
135

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    print("- Synset downloaded!")
    return synset

######################################################################
# Download Input Image
# --------------------
# Here we define 2 functions that prepare an image that we want to perform
# classification on.
#
# - A function that downloads a cat image.
#
# - A function that performs preprocessing to an image so that it fits the
#   format required by the resnet18 model.
#
def download_image():
    """Download a cat image and resize it to 224x224 which fits resnet.

    Returns
    -------
    image : PIL.Image.Image
        The loaded and resized image.
    """

    print("Downloading cat image...")

    from matplotlib import pyplot as plt
    from PIL import Image

    url = "https://github.com/dmlc/mxnet.js/blob/master/data/cat.png?raw=true"
165
    img_name = "cat.png"
166

167 168
    img_path = download_testdata(url, img_name, module='data')
    image = Image.open(img_path).resize((224, 224))
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 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319

    print("- Cat image downloaded!")

    plt.imshow(image)
    plt.show()

    return image

def transform_image(image):
    """Perform necessary preprocessing to input image.

    Parameters
    ----------
    image : numpy.ndarray
        The raw image.

    Returns
    -------
    image : numpy.ndarray
        The preprocessed image.
    """

    image = np.array(image) - np.array([123., 117., 104.])
    image /= np.array([58.395, 57.12, 57.375])
    image = image.transpose((2, 0, 1))
    image = image[np.newaxis, :]
    return image

######################################################################
# Compile the Model
# -----------------
# Here we define a function that invokes the NNVM compiler.
#
def compile_net(net, target_host, target, data_shape, params):
    """Compiles an NNVM computation graph.

    Parameters
    ----------
    net : nnvm.Graph
        The NNVM computation graph.

    target_host : str
        The target to compile the host portion of the library.

    target : str
        The target to compile the device portion of the library.

    data_shape : tuple
        The shape of the input data (image).

    params : dict[str -> NDArray]
        Model parameters.

    Returns
    -------
    graph : Graph
        The final execution graph.

    libmod : tvm.Module
        The module that comes with the execution graph

    params : dict[str -> NDArray]
        The updated parameters of graph if params is passed.
        This can be different from the params passed in.
    """

    print("Compiling the neural network...")

    with nnvm.compiler.build_config(opt_level=0):
        deploy_graph, lib, deploy_params = nnvm.compiler.build(
            net,
            target_host=target_host,
            target=target,
            shape={"data": data_shape},
            params=params)

    print("- Complilation completed!")
    return deploy_graph, lib, deploy_params

######################################################################
# Demo 1: Deploy Locally
# ----------------------
# In this demo, we will compile the model targetting the local machine.
#
# Then we will demonstrate how to save the compiled model as a shared library
# and load it back.
#
# Finally, we will run the model.
#
def deploy_local():
    """Runs the demo that deploys a model locally.
    """

    # Load resnet model.
    net, params, data_shape, out_shape = load_mxnet_resnet()

    # Compile the model.
    # Note that we specify the the host target as "llvm".
    deploy_graph, lib, deploy_params = compile_net(
        net,
        target_host="llvm",
        target="opengl",
        data_shape=data_shape,
        params=params)

    # Save the compiled module.
    # Note we need to save all three files returned from the NNVM compiler.
    print("Saving the compiled module...")
    from tvm.contrib import util
    temp = util.tempdir()

    path_lib = temp.relpath("deploy_lib.so")
    path_graph_json = temp.relpath("deploy_graph.json")
    path_params = temp.relpath("deploy_param.params")

    lib.export_library(path_lib)
    with open(path_graph_json, "w") as fo:
        fo.write(deploy_graph.json())
    with open(path_params, "wb") as fo:
        fo.write(nnvm.compiler.save_param_dict(deploy_params))

    print("- Saved files:", temp.listdir())

    # Load the module back.
    print("Loading the module back...")
    loaded_lib = tvm.module.load(path_lib)
    with open(path_graph_json) as fi:
        loaded_graph_json = fi.read()
    with open(path_params, "rb") as fi:
        loaded_params = bytearray(fi.read())
    print("- Module loaded!")

    # Run the model! We will perform prediction on an image.
    print("Running the graph...")
    from tvm.contrib import graph_runtime

    module = graph_runtime.create(loaded_graph_json, loaded_lib, tvm.opengl(0))
    module.load_params(loaded_params)

    image = transform_image(download_image())
    input_data = tvm.nd.array(image.astype("float32"), ctx=tvm.opengl(0))

    module.set_input("data", input_data)
    module.run()

    # Retrieve the output.
    out = module.get_output(0, tvm.nd.empty(out_shape, ctx=tvm.opengl(0)))
    top1 = np.argmax(out.asnumpy())
    synset = download_synset()
    print('TVM prediction top-1:', top1, synset[top1])

320
if run_deploy_local and opengl_enabled:
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    deploy_local()

######################################################################
# Demo 2: Deploy the Model to WebGL Remotely with RPC
# -------------------------------------------------------
# Following the steps above, we can also compile the model for WebGL.
# TVM provides rpc module to help with remote deploying.
#
# When we deploy a model locally to OpenGL, the model consists of two parts:
# the host LLVM part and the device GLSL part. Now that we want to deploy to
# WebGL, we need to leverage Emscripten to transform LLVM into JavaScript. In
# order to do that, we will need to specify the host target as
# 'llvm -target=asmjs-unknown-emscripten -system-lib`. Then call Emscripten to
# compile the LLVM binary output into a JavaScript file.
#
# First, we need to manually start an RPC server. Please follow the instructions
# in `tvm/web/README.md`. After following the steps, you should have a web page
# opened in a browser, and a Python script running a proxy.
#
def deploy_rpc():
    """Runs the demo that deploys a model remotely through RPC.
    """
343 344
    from tvm import rpc
    from tvm.contrib import util, emscripten
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 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

    # As usual, load the resnet18 model.
    net, params, data_shape, out_shape = load_mxnet_resnet()

    # Compile the model.
    # Note that this time we are changing the target.
    # This is because we want to translate the host library into JavaScript
    # through Emscripten.
    graph, lib, params = compile_net(
        net,
        target_host="llvm -target=asmjs-unknown-emscripten -system-lib",
        target="opengl",
        data_shape=data_shape,
        params=params)

    # Now we want to deploy our model through RPC.
    # First we ned to prepare the module files locally.
    print("Saving the compiled module...")

    temp = util.tempdir()
    path_obj = temp.relpath("deploy.bc") # host LLVM part
    path_dso = temp.relpath("deploy.js") # host JavaScript part
    path_gl = temp.relpath("deploy.gl") # device GLSL part
    path_json = temp.relpath("deploy.tvm_meta.json")

    lib.save(path_obj)
    emscripten.create_js(path_dso, path_obj, side_module=True)
    lib.imported_modules[0].save(path_gl)

    print("- Saved files:", temp.listdir())

    # Connect to the RPC server.
    print("Connecting to RPC server...")
    proxy_host = 'localhost'
    proxy_port = 9090
    remote = rpc.connect(proxy_host, proxy_port, key="js")
    print("- Connected to RPC server!")

    # Upload module to RPC server.
    print("Uploading module to RPC server...")
    remote.upload(path_dso, "deploy.dso")
    remote.upload(path_gl)
    remote.upload(path_json)
    print("- Upload completed!")

    # Load remote library.
    print("Loading remote library...")
    fdev = remote.load_module("deploy.gl")
    fhost = remote.load_module("deploy.dso")
    fhost.import_module(fdev)
    rlib = fhost
    print("- Remote library loaded!")

    ctx = remote.opengl(0)

    # Upload the parameters.
    print("Uploading parameters...")
    rparams = {k: tvm.nd.array(v, ctx) for k, v in params.items()}
    print("- Parameters uploaded!")

    # Create the remote runtime module.
    print("Running remote module...")
    from tvm.contrib import graph_runtime
    module = graph_runtime.create(graph, rlib, ctx)

    # Set parameter.
    module.set_input(**rparams)

    # Set input data.
    input_data = np.random.uniform(size=data_shape)
    module.set_input('data', tvm.nd.array(input_data.astype('float32')))

    # Run.
    module.run()
    print("- Remote module execution completed!")

    out = module.get_output(0, out=tvm.nd.empty(out_shape, ctx=ctx))
    # Print first 10 elements of output.
    print(out.asnumpy()[0][0:10])

425
if run_deploy_rpc and opengl_enabled:
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
    deploy_rpc()

######################################################################
# Demo 3: Deploy the Model to WebGL SystemLib
# -----------------------------------------------
# This time we are not using RPC. Instead, we will compile the model and link it
# with the entire tvm runtime into a single giant JavaScript file. Then we will
# run the model using JavaScript.
#
def deploy_web():
    """Runs the demo that deploys to web.
    """

    import base64
    import json
    import os
    import shutil
    import SimpleHTTPServer, SocketServer

    from tvm.contrib import emscripten

447
    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(os.getcwd())))
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
    working_dir = os.getcwd()
    output_dir = os.path.join(working_dir, "resnet")
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # As usual, load the resnet18 model.
    net, params, data_shape, out_shape = load_mxnet_resnet()

    # As usual, compile the model.
    graph, lib, params = compile_net(
        net,
        target_host="llvm -target=asmjs-unknown-emscripten -system-lib",
        target="opengl",
        data_shape=data_shape,
        params=params)

    # Now we save the model and link it with the TVM web runtime.
    path_lib = os.path.join(output_dir, "resnet.js")
    path_graph = os.path.join(output_dir, "resnet.json")
    path_params = os.path.join(output_dir, "resnet.params")
    path_data_shape = os.path.join(output_dir, "data_shape.json")
    path_out_shape = os.path.join(output_dir, "out_shape.json")

    lib.export_library(path_lib, emscripten.create_js, options=[
        "-s", "USE_GLFW=3",
        "-s", "USE_WEBGL2=1",
        "-lglfw",
        "-s", "TOTAL_MEMORY=1073741824",
    ])
    with open(path_graph, "w") as fo:
        fo.write(graph.json())
    with open(path_params, "w") as fo:
        fo.write(base64.b64encode(nnvm.compiler.save_param_dict(params)))

    shutil.copyfile(os.path.join(curr_path, "../tvm/web/tvm_runtime.js"),
                    os.path.join(output_dir, "tvm_runtime.js"))
    shutil.copyfile(os.path.join(curr_path, "web/resnet.html"),
                    os.path.join(output_dir, "resnet.html"))
486

487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
    # Now we want to save some extra files so that we can execute the model from
    # JavaScript.
    # - data shape
    with open(path_data_shape, "w") as fo:
        json.dump(list(data_shape), fo)
    # - out shape
    with open(path_out_shape, "w") as fo:
        json.dump(list(out_shape), fo)
    # - input image
    image = download_image()
    image.save(os.path.join(output_dir, "data.png"))
    # - synset
    synset = download_synset()
    with open(os.path.join(output_dir, "synset.json"), "w") as fo:
        json.dump(synset, fo)

    print("Output files are in", output_dir)

    # Finally, we fire up a simple web server to serve all the exported files.
    print("Now running a simple server to serve the files...")
    os.chdir(output_dir)
    port = 8080
    handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    httpd = SocketServer.TCPServer(("", port), handler)
    print("Please open http://localhost:" + str(port) + "/resnet.html")
    httpd.serve_forever()

514 515
if run_deploy_web and opengl_enabled:
    deploy_web()