get the number of model parameters load with torch.jit.load
- User
get the number of model parameters load with torch.jit.load
- Assistant
In PyTorch, when you load a model using
torch.jit.load, you get a ScriptModule which is a JIT-ed version of the original PyTorch model. The model parameters are not as straightforward to count as in a regular nn.Module, because they are not exposed as easily in the attributes.If you want to count the number of parameters after loading a JIT model, you can iterate over the parameters by using the
parameters()method. Here's an example of how you could do this:import torch # Load the ScriptModule from a file. jit_model = torch.jit.load('path_to_your_saved_model.pt') # Iterate over the parameters and count them. num_params = sum(param.numel() for param in jit_model.parameters()) print(f"The loaded model has {num_params} parameters.")The
param.numel()function returns the total number of elements in the parameter tensor, and summing these gives the total number of parameters across all the tensors in the model.Keep in mind that if your model has buffers or non-parameter tensors you want to include in the count, you would need to iterate over them in addition to the parameters.