Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
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.
✗ Incorrect
Tracing a model with torch.jit.trace records the operations performed with example inputs, creating a TorchScript version.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Not using quotes around the filename string.
Using a filename without an extension.
✗ Incorrect
The save method requires a string filename with quotes to save the model file.
3fill in blank
hardFix 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'
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.
✗ Incorrect
torch.jit.load loads a saved TorchScript model from a file.
4fill in blank
hardFill 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'
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.
✗ Incorrect
torch.jit.script creates a scripted model, and save writes it to a file.
5fill in blank
hardFill 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'
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.
✗ Incorrect
Load the model with torch.jit.load, pass input_tensor to it, and print the output's shape attribute.