Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix writer precision when fp bits >= 14 #909

Merged
merged 2 commits into from
Nov 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 3 additions & 8 deletions hls4ml/model/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,14 +559,9 @@ def update_precision(self, new_precision):
if isinstance(new_precision, (IntegerPrecisionType, XnorPrecisionType, ExponentPrecisionType)):
self.precision_fmt = '{:.0f}'
elif isinstance(new_precision, FixedPrecisionType):
if new_precision.fractional > 0:
# Use str to represent the float with digits, get the length
# to right of decimal point
lsb = 2**-new_precision.fractional
decimal_spaces = len(str(lsb).split('.')[1])
self.precision_fmt = f'{{:.{decimal_spaces}f}}'
else:
self.precision_fmt = '{:.0f}'
decimal_spaces = max(0, new_precision.fractional)
self.precision_fmt = f'{{:.{decimal_spaces}f}}'

else:
raise RuntimeError(f"Unexpected new precision type: {new_precision}")

Expand Down
33 changes: 33 additions & 0 deletions test/pytest/test_weight_writer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from glob import glob
from pathlib import Path

import keras
import numpy as np
import pytest

import hls4ml

test_root_path = Path(__file__).parent
test_root_path = Path('/tmp/trash')


@pytest.mark.parametrize('k', [0, 1])
@pytest.mark.parametrize('i', [4, 8, 10])
@pytest.mark.parametrize('f', [-2, 0, 2, 7, 14])
def test_weight_writer(k, i, f):
k, b, i = k, k + i + f, k + i
w = np.array([[np.float32(2.0**-f)]])
u = '' if k else 'u'
dtype = f'{u}fixed<{b}, {i}>'
hls_config = {'LayerName': {'dense': {'Precision': {'weight': dtype}}}}
model = keras.Sequential([keras.layers.Dense(1, input_shape=(1,), name='dense')])
model.layers[0].kernel.assign(keras.backend.constant(w))
output_dir = str(test_root_path / f'hls4ml_prj_test_weight_writer_{dtype}')
model_hls = hls4ml.converters.convert_from_keras_model(model, hls_config=hls_config, output_dir=output_dir)
model_hls.write()
w_paths = glob(str(Path(output_dir) / 'firmware/weights/w*.txt'))
print(w_paths[0])
assert len(w_paths) == 1
w_loaded = np.loadtxt(w_paths[0], delimiter=',').reshape(1, 1)
print(f'{w[0,0]:.14}', f'{w_loaded[0,0]:.14}')
assert np.all(w == w_loaded)
Loading