gpu code generation for deep learning networks using matlab function block -凯发k8网页登录

main content

gpu code generation for deep learning networks using matlab function block

with gpu coder™, you can generate optimized code for simulink® models containing a variety of trained deep learning networks. you can implement the deep learning functionality in simulink by using matlab function blocks or by using blocks from the deep neural networks library. when implementing with matlab function blocks, use the coder.loaddeeplearningnetwork function to load a trained deep learning network and use the object functions of the network object to obtain the desired responses. you can configure the code generator to take advantage of the nvidia® cuda® deep neural network library (cudnn) and tensorrt™ high performance inference libraries for nvidia gpus. the generated code implements the deep convolutional neural network (cnn) by using the architecture, the layers, and parameters that you specify in network object.

example: classify images by using googlenet

googlenet has been trained on over a million images and can classify images into 1000 object categories (such as keyboard, coffee mug, pencil, and animals). the network takes an image as input, and then outputs a label for the object in the image together with the probabilities for each of the object categories. this example shows you how to perform simulation and generate cuda code for the pretrained googlenet deep convolutional neural network and classify an image.

  1. load the pretrained googlenet network. you can choose to load a different pretrained network for image classification. if you do not have the required support packages installed, install the software according to the instructions provided.

    net = googlenet;
    
  2. the object net contains the dagnetwork object. use the analyzenetwork function to display an interactive visualization of the network architecture, to detect errors and issues in the network, and to display detailed information about the network layers. the layer information includes the sizes of layer activations and learnable parameters, the total number of learnable parameters, and the sizes of state parameters of recurrent layers.

    analyzenetwork(net);
    

    analyze network app showing network analysis of googlenet.

  3. the image that you want to classify must have the same size as the input size of the network. for googlenet, the size of the imageinputlayer is 224-by-224-by-3. the classes property of the output classificationlayer contains the names of the classes learned by the network. view 10 random class names out of the total of 1000.

    classnames = net.layers(end).classes;
    numclasses = numel(classnames);
    disp(classnames(randperm(numclasses,10)))
    
        'speedboat'
        'window screen'
        'isopod'
        'wooden spoon'
        'lipstick'
        'drake'
        'hyena'
        'dumbbell'
        'strawberry'
        'custard apple'
    

create googlenet model

  1. create a simulink model and insert a matlab function block from the user-defined functions library.

  2. add an image from file block from the computer vision toolbox™ library and set the file name parameter to peppers.png.

  3. add a resize block from the computer vision toolbox library to the model. set the specify parameter of the resize block to number of output rows and columns and enter [224 224] as the value for number of output rows and columns. this bock resizes the input image to that of the input layer of the network.

    simulink model containing blocks for classifying images using googlenet.

  4. double-click the matlab function block. a default function signature appears in the matlab function block editor.

  5. define a function called googlenet_predict, which implements the prediction entry-point function. the function header declares in as an argument to the googlenet_predict function, with scores and indxtop as the return value.

    function [scores,indxtop] = googlenet_predict(in) %#codegen
    persistent mynet;
    if isempty(mynet)
        mynet = coder.loaddeeplearningnetwork('googlenet');
    end
    % pass in input   
    predict_scores = predict(mynet,in);
    [scores,indx] = sort(predict_scores, 'descend');
    indxtop = indx(1:5);
    

    a persistent object mynet loads the dagnetwork object. at the first call to the entry-point function, the persistent object is constructed and set up. on subsequent calls to the function, the same object is reused to call predict on inputs, avoiding reconstructing and reloading the network object.

    you can also use the (deep learning toolbox) method to network activations for a specific layer. for example, the following line of code returns the network activations for the layer specified in layeridx.

    out = activations(mynet,in,layeridx,'outputas','channels');
    

    you can also use the (deep learning toolbox) method to predict class labels for the image data in in using the trained network mynet.

    [out,scores] = classify(mynet,in);
    

    for lstm networks, you can use the (deep learning toolbox) and (deep learning toolbox) methods. for usage notes and limitations of these method, see .

  6. open the block parameters of the matlab function block. on the code generation tab, select reusable function for function packaging.

  7. connect these blocks as shown in the diagram. save the model as googlenetmodel.

    simulink model showing connection between the blocks.

configure model for gpu acceleration

model configuration parameters determine the acceleration method used during simulation.

  1. open the configuration parameters dialog box. open the solver pane. to compile your model for acceleration and generate cuda code, configure the model to use a fixed-step solver. this table shows the solver configuration for this example.

    parametersettingeffect on generated code
    typefixed-stepmaintains a constant (fixed) step size, which is required for code generation
    solverdiscrete (no continuous states)applies a fixed-step integration technique for computing the state derivative of the model
    fixed-step sizeautosimulink chooses the step size

    snapshot of the configuration parameters dialog showing solver options for simulation.

  2. select the simulation target pane. set the language to c .

  3. select gpu acceleration.

    options specific to gpu coder are now visible in the simulation target > gpu acceleration pane. for this example, you can use the default values for these gpu-specific parameters.

    gpu acceleration pane on the configuration parameters dialog of the model.

  4. on the simulation target pane, set the target library parameter in the deep learning group to cudnn.

    snapshot of the configuration parameters dialog showing deep learning options for simulation acceleration.

    you can also select tensorrt to target tensorrt high performance inference libraries for nvidia gpus.

  5. click ok to save and close the configuration parameters dialog box.

    you can use set_param to configure the model parameter programmatically in the matlab® command window.

    set_param('googlenetmodel','gpuacceleration','on');
    

