0
0
PyTorchml~10 mins

TorchScript export in PyTorch - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to convert a PyTorch model to TorchScript using tracing.

PyTorch
import torch
import torch.nn as nn

class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(10, 5)

    def forward(self, x):
        return self.linear(x)

model = SimpleModel()
example_input = torch.randn(1, 10)
scripted_model = torch.jit.[1](model, example_input)
Drag options to blanks, or click blank then click option'
Atrace
Boptimize
Ccompile
Dscript
Attempts:
3 left
💡 Hint
Common Mistakes
Using torch.jit.script instead of torch.jit.trace for models with simple forward passes.
Not providing example inputs to the trace function.
2fill in blank
medium

Complete the code to save the TorchScript model to a file.

PyTorch
scripted_model.save([1])
Drag options to blanks, or click blank then click option'
Amodel
B'model.pt'
C'model'
Dmodel.pt
Attempts:
3 left
💡 Hint
Common Mistakes
Not using quotes around the filename string.
Using a filename without an extension.
3fill in blank
hard

Fix the error in loading a TorchScript model from a file.

PyTorch
loaded_model = torch.jit.[1]('model.pt')
Drag options to blanks, or click blank then click option'
Aload
Bscript
Ctrace
Dimport
Attempts:
3 left
💡 Hint
Common Mistakes
Using torch.jit.script or torch.jit.trace to load a model file.
Using an incorrect function name like import.
4fill in blank
hard

Fill both blanks to create a TorchScript model using scripting and then save it.

PyTorch
scripted_model = torch.jit.[1](model)
scripted_model.[2]('scripted_model.pt')
Drag options to blanks, or click blank then click option'
Ascript
Bsave
Ctrace
Dload
Attempts:
3 left
💡 Hint
Common Mistakes
Using trace instead of script for models with control flow.
Using load instead of save to write the model.
5fill in blank
hard

Fill all three blanks to load a TorchScript model, run it on input, and print the output shape.

PyTorch
loaded_model = torch.jit.[1]('scripted_model.pt')
input_tensor = torch.randn(2, 10)
output = loaded_model([2])
print(output.[3])
Drag options to blanks, or click blank then click option'
Aload
Binput_tensor
Cshape
Dscript
Attempts:
3 left
💡 Hint
Common Mistakes
Using script instead of load to load the model.
Passing wrong variable to the model call.
Printing output instead of output.shape.