Skip to content
Snippets Groups Projects
Commit a03373da authored by Cyril Moineau's avatar Cyril Moineau
Browse files

Remove unused templates.

parent 97c9990f
No related branches found
No related tags found
No related merge requests found
#ifndef MEM_INFO_H
#define MEM_INFO_H
#define MEMORY_SIZE {{ mem_size }}
#define MEMORY_ALIGNMENT {{ mem_alignment }}
{% for i in range(mem_info|length) -%}
{%- set layer_name = mem_info[i][0] %}
/* {{layer_name}} memory */
{% for j in range(1, mem_info[i]|length) %}
#define {{ layer_name|upper }}_MEM_{{ mem_info_legends[j]|upper }} {{ mem_info[i][j] }}
{%- endfor %}
{% endfor %}
#endif /* MEM_INFO_H */
{#- For name header -#}
#ifndef DNN_H
#define DNN_H
#ifdef __cplusplus
extern "C" {
#endif
{#- For libraries #}
{% for lib in libraries %}
#include <{{ lib }}>
{%- endfor %}
{% for func in functions %}
{{ func }}
{% endfor %}
#ifdef __cplusplus
}
#endif
#endif /* DNN_H */
\ No newline at end of file
{#- For libraries -#}
#include <stdint.h>
#include "dnn.h"
#include "network_functions.h"
// Layer & memory configurations
{%- for header in headers %}
#include "{{ header }}"
{%- endfor %}
{# mem has the datatype of the firt input #}
{#- Change here to improve it -#}
{% if inputs[0][0] %}
static {{inputs[0][0]}} mem[MEMORY_SIZE];
{% else %}
static float mem[MEMORY_SIZE];
{% endif %}
{# Forward function #}
{#- Support multiple inputs with different datatypes and multiple outputs with different datatypes -#}
void model_forward({% for inp in inputs %}const {{inp[0]}}* {{inp[1]}}, {% endfor %}{% for out in outputs %}{{out[0]}}* {{out[1]}}{{ ", " if not loop.last else "" }}{% endfor %})
{
{%- for action in actions %}
{{ action }}
{%- endfor %}
}
{#- For name header -#}
#ifndef NETWORK_FUNCTIONS_HPP
#define NETWORK_FUNCTIONS_HPP
{#- For libraries #}
{% for lib in libraries %}
#include <{{ lib }}>
{%- endfor %}
{% for file in files %}
#include "{{ file }}"
{%- endfor %}
{% for func in functions %}
{{ func }}
{% endfor %}
#endif /* NETWORK_FUNCTIONS_HPP */
\ No newline at end of file
from pathlib import Path
# Constants
FILE = Path(__file__).resolve()
ROOT = FILE.parents[1]
def get_all_available_boards():
boards = {}
directory_path = Path(str(ROOT / "boards"))
for subfolder in directory_path.rglob('*'):
if subfolder.is_dir() and \
subfolder.name != "__pycache__" and \
(subfolder.parent / '__init__.py').exists() and \
not (subfolder / '__init__.py').exists():
# Get relative path to boards directory
relpath = str(subfolder.relative_to(directory_path))
# Get board name
board_name = relpath.replace('/', '').replace('\\', '')
boards[board_name.lower()] = str(subfolder)
return boards
AVAILABLE_BOARDS = get_all_available_boards()
def has_board(board_name: str) -> bool:
return board_name.lower() in AVAILABLE_BOARDS.keys()
import numpy as np
import aidge_core
def numpy_dtype2ctype(dtype):
if dtype == np.int8:
return "int8_t"
elif dtype == np.uint8:
return "uint8_t"
elif dtype == np.int16:
return "int16_t"
elif dtype == np.int32:
return "int32_t"
elif dtype == np.int64:
return "int64_t"
elif dtype == np.float32:
return "float"
elif dtype == np.float64:
return "double"
# Add more dtype mappings as needed
else:
raise ValueError(f"Unsupported {dtype} dtype")
def aidge_datatype2ctype(datatype):
if datatype == aidge_core.dtype.int8:
return "int8_t"
elif datatype == aidge_core.dtype.uint8:
return "uint8_t"
elif datatype == aidge_core.dtype.int32:
return "int32_t"
elif datatype == aidge_core.dtype.int64:
return "int64_t"
elif datatype == aidge_core.dtype.float32:
return "float"
elif datatype == aidge_core.dtype.float64:
return "double"
# Add more dtype mappings as needed
else:
raise ValueError(f"Unsupported {datatype} aidge dtype")
def aidge_datatype2dataformat(datatype):
if datatype == aidge_core.dtype.int8:
return "int8"
elif datatype == aidge_core.dtype.int32:
return "int32"
elif datatype == aidge_core.dtype.int64:
return "int64"
elif datatype == aidge_core.dtype.float32:
return "float32"
elif datatype == aidge_core.dtype.float64:
return "float64"
# Add more dtype mappings as needed
else:
raise ValueError(f"Unsupported {datatype} aidge dtype")
# Examples on how to use this module Aidge ARM CortexM Export
This folder contains some examples on how to use the `Aidge ARM CortexM Export` module in your projects.
- [LeNet export for MNIST dataset](./export_LeNet/)
Feel free to propose your own contributions with this module !
\ No newline at end of file
%% Cell type:markdown id: tags:
# Export a MNIST model to a CPP standalone project
%% Cell type:code id: tags:
``` python
%pip install requests numpy ipywidgets ipycanvas
```
%% Cell type:markdown id: tags:
## Download the model
%% Cell type:code id: tags:
``` python
import os
import requests
```
%% Cell type:code id: tags:
``` python
# Download onnx file if it has not been done before
if not os.path.isfile("./lenet_mnist.onnx"):
response = requests.get("https://huggingface.co/vtemplier/LeNet_MNIST/resolve/main/lenet_mnist.onnx?download=true")
if response.status_code == 200:
with open("lenet_mnist.onnx", 'wb') as f:
f.write(response.content)
print("ONNX model downloaded successfully.")
else:
print("Failed to download ONNX model. Status code:", response.status_code)
```
%% Cell type:markdown id: tags:
## Load the model in Aidge and manipulate it
%% Cell type:code id: tags:
``` python
import aidge_core
import aidge_backend_cpu
import aidge_onnx
import aidge_export_cpp
import aidge_export_arm_cortexm
```
%% Cell type:code id: tags:
``` python
model = aidge_onnx.load_onnx("lenet_mnist.onnx")
```
%% Cell type:code id: tags:
``` python
# Remove Flatten node, useless in the CPP export
aidge_core.remove_flatten(model)
# Freeze the model by setting constant to parameters producers
for node in model.get_nodes():
if node.type() == "Producer":
node.get_operator().set_attr("Constant", True)
# Create Producer Node for the Graph
input_node = aidge_core.Producer([1, 1, 28, 28], "input")
input_node.add_child(model)
model.add(input_node)
# Configuration for the model + forward dimensions
model.compile("cpu", aidge_core.DataType.Float32)
```
%% Cell type:code id: tags:
``` python
# Generate scheduling of the model
scheduler = aidge_core.SequentialScheduler(model)
scheduler.generate_scheduling()
```
%% Cell type:markdown id: tags:
## Export the model
%% Cell type:code id: tags:
``` python
aidge_export_arm_cortexm.export("lenet_export_fp32", model, scheduler, board="stm32h7")
```
%% Cell type:markdown id: tags:
### Draw your own number
%% Cell type:code id: tags:
``` python
from ipywidgets import HBox, VBox, Button, Layout
from ipycanvas import RoughCanvas, hold_canvas
img_name = "my_number.png"
canvas = RoughCanvas(width=28, height=28, sync_image_data=True)
button_gen = Button(description="Generate PNG")
button_clear = Button(description="Clear")
drawing = False
position = None
shape = []
def on_erase_button_clicked(b):
canvas.clear()
def on_generate_button_clicked(b):
try:
canvas.to_file(img_name)
print(f"Image generated to {img_name} !")
except:
print("Draw a number before generating the image.")
button_clear.on_click(on_erase_button_clicked)
button_gen.on_click(on_generate_button_clicked)
def on_mouse_down(x, y):
global drawing
global position
global shape
drawing = True
position = (x, y)
shape = [position]
def on_mouse_move(x, y):
global drawing
global position
global shape
if not drawing:
return
with hold_canvas():
canvas.stroke_line(position[0], position[1], x, y)
position = (x, y)
shape.append(position)
def on_mouse_up(x, y):
global drawing
global position
global shape
drawing = False
with hold_canvas():
canvas.stroke_line(position[0], position[1], x, y)
shape = []
canvas.on_mouse_down(on_mouse_down)
canvas.on_mouse_move(on_mouse_move)
canvas.on_mouse_up(on_mouse_up)
canvas.stroke_style = "#000000"
VBox((canvas, HBox((button_gen, button_clear))),
layout=Layout(height='auto', width="300px"))
```
%% Cell type:markdown id: tags:
### Generate inputs for testing the model from your drawing
%% Cell type:code id: tags:
``` python
try:
number_np = canvas.get_image_data()
# We got a numpy array with the shape of (28,28,4)
# Transform it to (28,28)
x = number_np[:, :, 3].astype("float32")
# Convert from [0, 255] to [0, 1] and export it
aidge_export_cpp.generate_input_file(export_folder="lenet_export_fp32",
array_name="inputs",
array=x / 255)
except:
print("Please draw a number in the previous cell before running this one.")
```
%% Cell type:markdown id: tags:
### Compile the export and test it
%% Cell type:code id: tags:
``` python
!cd lenet_export_fp32 && make build_image_docker && make build_docker
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment