Skip to content

Hello, after converting GRU network to IP core using hls4ml, the output of IP core is not always 0. Here is my conversion code. #1111

Open
@yulin3262

Description

@yulin3262

from pathlib import Path

import numpy as np
import pytest
import torch
import torch.nn as nn

from hls4ml.converters import convert_from_pytorch_model
from hls4ml.utils.config import config_from_pytorch_model
from hls4ml.utils import plot_model
import plotting
import hls4ml

test_root_path = Path(file).parent

import os
os.environ['PATH'] = '/tools/Xilinx/Vivado/2019.2/bin:' + os.environ['PATH']

class GRUNet(nn.Module):
def init(self):
super().init()
self.rnn = nn.GRU(4, 2, num_layers=1, batch_first=True, bias=True)

def forward(self, x, h0):
    output, hnn = self.rnn(x, h0)
    return output

def test_gru(backend, io_type):
model = GRUNet()
model.eval()

X_input = torch.randn(1, 1, 4)
h0 = torch.zeros(1, 1, 2)

pytorch_prediction = model(torch.Tensor(X_input), torch.Tensor(h0)).detach().numpy()

config = config_from_pytorch_model(
    model, [(None, 1, 4), (None, 1, 2)], channels_last_conversion="off", transpose_outputs=False
)
config['Model']['ReuseFactor'] = 1
config['Model']['Precision'] = 'ap_fixed<16,6>'    
print("-----------------------------------")
print("Configuration")
plotting.print_dict(config)
print("-----------------------------------")
output_dir = str(test_root_path / f'hls4mlprj_pytorch_api_gru_{backend}_{io_type}')

#hls_model = convert_from_pytorch_model(model, hls_config=config, output_dir=output_dir, backend=backend, io_type=io_type, part='xcu250-figd2104-2L-e')
hls_model = convert_from_pytorch_model(model, hls_config=config, output_dir=output_dir, backend=backend, io_type=io_type,
                                       part='xc7z045ffg900-2',clock_period = 4)

plot_model(hls_model, show_shapes=True, show_precision=True, to_file=None)

hls_model.compile()

hls_prediction = np.reshape(hls_model.predict([X_input.detach().numpy(), h0.detach().numpy()]), (1, 1, 2))

print("*****************************************")
print(X_input,h0,pytorch_prediction,hls_prediction)
print("*****************************************")

np.testing.assert_allclose(hls_prediction, pytorch_prediction, rtol=0, atol=1e-1)

hls_model.build(csim=True, export=True)

hls4ml.report.read_vivado_report(output_dir)

if name == 'main':
test_gru('Vivado', 'io_stream')

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions