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

[mpact][compiler] add number of model parameters utility #63

Merged
merged 1 commit into from
Jul 29, 2024
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
14 changes: 13 additions & 1 deletion python/mpact/models/train.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,16 @@
import torch.nn.functional as F


def num_all_parameters(model):
"""Returns the number of all parameters in a model."""
return sum(p.numel() for p in model.parameters())


def num_parameters(model):
"""Returns the number of trainable parameters in a model."""
return sum(p.numel() for p in model.parameters() if p.requires_grad)


def training_loop(model, optimizer, loss_function, train, validation, epochs=10):
"""A rudimentary PyTorch training loop for classification with training and validation data."""
for epoch in range(epochs):
Expand All @@ -27,7 +37,9 @@ def training_loop(model, optimizer, loss_function, train, validation, epochs=10)
output = model(inp)
loss = loss_function(output, target)
vloss += loss.data.item()
correct = torch.eq(torch.max(F.softmax(output), dim=1)[1], target).view(-1)
correct = torch.eq(
torch.max(F.softmax(output, dim=1), dim=1)[1], target
).view(-1)
num_correct += torch.sum(correct).item()
num_total += correct.shape[0]

Expand Down
8 changes: 7 additions & 1 deletion test/python/train_simple.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from mpact.mpactbackend import mpact_jit
from mpact.models.kernels import SimpleNet
from mpact.models.train import training_loop
from mpact.models.train import training_loop, num_all_parameters, num_parameters


A = torch.tensor(
Expand Down Expand Up @@ -94,6 +94,12 @@ def __getitem__(self, index):
validation = DataLoader(validation_data, batch_size=2)


# CHECK-LABEL: parameters
# CHECK-COUNT-2: 182
print("parameters")
print(num_all_parameters(net))
print(num_parameters(net))

# Run it with PyTorch.
# CHECK-LABEL: pytorch
# CHECK: Epoch 9
Expand Down
Loading