|
| 1 | +from hls4ml.converters.keras_to_hls import keras_to_hls |
| 2 | +import pytest |
| 3 | +import hls4ml |
| 4 | +import numpy as np |
| 5 | +from sklearn.metrics import accuracy_score |
| 6 | +import tensorflow as tf |
| 7 | +from tensorflow.keras.models import model_from_json, Model |
| 8 | +from tensorflow.keras.layers import Input, Permute |
| 9 | +import yaml |
| 10 | + |
| 11 | +@pytest.fixture(scope='module') |
| 12 | +def data(): |
| 13 | + X = np.random.rand(1, 2, 3) |
| 14 | + return X |
| 15 | + |
| 16 | +@pytest.fixture(scope='module') |
| 17 | +def keras_model(): |
| 18 | + inp = Input(shape=(2, 3), name='input_1') |
| 19 | + out = Permute((2, 1))(inp) |
| 20 | + model = Model(inputs=inp, outputs=out) |
| 21 | + return model |
| 22 | + |
| 23 | +@pytest.fixture |
| 24 | +@pytest.mark.parametrize('io_type', ['io_parallel', |
| 25 | + 'io_stream']) |
| 26 | +def hls_model(keras_model, io_type): |
| 27 | + hls_config = hls4ml.utils.config_from_keras_model(keras_model, |
| 28 | + default_precision='ap_fixed<16,3,AP_RND_CONV,AP_SAT>', |
| 29 | + granularity='name') |
| 30 | + hls_model = hls4ml.converters.convert_from_keras_model(keras_model, |
| 31 | + hls_config=hls_config, |
| 32 | + io_type=io_type, |
| 33 | + output_dir='hls4mlprj_transpose_{}'.format(io_type)) |
| 34 | + |
| 35 | + hls_model.compile() |
| 36 | + return hls_model |
| 37 | + |
| 38 | +@pytest.mark.parametrize('io_type', ['io_parallel', |
| 39 | + 'io_stream']) |
| 40 | +def test_accuracy(data, keras_model, hls_model): |
| 41 | + X = data |
| 42 | + model = keras_model |
| 43 | + # model under test predictions and accuracy |
| 44 | + y_keras = model.predict(X) |
| 45 | + y_hls4ml = hls_model.predict(X).reshape(y_keras.shape) |
| 46 | + # "accuracy" of hls4ml predictions vs keras |
| 47 | + np.testing.assert_allclose(y_keras, y_hls4ml, rtol=0, atol=1e-04, verbose=True) |
0 commit comments