build gpu accelerated model

  1. to build and simulate the gpu accelerated model, select run on the simulation tab or use the matlab command:

    out = sim('googlenetmodel');
    

    the software first checks to see if cuda/c code was previously compiled for your model. if code was created previously, the software runs the model. if code was not previously built, the software first generates and compiles the cuda/c code, and then runs the model. the code generation tool places the generated code in a subfolder of the working folder called slprj/_slprj/googlenetmodel.

  2. display the top five predicted labels and their associated probabilities as a histogram. because the network classifies images into so many object categories, and many categories are similar, it is common to consider the top-five accuracy when evaluating networks. the network classifies the image as a bell pepper with a high probability.

    im = imread('peppers.png');
    classnamestop = classnames(out.yout{2}.values.data(:,:,1))
    h = figure;
    h.position(3) = 2*h.position(3);
    ax1 = subplot(1,2,1);
    ax2 = subplot(1,2,2);
    image(ax1,im);
    barh(ax2,out.yout{1}.values.data(1,5:-1:1,1))
    xlabel(ax2,'probability')
    yticklabels(ax2,classnamestop(5:-1:1))
    ax2.yaxislocation = 'right';
    sgtitle('top 5 predictions using googlenet')
    

configure the model for code generation

the model configuration parameters provide many options for the code generation and build process.

  1. select the code generation pane. set the system target file to grt.tlc.

    you can also use the embedded coder® target file ert.tlc or a custom system target file.

    for gpu code generation, the custom target file must be based on grt.tlc or ert.tlc. for information on developing a custom target file, see (simulink coder).

  2. set the language to c .

  3. select generate gpu code.

  4. select generate code only.

  5. select the toolchain. for linux® platforms, select nvidia cuda | gmake (64-bit linux). for windows® systems, select nvidia cuda (w/microsoft visual c 20xx) | nmake (64-bit windows).

    when using a custom system target file, you must set the build controls for the toolchain approach. to learn more about toolchain approach for custom targets, see (simulink coder).

  6. on the code generation > report pane, select create code generation report and open report automatically.

  7. on the code generation > interface pane, set the target library in the deep learning group to cudnn.

    you can also select tensorrt to target tensorrt high performance inference libraries for nvidia gpus.

  8. when the generate gpu code parameter is enabled, options specific to gpu coder are visible in the code generation > gpu code pane. for this example, you can use the default values of the gpu-specific parameters in code generation > gpu code pane.

    gpu code pane on the configuration parameters dialog of the model.

  9. click ok to save and close the configuration parameters dialog box.

    you can also use set_param function to configure the model parameter programmatically in the matlab command window.

    set_param('googlenetmodel','generategpucode','cuda');
    

generate cuda code for the model

  1. in the simulink editor, open the simulink coder app.

  2. generate code.

messages appear in the diagnostics viewer. the code generator produces cuda source and header files, and an html code generation report. the code generator places the files in a build folder, a subfolder named googlenetmodel_grt_rtw under your current working folder.

limitations

  • code generation for the (deep learning toolbox) does not support non-zero padding value when targeting third-party libraries.

    for simulink models that implement deep learning functionality using matlab function block, simulation errors out if the network contains an average pooling layer with non-zero padding value. in such cases, use the blocks from the deep neural networks library instead of a matlab function to implement the deep learning functionality.

  • gpu code generation for matlab function blocks in stateflow® charts is not supported.

  • when gpu acceleration is enabled, the code generator does not support import custom code for importing custom authored cuda source files (*.cu). instead, use inside the matlab function block.

  • the matlab function block does not support all the data types from the matlab language. for supported data types, refer to the block documentation.

  • for gpu code generation, the custom target file must be based on grt.tlc or ert.tlc.

  • for deploying the generated code, it is recommended to use the generate an example main program option to generate the ert_main.cu module. this option requires the embedded coder license.

    you can also use the rt_cppclass_main.cpp static main module provided by mathworks®. however, the static main file must be modified such that the models class constructor points to the deep learning object. for example,

    static googlenetmodelmodelclass::deeplearning_googlenetmodel_t
      googlenetmodel_deeplearning;
    static googlenetmodelmodelclass googlenetmodel_obj{ &googlenetmodel_deeplearning};
    

see also

functions

  • (simulink) | (simulink) | (simulink) | (simulink) | (simulink) | (simulink) | (simulink) | (simulink) | (simulink)

related topics

网站地图