Skip to content

Commit f8aecb6

Browse files
authored
Merge pull request #19 from RMeli/jit
Compile models and losses with TorchScript for training and inference
2 parents 39985f3 + d34c1e6 commit f8aecb6

3 files changed

Lines changed: 14 additions & 9 deletions

File tree

gnina/inference.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,9 @@ def inference(args):
153153
# Create model
154154
model = models.models_dict[(args.model, affinity)](test_loader.dims).to(device)
155155

156+
# Compile model with TorchScript
157+
model = torch.jit.script(model)
158+
156159
# Load checkpoint
157160
checkpoint = torch.load(args.checkpoint, map_location=device)
158161
Checkpoint.load_objects(to_load={"model": model}, checkpoint=checkpoint)

gnina/losses.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def forward(self, input: Tensor, target: Tensor) -> Tensor:
9090

9191
if self.reduction == "mean":
9292
reduced_loss = torch.mean(loss)
93-
elif self.reduction == "sum":
93+
else: # Assertion in init ensures that reduction is "sum"
9494
reduced_loss = torch.sum(loss)
9595

9696
return self.scale * reduced_loss

gnina/training.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -589,8 +589,8 @@ def training(args):
589589
model = models_dict[(args.model, affinity)](train_loader.dims).to(device)
590590
model.apply(weights_and_biases_init)
591591

592-
# TODO: Compile model into TorchScript
593-
# Requires model refactoring to avoid branching based on affinity
592+
# Compile model into TorchScript
593+
model = torch.jit.script(model)
594594

595595
optimizer = optim.SGD(
596596
model.parameters(),
@@ -600,13 +600,15 @@ def training(args):
600600
)
601601

602602
# Define loss functions
603-
pose_loss = nn.NLLLoss()
603+
pose_loss = torch.jit.script(nn.NLLLoss())
604604
affinity_loss = (
605-
AffinityLoss(
606-
delta=args.delta_affinity_loss,
607-
penalty=args.penalty_affinity_loss,
608-
pseudo_huber=args.pseudo_huber_affinity_loss,
609-
scale=args.scale_affinity_loss,
605+
torch.jit.script(
606+
AffinityLoss(
607+
delta=args.delta_affinity_loss,
608+
penalty=args.penalty_affinity_loss,
609+
pseudo_huber=args.pseudo_huber_affinity_loss,
610+
scale=args.scale_affinity_loss,
611+
)
610612
)
611613
if affinity
612614
else None

0 commit comments

Comments
 (0)