Skip to content

Instantly share code, notes, and snippets.

@vloncar
Last active March 31, 2021 02:39
Show Gist options
  • Save vloncar/abbe2a789e9f71f263e493c804269f64 to your computer and use it in GitHub Desktop.
Save vloncar/abbe2a789e9f71f263e493c804269f64 to your computer and use it in GitHub Desktop.
import numpy as np
import random as rnd
import hls4ml
from tensorflow.keras.layers import *
from tensorflow.keras.models import Sequential
height = 8
width = 8
chan = 3
input_shape = (height,width,chan)
num_classes = 32
keras_model = Sequential()
keras_model.add(Conv2D(4, kernel_size=(3, 3), activation='linear', input_shape=input_shape))
keras_model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
print(keras_model.summary())
# Set some random weights
rnd.seed(42)
for layer in keras_model.layers:
old_weights = layer.get_weights()
if len(old_weights) > 0:
new_weights = []
for w in old_weights:
new_w = []
for i in range(np.prod(w.shape)):
new_w.append(rnd.randint(1, 10))
new_w = np.asarray(new_w).reshape(w.shape)
new_weights.append(new_w)
layer.set_weights(new_weights)
# Create conversion config
yaml_config = {}
yaml_config['KerasModel'] = keras_model
yaml_config['OutputDir'] = 'pr299_test'
yaml_config['ProjectName'] = 'myproject'
yaml_config['XilinxPart'] = 'xcvu9p-flgb2104-2-e'
yaml_config['ClockPeriod'] = 5
yaml_config['IOType'] = 'io_stream'
yaml_config['HLSConfig'] = {
'Model': {
'Precision': 'ap_fixed<16,8>',
'ReuseFactor': 1
}
}
# Prepare some data
np.random.seed(42)
x = np.random.rand(np.prod(keras_model.input.shape[1:])).reshape(keras_model.input.shape[1:])
# Predict with Keras
y_gold = keras_model.predict(np.expand_dims(x, axis=0))
print('Keras predictions:')
print(y_gold)
# Predict with hls4ml (strategy: latency)
hls_model = hls4ml.converters.keras_to_hls(yaml_config)
hls_model.compile()
y_latency = hls_model.predict(x)
print('HLS4ML predictions (strategy: latency):')
print(y_latency)
# Predict with hls4ml (strategy: resource)
yaml_config['HLSConfig']['Model']['Strategy'] = 'Resource'
hls_model = hls4ml.converters.keras_to_hls(yaml_config)
hls_model.compile()
y_resource = hls_model.predict(x)
print('HLS4ML predictions (strategy: resource):')
print(y_resource)
print('HLS4ML strategies are equal:', np.array_equal(y_latency, y_resource))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment