{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Building the Streaming Dataflow Accelerator\n", "\n", "<font color=\"red\">**Live FINN tutorial:** We recommend clicking **Cell -> Run All** when you start reading this notebook for \"latency hiding\".</font>\n", "\n", "**Important: This notebook depends on the 1-train-mlp-with-brevitas notebook because we are using models that were created by that notebook. So please make sure the needed .onnx files are generated prior to running this notebook.**\n", "\n", "<img align=\"left\" src=\"finn-example.png\" alt=\"drawing\" style=\"margin-right: 20px\" width=\"250\"/>\n", "\n", "In this notebook, we'll use the FINN compiler generate an FPGA accelerator with a streaming dataflow architecture from our quantized MLP for the cybersecurity task. The key idea in such architectures is to parallelize across layers as well as within layers by dedicating a proportionate amount of compute resources to each layer, illustrated on the figure to the left. You can read more about the general concept in the [FINN](https://arxiv.org/pdf/1612.07119) and [FINN-R](https://dl.acm.org/doi/pdf/10.1145/3242897) papers. This is done by mapping each layer to a Vivado HLS description, parallelizing each layer's implementation to the appropriate degree and using on-chip FIFOs to link up the layers to create the full accelerator.\n", "\n", "These implementations offer a good balance of performance and flexibility, but building them by hand is difficult and time-consuming. This is where the FINN compiler comes in: it can build streaming dataflow accelerators from an ONNX description to match the desired throughput." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Outline\n", "-------------\n", "\n", "1. [Introduction to `build_dataflow` Tool](#intro_build_dataflow) \n", "2. [Understanding the Build Configuration: `DataflowBuildConfig`](#underst_build_conf) \n", " 2.1.[Output Products](#output_prod) \n", " 2.2.[Configuring the Board and FPGA Part](#config_fpga) \n", " 2.3 [Configuring the Performance](#config_perf) \n", "4. [Launch a Build: Only Estimate Reports](#build_estimate_report)\n", "5. [Launch a Build: Stitched IP, out-of-context synth and rtlsim Performance](#build_ip_synth_rtlsim)\n", "6. [(Optional) Launch a Build: PYNQ Bitfile and Driver](#build_bitfile_driver)\n", "7. [(Optional) Run on PYNQ board](#run_on_pynq)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Introduction to `build_dataflow` Tool <a id=\"intro_build_dataflow\"></a>\n", "\n", "Since version 0.5b, the FINN compiler has a `build_dataflow` tool. Compared to previous versions which required setting up all the needed transformations in a Python script, it makes experimenting with dataflow architecture generation easier. The core idea is to specify the relevant build info as a configuration `dict`, which invokes all the necessary steps to make the dataflow build happen. It can be invoked either from the [command line](https://finn-dev.readthedocs.io/en/latest/command_line.html) or with a single Python function call.\n", "\n", "\n", "In this notebook, we'll use the Python function call to invoke the builds to stay inside the Jupyter notebook, but feel free to experiment with reproducing what we do here with the `./run-docker.sh build_dataflow` and `./run-docker.sh build_custom` command-line entry points too. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Understanding the Build Configuration: `DataflowBuildConfig` <a id=\"underst_build_conf\"></a>\n", "\n", "The build configuration is specified by an instance of `finn.builder.build_dataflow_config.DataflowBuildConfig`. The configuration is a Python [`dataclass`](https://docs.python.org/3/library/dataclasses.html) which can be serialized into or de-serialized from JSON files for persistence, although we'll just set it up in Python here.\n", "There are many options in the configuration to customize different aspects of the build, we'll only cover a few of them in this notebook. You can read the details on all the config options on [the FINN API documentation](https://finn-dev.readthedocs.io/en/latest/source_code/finn.builder.html#finn.builder.build_dataflow_config.DataflowBuildConfig).\n", "\n", "Let's go over some of the members of the `DataflowBuildConfig`:\n", "\n", "### Output Products <a id=\"output_prod\"></a>\n", "\n", "The build can produce many different outputs, and some of them can take a long time (e.g. bitfile synthesis for a large network). When you first start working on generating a new accelerator and exploring the different performance options, you may not want to go all the way to a bitfile. Thus, in the beginning you may just select the estimate reports as the output products. Gradually, you can generate the output products from later stages until you are happy enough with the design to build the full accelerator integrated into a shell.\n", "\n", "The output products are controlled by:\n", "\n", "* `generate_outputs`: list of output products (of type [`finn.builder.build_dataflow_config.DataflowOutputType`](https://finn-dev.readthedocs.io/en/latest/source_code/finn.builder.html#finn.builder.build_dataflow_config.DataflowOutputType)) that will be generated by the build. Some available options are:\n", " - `ESTIMATE_REPORTS` : report expected resources and performance per layer and for the whole network without any synthesis\n", " - `STITCHED_IP` : create a stream-in stream-out IP design that can be integrated into other Vivado IPI or RTL designs\n", " - `RTLSIM_PERFORMANCE` : use PyVerilator to do a performance/latency test of the `STITCHED_IP` design\n", " - `OOC_SYNTH` : run out-of-context synthesis (just the accelerator itself, without any system surrounding it) on the `STITCHED_IP` design to get post-synthesis FPGA resources and achievable clock frequency\n", " - `BITFILE` : integrate the accelerator into a shell to produce a standalone bitfile\n", " - `PYNQ_DRIVER` : generate a PYNQ Python driver that can be used to launch the accelerator\n", " - `DEPLOYMENT_PACKAGE` : create a folder with the `BITFILE` and `PYNQ_DRIVER` outputs, ready to be copied to the target FPGA platform.\n", "* `output_dir`: the directory where all the generated build outputs above will be written into.\n", "* `steps`: list of predefined (or custom) build steps FINN will go through. Use `build_dataflow_config.estimate_only_dataflow_steps` to execute only the steps needed for estimation (without any synthesis), and the `build_dataflow_config.default_build_dataflow_steps` otherwise (which is the default value). You can find the list of default steps [here](https://finn.readthedocs.io/en/latest/source_code/finn.builder.html#finn.builder.build_dataflow_config.default_build_dataflow_steps) in the documentation.\n", "\n", "### Configuring the Board and FPGA Part <a id=\"config_fpga\"></a>\n", "\n", "* `fpga_part`: Xilinx FPGA part to be used for synthesis, can be left unspecified to be inferred from `board` below, or specified explicitly for e.g. out-of-context synthesis.\n", "* `board`: target Xilinx Zynq or Alveo board for generating accelerators integrated into a shell. See the `pynq_part_map` and `alveo_part_map` dicts in [this file](https://github.com/Xilinx/finn-base/blob/dev/src/finn/util/basic.py#L41) for a list of possible boards.\n", "* `shell_flow_type`: the target [shell flow type](https://finn-dev.readthedocs.io/en/latest/source_code/finn.builder.html#finn.builder.build_dataflow_config.ShellFlowType), only needed for generating full bitfiles where the FINN design is integrated into a shell (so only needed if `BITFILE` is selected) \n", "\n", "### Configuring the Performance <a id=\"config_perf\"></a>\n", "\n", "You can configure the performance (and correspondingly, the FPGA resource footprint) of the generated dataflow accelerator in two ways:\n", "\n", "1) (basic) Set a target performance and let the compiler figure out the per-node parallelization settings.\n", "\n", "2) (advanced) Specify a separate .json as `folding_config_file` that lists the degree of parallelization (as well as other hardware options) for each layer.\n", "\n", "This notebook only deals with the basic approach, for which you need to set up:\n", "\n", "* `target_fps`: target inference performance in frames per second. Note that target may not be achievable due to specific layer constraints, or due to resource limitations of the FPGA. \n", "* `synth_clk_period_ns`: target clock frequency (in nanoseconds) for Vivado synthesis. e.g. `synth_clk_period_ns=5.0` will target a 200 MHz clock. Note that the target clock period may not be achievable depending on the FPGA part and design complexity." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Launch a Build: Only Estimate Reports <a id=\"build_estimate_report\"></a>\n", "\n", "First, we'll launch a build that only generates the estimate reports, which does not require any synthesis. Note two things below: how the `generate_outputs` only contains `ESTIMATE_REPORTS`, but also how the `steps` uses a value of `estimate_only_dataflow_steps`. This skips steps like HLS synthesis to provide a quick estimate from analytical models." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Previous run results deleted!\n" ] } ], "source": [ "import finn.builder.build_dataflow as build\n", "import finn.builder.build_dataflow_config as build_cfg\n", "import os\n", "import shutil\n", "\n", "model_file = \"cybsec-mlp-ready.onnx\"\n", "\n", "estimates_output_dir = \"output_estimates_only\"\n", "\n", "#Delete previous run results if exist\n", "if os.path.exists(estimates_output_dir):\n", " shutil.rmtree(estimates_output_dir)\n", " print(\"Previous run results deleted!\")\n", "\n", "\n", "cfg_estimates = build.DataflowBuildConfig(\n", " output_dir = estimates_output_dir,\n", " mvau_wwidth_max = 80,\n", " target_fps = 1000000,\n", " synth_clk_period_ns = 10.0,\n", " fpga_part = \"xc7z020clg400-1\",\n", " steps = build_cfg.estimate_only_dataflow_steps,\n", " generate_outputs=[\n", " build_cfg.DataflowOutputType.ESTIMATE_REPORTS,\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Building dataflow accelerator from cybsec-mlp-ready.onnx\n", "Intermediate outputs will be generated in /tmp/finn_dev_ubuntu\n", "Final outputs will be generated in output_estimates_only\n", "Build log is at output_estimates_only/build_dataflow.log\n", "Running step: step_tidy_up [1/7]\n", "Running step: step_streamline [2/7]\n", "Running step: step_convert_to_hls [3/7]\n", "Running step: step_create_dataflow_partition [4/7]\n", "Running step: step_target_fps_parallelization [5/7]\n", "Running step: step_apply_folding_config [6/7]\n", "Running step: step_generate_estimate_reports [7/7]\n", "Completed successfully\n", "CPU times: user 1.84 s, sys: 599 ms, total: 2.44 s\n", "Wall time: 1.77 s\n" ] }, { "data": { "text/plain": [ "0" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%time\n", "build.build_dataflow_cfg(model_file, cfg_estimates)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We'll now examine the generated outputs from this build. If we look under the outputs directory, we'll find a subfolder with the generated estimate reports." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "build_dataflow.log intermediate_models report time_per_step.json\r\n" ] } ], "source": [ "! ls {estimates_output_dir}" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "estimate_layer_config_alternatives.json estimate_network_performance.json\r\n", "estimate_layer_cycles.json\t\t op_and_param_counts.json\r\n", "estimate_layer_resources.json\r\n" ] } ], "source": [ "! ls {estimates_output_dir}/report" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We see that various reports have been generated as .json files. Let's examine the contents of the `estimate_network_performance.json` for starters. Here, we can see the analytical estimates for the performance and latency." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\r\n", " \"critical_path_cycles\": 252,\r\n", " \"max_cycles\": 64,\r\n", " \"max_cycles_node_name\": \"StreamingFCLayer_Batch_1\",\r\n", " \"estimated_throughput_fps\": 1562500.0,\r\n", " \"estimated_latency_ns\": 2520.0\r\n", "}" ] } ], "source": [ "! cat {estimates_output_dir}/report/estimate_network_performance.json" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since all of these reports are .json files, we can easily load them into Python for further processing. This can be useful if you are building your own design automation tools on top of FINN. Let's define a helper function and look at the `estimate_layer_cycles.json` report." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "import json\n", "def read_json_dict(filename):\n", " with open(filename, \"r\") as f:\n", " ret = json.load(f)\n", " return ret" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'StreamingFCLayer_Batch_0': 60,\n", " 'StreamingFCLayer_Batch_1': 64,\n", " 'StreamingFCLayer_Batch_2': 64,\n", " 'StreamingFCLayer_Batch_3': 64}" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "read_json_dict(estimates_output_dir + \"/report/estimate_layer_cycles.json\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here, we can see the estimated number of clock cycles each layer will take. Recall that all of these layers will be running in parallel, and the slowest layer will determine the overall throughput of the entire neural network. FINN attempts to parallelize each layer such that they all take a similar number of cycles, and less than the corresponding number of cycles that would be required to meet `target_fps`. Additionally by summing up all layer cycle estimates one can obtain an estimate for the overall latency of the whole network. \n", "\n", "Finally, we can see the layer-by-layer resource estimates in the `estimate_layer_resources.json` report:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'StreamingFCLayer_Batch_0': {'BRAM_18K': 36,\n", " 'BRAM_efficiency': 0.11574074074074074,\n", " 'LUT': 8184,\n", " 'URAM': 0,\n", " 'URAM_efficiency': 1,\n", " 'DSP': 0},\n", " 'StreamingFCLayer_Batch_1': {'BRAM_18K': 4,\n", " 'BRAM_efficiency': 0.1111111111111111,\n", " 'LUT': 1217,\n", " 'URAM': 0,\n", " 'URAM_efficiency': 1,\n", " 'DSP': 0},\n", " 'StreamingFCLayer_Batch_2': {'BRAM_18K': 4,\n", " 'BRAM_efficiency': 0.1111111111111111,\n", " 'LUT': 1217,\n", " 'URAM': 0,\n", " 'URAM_efficiency': 1,\n", " 'DSP': 0},\n", " 'StreamingFCLayer_Batch_3': {'BRAM_18K': 1,\n", " 'BRAM_efficiency': 0.006944444444444444,\n", " 'LUT': 341,\n", " 'URAM': 0,\n", " 'URAM_efficiency': 1,\n", " 'DSP': 0},\n", " 'total': {'BRAM_18K': 45.0, 'LUT': 10959.0, 'URAM': 0.0, 'DSP': 0.0}}" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "read_json_dict(estimates_output_dir + \"/report/estimate_layer_resources.json\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This particular report is useful to determine whether the current configuration will fit into a particular FPGA. If you see that the resource requirements are too high for the FPGA you had in mind, you should consider lowering the `target_fps`.\n", "\n", "**Note that the analytical models tend to over-estimate how much resources are needed, since they can't capture the effects of various synthesis optimizations.**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Launch a Build: Stitched IP, out-of-context synth and rtlsim Performance <a id=\"build_ip_synth_rtlsim\"></a>\n", "\n", "Once we have a configuration that gives satisfactory estimates, we can move on to generating the accelerator. We can do this in different ways depending on how we want to integrate the accelerator into a larger system. For instance, if we have a larger streaming system built in Vivado or if we'd like to re-use this generated accelerator as an IP component in other projects, the `STITCHED_IP` output product is a good choice. We can also use the `OOC_SYNTH` output product to get post-synthesis resource and clock frequency numbers for our accelerator.\n", "\n", "<font color=\"red\">**Live FINN tutorial:** These next builds will take about 10 minutes to complete since multiple calls to Vivado and a call to RTL simulation are involved. While this is running, you can examine the generated files with noVNC -- it is running on **(your AWS URL):6080/vnc.html**\n", "\n", "* Once the `step_hls_codegen [8/16]` below is completed, you can view the generated HLS code under its own folder for each layer: `/tmp/finn_dev_ubuntu/code_gen_ipgen_StreamingFCLayer_Batch_XXXXXX`\n", " \n", "* Once the `step_create_stitched_ip [11/16]` below is completed, you can view the generated stitched IP in Vivado under `/home/ubuntu/finn/notebooks/end2end_example/cybersecurity/output_ipstitch_ooc_rtlsim/stitched_ip`\n", "</font> " ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Previous run results deleted!\n" ] } ], "source": [ "import finn.builder.build_dataflow as build\n", "import finn.builder.build_dataflow_config as build_cfg\n", "import os\n", "import shutil\n", "\n", "model_file = \"cybsec-mlp-ready.onnx\"\n", "\n", "rtlsim_output_dir = \"output_ipstitch_ooc_rtlsim\"\n", "\n", "#Delete previous run results if exist\n", "if os.path.exists(rtlsim_output_dir):\n", " shutil.rmtree(rtlsim_output_dir)\n", " print(\"Previous run results deleted!\")\n", "\n", "cfg_stitched_ip = build.DataflowBuildConfig(\n", " output_dir = rtlsim_output_dir,\n", " mvau_wwidth_max = 80,\n", " target_fps = 1000000,\n", " synth_clk_period_ns = 10.0,\n", " fpga_part = \"xc7z020clg400-1\",\n", " generate_outputs=[\n", " build_cfg.DataflowOutputType.STITCHED_IP,\n", " build_cfg.DataflowOutputType.RTLSIM_PERFORMANCE,\n", " build_cfg.DataflowOutputType.OOC_SYNTH,\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Building dataflow accelerator from cybsec-mlp-ready.onnx\n", "Intermediate outputs will be generated in /tmp/finn_dev_ubuntu\n", "Final outputs will be generated in output_ipstitch_ooc_rtlsim\n", "Build log is at output_ipstitch_ooc_rtlsim/build_dataflow.log\n", "Running step: step_tidy_up [1/16]\n", "Running step: step_streamline [2/16]\n", "Running step: step_convert_to_hls [3/16]\n", "Running step: step_create_dataflow_partition [4/16]\n", "Running step: step_target_fps_parallelization [5/16]\n", "Running step: step_apply_folding_config [6/16]\n", "Running step: step_generate_estimate_reports [7/16]\n", "Running step: step_hls_codegen [8/16]\n", "Running step: step_hls_ipgen [9/16]\n", "Running step: step_set_fifo_depths [10/16]\n", "Running step: step_create_stitched_ip [11/16]\n", "Running step: step_measure_rtlsim_performance [12/16]\n", "Running step: step_make_pynq_driver [13/16]\n", "Running step: step_out_of_context_synthesis [14/16]\n", "Running step: step_synthesize_bitfile [15/16]\n", "Running step: step_deployment_package [16/16]\n", "Completed successfully\n", "CPU times: user 4.76 s, sys: 710 ms, total: 5.47 s\n", "Wall time: 8min 5s\n" ] }, { "data": { "text/plain": [ "0" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%time\n", "build.build_dataflow_cfg(model_file, cfg_stitched_ip)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Why is e.g. `step_synthesize_bitfile` listed above even though we didn't ask for a bitfile in the output products? This is because we're using the default set of build steps, which includes `step_synthesize_bitfile`. Since its output product is not selected, this step will do nothing." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Among the output products, we will find the accelerator exported as a stitched IP block design:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "all_verilog_srcs.txt\t\t finn_vivado_stitch_proj.xpr\r\n", "finn_vivado_stitch_proj.cache\t ip\r\n", "finn_vivado_stitch_proj.hw\t make_project.sh\r\n", "finn_vivado_stitch_proj.ip_user_files make_project.tcl\r\n", "finn_vivado_stitch_proj.sim\t vivado.jou\r\n", "finn_vivado_stitch_proj.srcs\t vivado.log\r\n" ] } ], "source": [ "! ls {rtlsim_output_dir}/stitched_ip" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We also have a few reports generated by these output products, different from the ones generated by `ESTIMATE_REPORTS`." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "estimate_layer_resources_hls.json rtlsim_performance.json\r\n", "ooc_synth_and_timing.json\r\n" ] } ], "source": [ "! ls {rtlsim_output_dir}/report" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In `ooc_synth_and_timing.json` we can find the post-synthesis and maximum clock frequency estimate for the accelerator. Note that the clock frequency estimate here tends to be optimistic, since out-of-context synthesis is less constrained." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\r\n", " \"vivado_proj_folder\": \"/tmp/finn_dev_ubuntu/synth_out_of_context_iut077er/results_finn_design_wrapper\",\r\n", " \"LUT\": 8667.0,\r\n", " \"FF\": 9063.0,\r\n", " \"DSP\": 0.0,\r\n", " \"BRAM\": 22.0,\r\n", " \"WNS\": 0.946,\r\n", " \"\": 0,\r\n", " \"fmax_mhz\": 110.44842058758559,\r\n", " \"estimated_throughput_fps\": 1725756.5716810247\r\n", "}" ] } ], "source": [ "! cat {rtlsim_output_dir}/report/ooc_synth_and_timing.json" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In `rtlsim_performance.json` we can find the steady-state throughput and latency for the accelerator, as obtained by rtlsim. If the DRAM bandwidth numbers reported here are below what the hardware platform is capable of (i.e. the accelerator is not memory-bound), you can expect the same steady-state throughput (excluding any software/driver overheads) in real hardware." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\r\n", " \"cycles\": 643,\r\n", " \"runtime[ms]\": 0.00643,\r\n", " \"throughput[images/s]\": 1088646.967340591,\r\n", " \"DRAM_in_bandwidth[Mb/s]\": 81.64852255054431,\r\n", " \"DRAM_out_bandwidth[Mb/s]\": 0.13608087091757387,\r\n", " \"fclk[mhz]\": 100.0,\r\n", " \"N\": 7,\r\n", " \"latency_cycles\": 211\r\n", "}" ] } ], "source": [ "! cat {rtlsim_output_dir}/report/rtlsim_performance.json" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, let's have a look at `final_hw_config.json`. This is the node-by-node hardware configuration determined by the FINN compiler, including FIFO depths, parallelization settings (PE/SIMD) and others. If you want to optimize your build further (the \"advanced\" method we mentioned under \"Configuring the performance\"), you can use this .json file as the `folding_config_file` for a new run to use it as a starting point for further exploration and optimizations." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\r\n", " \"Defaults\": {},\r\n", " \"StreamingFIFO_0\": {\r\n", " \"ram_style\": \"auto\",\r\n", " \"depth\": 32,\r\n", " \"impl_style\": \"rtl\"\r\n", " },\r\n", " \"StreamingFCLayer_Batch_0\": {\r\n", " \"PE\": 16,\r\n", " \"SIMD\": 40,\r\n", " \"ram_style\": \"auto\",\r\n", " \"resType\": \"lut\",\r\n", " \"mem_mode\": \"decoupled\",\r\n", " \"runtime_writeable_weights\": 0\r\n", " },\r\n", " \"StreamingDataWidthConverter_Batch_0\": {\r\n", " \"impl_style\": \"hls\"\r\n", " },\r\n", " \"StreamingFCLayer_Batch_1\": {\r\n", " \"PE\": 1,\r\n", " \"SIMD\": 64,\r\n", " \"ram_style\": \"auto\",\r\n", " \"resType\": \"lut\",\r\n", " \"mem_mode\": \"decoupled\",\r\n", " \"runtime_writeable_weights\": 0\r\n", " },\r\n", " \"StreamingDataWidthConverter_Batch_1\": {\r\n", " \"impl_style\": \"hls\"\r\n", " },\r\n", " \"StreamingFCLayer_Batch_2\": {\r\n", " \"PE\": 1,\r\n", " \"SIMD\": 64,\r\n", " \"ram_style\": \"auto\",\r\n", " \"resType\": \"lut\",\r\n", " \"mem_mode\": \"decoupled\",\r\n", " \"runtime_writeable_weights\": 0\r\n", " },\r\n", " \"StreamingFCLayer_Batch_3\": {\r\n", " \"PE\": 1,\r\n", " \"SIMD\": 1,\r\n", " \"ram_style\": \"auto\",\r\n", " \"resType\": \"lut\",\r\n", " \"mem_mode\": \"decoupled\",\r\n", " \"runtime_writeable_weights\": 0\r\n", " }\r\n", "}" ] } ], "source": [ "! cat {rtlsim_output_dir}/final_hw_config.json" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## (Optional) Launch a Build: PYNQ Bitfile and Driver <a id=\"build_bitfile_driver\"></a>\n", "\n", "<font color=\"red\">**Live FINN tutorial:** This section is not included in the hands-on tutorial due to the bitfile synthesis time (15-20 min). If you own a PYNQ board, we encourage you to uncomment the cells below to try it out on your own after the tutorial.</font>" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "import finn.builder.build_dataflow as build\n", "import finn.builder.build_dataflow_config as build_cfg\n", "import os\n", "import shutil\n", "\n", "model_file = \"cybsec-mlp-ready.onnx\"\n", "\n", "final_output_dir = \"output_final\"\n", "\n", "#Delete previous run results if exist\n", "if os.path.exists(final_output_dir):\n", " shutil.rmtree(final_output_dir)\n", " print(\"Previous run results deleted!\")\n", "\n", "cfg = build.DataflowBuildConfig(\n", " output_dir = final_output_dir,\n", " mvau_wwidth_max = 80,\n", " target_fps = 1000000,\n", " synth_clk_period_ns = 10.0,\n", " board = \"Pynq-Z1\",\n", " shell_flow_type = build_cfg.ShellFlowType.VIVADO_ZYNQ,\n", " generate_outputs=[\n", " build_cfg.DataflowOutputType.BITFILE,\n", " build_cfg.DataflowOutputType.PYNQ_DRIVER,\n", " build_cfg.DataflowOutputType.DEPLOYMENT_PACKAGE,\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Building dataflow accelerator from cybsec-mlp-ready.onnx\n", "Intermediate outputs will be generated in /tmp/finn_dev_ubuntu\n", "Final outputs will be generated in output_final\n", "Build log is at output_final/build_dataflow.log\n", "Running step: step_tidy_up [1/16]\n", "Running step: step_streamline [2/16]\n", "Running step: step_convert_to_hls [3/16]\n", "Running step: step_create_dataflow_partition [4/16]\n", "Running step: step_target_fps_parallelization [5/16]\n", "Running step: step_apply_folding_config [6/16]\n", "Running step: step_generate_estimate_reports [7/16]\n", "Running step: step_hls_codegen [8/16]\n", "Running step: step_hls_ipgen [9/16]\n", "Running step: step_set_fifo_depths [10/16]\n", "Running step: step_create_stitched_ip [11/16]\n", "Running step: step_measure_rtlsim_performance [12/16]\n", "Running step: step_make_pynq_driver [13/16]\n", "Running step: step_out_of_context_synthesis [14/16]\n", "Running step: step_synthesize_bitfile [15/16]\n", "Running step: step_deployment_package [16/16]\n", "Completed successfully\n", "CPU times: user 4.47 s, sys: 766 ms, total: 5.24 s\n", "Wall time: 22min 13s\n" ] }, { "data": { "text/plain": [ "0" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#%%time\n", "#build.build_dataflow_cfg(model_file, cfg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For our final build, the output products include the bitfile (and the accompanying .hwh file, also needed to execute correctly on PYNQ for Zynq platforms):" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "finn-accel.bit\tfinn-accel.hwh\r\n" ] } ], "source": [ "#! ls {final_output_dir}/bitfile" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The generated Python driver lets us execute the accelerator on PYNQ platforms with simply numpy i/o. You can find some notebooks showing how to use FINN-generated accelerators at runtime in the [finn-examples](https://github.com/Xilinx/finn-examples) repository." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "driver.py driver_base.py finn runtime_weights validate.py\r\n" ] } ], "source": [ "#! ls {final_output_dir}/driver" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The reports folder contains the post-synthesis resource and timing reports:" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "estimate_layer_resources_hls.json post_synth_resources.xml\r\n", "post_route_timing.rpt\r\n" ] } ], "source": [ "#! ls {final_output_dir}/report" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, we have the `deploy` folder which contains everything you need to copy onto the target board to get the accelerator running:" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "bitfile driver\r\n" ] } ], "source": [ "#! ls {final_output_dir}/deploy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## (Optional) Run on PYNQ board <a id=\"run_on_pynq\"></a>\n", "\n", "<font color=\"red\">**Live FINN tutorial:** This section is not included in the hands-on tutorial due to the bitfile synthesis time (15-20 min) of the previous section. If you own a PYNQ board, we encourage you to uncomment the cells below to try it out on your own after the tutorial.</font>\n", "\n", "To test the accelerator on the board, we'll put a copy of the dataset and a premade Python script that validates the accuracy into the `driver` folder, then make a zip archive of the whole deployment folder." ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "#! cp unsw_nb15_binarized.npz {final_output_dir}/deploy/driver" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "#! cp validate-unsw-nb15.py {final_output_dir}/deploy/driver" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "driver.py\tfinn\t\t unsw_nb15_binarized.npz validate.py\r\n", "driver_base.py\truntime_weights validate-unsw-nb15.py\r\n" ] } ], "source": [ "#! ls {final_output_dir}/deploy/driver" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'/workspace/finn/notebooks/end2end_example/cybersecurity/deploy-on-pynq.zip'" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#from shutil import make_archive\n", "#make_archive('deploy-on-pynq', 'zip', final_output_dir+\"/deploy\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can now download the created zipfile (**File -> Open**, mark the checkbox next to the `deploy-on-pynq.zip` and select Download from the toolbar), then copy it to your PYNQ board (for instance via `scp` or `rsync`). Then, run the following commands **on the PYNQ board** to extract the archive and run the validation:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```shell\n", "unzip deploy-on-pynq.zip -d finn-cybsec-mlp-demo\n", "cd finn-cybsec-mlp-demo/driver\n", "sudo python3.6 -m pip install bitstring\n", "sudo python3.6 validate-unsw-nb15.py --batchsize 1000\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You should see `Final accuracy: 91.868293` at the end. You may have noticed that the validation doesn't *quite* run at 1M inferences per second. This is because of the Python packing/unpacking and data movement overheads. To see this in more detail, the generated driver includes a benchmarking mode that shows the runtime breakdown:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```shell\n", "sudo python3.6 driver.py --exec_mode throughput_test --bitfile ../bitfile/finn-accel.bit --batchsize 1000\n", "cat nw_metrics.txt\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```{'runtime[ms]': 1.0602474212646484,\n", " 'throughput[images/s]': 943176.0737575893,\n", " 'DRAM_in_bandwidth[Mb/s]': 70.7382055318192,\n", " 'DRAM_out_bandwidth[Mb/s]': 0.9431760737575894,\n", " 'fclk[mhz]': 100.0,\n", " 'batch_size': 1000,\n", " 'fold_input[ms]': 9.679794311523438e-05,\n", " 'pack_input[ms]': 0.060115814208984375,\n", " 'copy_input_data_to_device[ms]': 0.002428770065307617,\n", " 'copy_output_data_from_device[ms]': 0.0005249977111816406,\n", " 'unpack_output[ms]': 0.3773000240325928,\n", " 'unfold_output[ms]': 6.818771362304688e-05}```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here, the various `pack_input/unpack_output` calls show the overhead of packing/unpacking the inputs/outputs to convert from numpy arrays to the bit-contiguous data representation our accelerator expects. The `copy_input_data_to_device` and `copy_output_data_from_device` indicate the cost of moving the data between the CPU and accelerator memories. These overheads can dominate the execution time when running with small batch sizes.\n", "\n", "Finally, we can see that `throughput[images/s]`, which is the pure hardware throughput without any software and data movement overheads, is close to 1M inferences per second." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.8" } }, "nbformat": 4, "nbformat_minor": 4 }