Main Content

Code Generation from Simulink Models with GPU Coder

GPU Coder™ generates optimized CUDA®code from Simulink®models containingMATLAB Functionblocks. You can use the generated code and executable for rapid prototyping on NVIDIA®GPUs. Code generation reports and traceability enable you to view and analyze the generated code. The basic steps for CUDA code generation by using GPU Coder are:

  • Create or open a model.

  • Configure the model for code generation by selecting thesolver,language,toolchain, and other GPU-specific configuration parameters.

  • Build the model.

Example: Sobel Edge Detection

The Sobel edge detection algorithm is a simple edge detection algorithm that performs a 2-D spatial gradient operation on a grayscale image. This algorithm emphasizes the high spatial frequency regions that correspond to the edges of the input image.

The Sobel edge algorithm computes the horizontal gradient (H) and the vertical gradient (V) of the input image by using two orthogonal filter kernels (kandk'). After the filtering operation, the algorithm computes the gradient magnitude and applies a threshold to find the regions of the images that are considered to be edges.

k = single([1 2 1; 0 0 0; -1 -2 -1]); H = conv2(single(grayImage),k,'same'); V = conv2(single(grayImage),k','same'); E = sqrt(H.*H + V.*V); edgeImage = uint8((E > threshold) * 255);

MATLAB peppers.png test image and its edge detected output.

Create Edge Detection Model

  1. Create a Simulink model and insert twoMATLAB Functionblocks from theUser-Defined Functionslibrary.

  2. Add aConstantblock and set its value to0.4.

  3. Add aFrom Multimedia Fileblock from theComputer Vision Toolbox™library.

  4. Open theBlock Parametersdialog box for theFrom Multimedia Fileblock and set theFile nameparameter torhinos.avi.

    Set theImage signalparameter toOne multidimensional signal.

  5. Add twoVideo Viewerblocks from theComputer Vision Toolboxlibrary to the model.

    Simulink model containing blocks for implementing edge detection algorithm.

  6. Double-click on one of theMATLAB Functionblocks. A default function signature appears in theMATLAB FunctionBlock Editor.

  7. Define a function calledsobel, which implements the Sobel edge detection algorithm. The function header declaresgrayImageandthresholdas an argument to thesobelfunction, withedgeImageas the return value. Save Editor document to file.

    functionedgeImage = sobel(grayImage,threshold)%#codegen% Define Kernel for Sobel edge detectionk = single([1 2 1; 0 0 0; -1 -2 -1]);% Detect EdgeH = conv2(single(grayImage),k,'same'); V = conv2(single(grayImage),k','same'); E = sqrt(H.*H + V.*V); edgeImage = uint8((E > threshold) * 255);end

  8. Open the block parameters for theMATLAB Functionblock. On theCode Generationtab, selectReusable functionforFunction packagingparameter.

    If theFunction packagingparameter is set to any other value, CUDA kernels may not get generated.

  9. Modify the otherMATLAB Functionblock to implement the RGB to grayscale conversion prior to the Sobel edge detection operation. Set theFunction packagingparameter of theMATLAB Functionblock toReusable function.

    functiongray = RGB2gray(RGB)%#codegen% Convert color image to grey imagegray = (0.2989 * double(RGB(:,:,1)) +...0.5870 * double(RGB(:,:,2)) +...0.1140 * double(RGB(:,:,3)));end
  10. Connect these blocks as shown in the diagram. Save the model asedgeDetection.slx.

    Simulink model showing connection between the blocks.

  11. To test the model for errors, simulate the model in the Simulink Editor. On the toolstrip, clickRun.

    To see all video frames during simulation, disable theSimulation > Drop Frames to improve Performanceoption of theVideo Viewerblock.

    Edge detected output from the Video Viewer block.

Configure Model for Code Generation

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

  1. Open the Configuration Parameters dialog box. Open theSolverpane. 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.

    Parameter Setting Effect on Generated Code
    Type Fixed-step Maintains a constant (fixed) step size, which is required for code generation
    Solver discrete (no continuous states) Applies a fixed-step integration technique for computing the state derivative of the model
    Fixed-step size auto Simulink chooses the step size

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

  2. On theCode Generationpane, set theSystem target filetogrt.tlc.

    You can also use the Embedded Coder®target fileert.tlcor a custom system target file.

    For GPU code generation, the custom target file must be based ongrt.tlcorert.tlc. For information on developing a custom target file, seeCustomize System Target Files(Simulink Coder).

  3. Set theLanguagetoC++.

  4. SelectGenerate GPU code.

  5. On theCode Generationpane, selectGenerate code only.

  6. Select theToolchain. For Linux®platforms, selectNVIDIA CUDA | gmake (64-bit Linux). For Windows®systems, selectNVIDIA 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, seeSupport Toolchain Approach with Custom Target(Simulink Coder).

  7. On theCode Generation > Interfacepane, disableMAT-file logging.

  8. On theCode Generation > Reportpane, selectCreate code generation reportandOpen report automatically.

  9. When you enable theGenerate GPU codeparameter, options specific to GPU Coder appear in theCode Generation > GPU Codepane.

    For this example, you can use the default values of the GPU-specific parameters inCode Generation > GPU Codepane.

    GPU代码面板的配置参数dialog of the model.

  10. ClickOKto save and close the Configuration Parameters dialog box.

    You can use theset_paramfunction to configure the model parameter programmatically in the MATLAB®Command Window.

    set_param('edgeDetection','GenerateGPUCode','CUDA');

Generate CUDA Code for the Model

  1. In the Simulink Editor, open theSimulink Coder应用程序。

  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 abuild folder, a subfolder namededgeDetection_grt_rtw在你当前的工作目录。

You can find the CUDA kernels in the_eML_blk_kerneland_eML_blk_kernel_cfunctions. The information within the triple chevrons is the execution configuration for the kernel.

Limitations

  • GPU code generation forMATLAB Functionblocks in Stateflow®charts is not supported.

  • TheMATLAB Functionblock 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 ongrt.tlcorert.tlc.

See Also

Functions

Related Topics