Skip to content

Instantly share code, notes, and snippets.

@jmduarte
Forked from vloncar/pr299_test.py
Last active March 31, 2021 03:40
Show Gist options
  • Save jmduarte/5c9cf2607a25633246e6fc85cbca89de to your computer and use it in GitHub Desktop.
Save jmduarte/5c9cf2607a25633246e6fc85cbca89de to your computer and use it in GitHub Desktop.
import numpy as np
import random as rnd
import hls4ml
from tensorflow.keras.layers import Conv2D, MaxPooling2D, BatchNormalization
from qkeras.qconvolutional import QConv2D
from qkeras.quantizers import quantized_bits, quantized_relu
from tensorflow.keras.models import Sequential
from qkeras import QActivation
height = 8
width = 8
chan = 3
input_shape = (height,width,chan)
num_classes = 32
keras_model = Sequential()
keras_model.add(QConv2D(4, kernel_size=(3, 3), strides=(2, 2), activation='linear', input_shape=input_shape,
kernel_quantizer=quantized_bits(15, 7, alpha=1),
bias_quantizer=quantized_bits(15, 7, alpha=1), padding='valid'))
keras_model.add(BatchNormalization())
keras_model.add(QActivation("quantized_bits(15, 7, alpha=1)"))
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.uniform(0, 2))
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