|
| 1 | +from glob import glob |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import keras |
| 5 | +import numpy as np |
| 6 | +import pytest |
| 7 | + |
| 8 | +import hls4ml |
| 9 | + |
| 10 | +test_root_path = Path(__file__).parent |
| 11 | +test_root_path = Path('/tmp/trash') |
| 12 | + |
| 13 | + |
| 14 | +@pytest.mark.parametrize('k', [0, 1]) |
| 15 | +@pytest.mark.parametrize('i', [4, 8, 10]) |
| 16 | +@pytest.mark.parametrize('f', [-2, 0, 2, 7, 14]) |
| 17 | +def test_weight_writer(k, i, f): |
| 18 | + k, b, i = k, k + i + f, k + i |
| 19 | + w = np.array([[np.float32(2.0**-f)]]) |
| 20 | + u = '' if k else 'u' |
| 21 | + dtype = f'{u}fixed<{b}, {i}>' |
| 22 | + hls_config = {'LayerName': {'dense': {'Precision': {'weight': dtype}}}} |
| 23 | + model = keras.Sequential([keras.layers.Dense(1, input_shape=(1,), name='dense')]) |
| 24 | + model.layers[0].kernel.assign(keras.backend.constant(w)) |
| 25 | + output_dir = str(test_root_path / f'hls4ml_prj_test_weight_writer_{dtype}') |
| 26 | + model_hls = hls4ml.converters.convert_from_keras_model(model, hls_config=hls_config, output_dir=output_dir) |
| 27 | + model_hls.write() |
| 28 | + w_paths = glob(str(Path(output_dir) / 'firmware/weights/w*.txt')) |
| 29 | + print(w_paths[0]) |
| 30 | + assert len(w_paths) == 1 |
| 31 | + w_loaded = np.loadtxt(w_paths[0], delimiter=',').reshape(1, 1) |
| 32 | + print(f'{w[0,0]:.14}', f'{w_loaded[0,0]:.14}') |
| 33 | + assert np.all(w == w_loaded) |
0 commit comments