- The top-level function containing the model functionality.
- A test bench MATLAB script file to drive the above function.
Import pytorch and use hdl coder to create system C code
5 views (last 30 days)
Show older comments
I created a deep learning mode on using pytorch using the following script
class RegressionANN(nn.Module):
def __init__(self):
super().__init__()
self.linear1 = nn.Linear(8, 64) # Increased neurons to 64
self.linear2 = nn.Linear(64, 1) # Changed input to 64
def forward(self, x):
x = torch.relu(self.linear1(x))
x = self.linear2(x)
return x
model = RegressionANN()
loss_fn = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
# Forward pass
y_pred = model(X_train_tensor)
# Calculate initial loss
initial_loss = loss_fn(y_pred, y_train_tensor)
print(f"Initial Loss: {initial_loss.item()}")
epochs = 100
for epoch in range(epochs):
# Zero gradients
optimizer.zero_grad()
# Forward pass
y_pred = model(X_train_tensor)
# Compute loss
loss = loss_fn(y_pred, y_train_tensor)
# Backpropagation
loss.backward()
# Update parameters
optimizer.step()
if (epoch + 1) % 10 == 0:
print(f'Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}')
print(f"Loss after {epochs} iterations: {loss.item():.4f}")
Following that I did the following
X = torch.rand(1, 8)
traced_model = torch.jit.trace(model.forward, X)
traced_model.save("traced_linear_model.pt")
Model was saved successfully. I tried importing the model using
importNetworkFromPyTorch
How do i proceed with HDL code generation ?
Importing created a matlab .m file for each layer.
Which matlab file should I use for code generation ?
0 Comments
Accepted Answer
Dev
on 28 Feb 2025
To generate System C code using the HDL Coder application in MATLAB R2024b, this application requires two basic files to proceed-
For more information on the same, please refer to the HDL code generation using HDL Coder documentation below-https://www.mathworks.com/help/releases/r2024b/visionhdl/ug/generate-hdl-code-from-matlab.html
The code provided in the question uses the ‘importNetworkFromPyTorch’ function to import the Pytorch model, which also generates the .M files for each custom layer in the model. However, this function does not generate dedicated top-level function or test bench files for the model, a necessary requirement in the HDL Coder workflow. You can refer more on this function below-
A possible workaround to generate the System C code for this Pytorch model is to use a combination of the Deep Network Designer and the MATLAB Coder applications available in MATLAB R2024b. The Deep Network Designer app can help us generate the corresponding MATLAB code for the functionality of our model. You can refer more on the usage of this application at the link below-
Next, the generated MATLAB code can then be provided to the MATLAB Coder app to generate the corresponding C code. For more information on the usage of this application, please refer to the link below-https://www.mathworks.com/help/releases/r2024b/coder/ref/matlabcoder-app.html
I hope the above workaround resolves the query.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!