Saving model in fastai v2

Hello there,

I’m new to fastai v2 (not fastaiv1) and this forum so I’m still trying to figure a few things out.
I’ve trained a model and want to save it. In the fastai v2 documentation there is a function called ‘save_model()’. (https://docs.fast.ai/learner).

The arguments for the function are:

  • file (path)
    -model (I guess the trained learner object)
  • opt

My question is: what is opt?

When I pass the function without specifying opt I get this message (./ is the path, learn is the model I just trained:
save_model('./' , learn)
TypeError: save_model() missing 1 required positional argument: 'opt'

So I was wondering what opt is, as it’s not clear in the documentation.

Thank you in advance for anyone taking their time to answer the question.

hey @lucacontini, opt stands for optimizer (fastai vocab gets tricky sometimes: https://docs.fast.ai/dev/abbr). If you keep with_opt=True it is a required argument.

2 Likes

The better option is learn.save('myfname'). This will automatically fill that opt requirement for you. (and uses the API properly)

4 Likes

Thank you! Very helpful

That’s what I ended up doing. Thank you for the reply!

Bit confused by this, it’s a required argument even if with_opt=False? You can’t have an optional positional argument can you??

# %% ../nbs/13a_learner.ipynb 17
def load_model(file, model, opt, with_opt=True, device=None, strict=True, **torch_load_kwargs):
    "Load `model` from `file` along with `opt` (if available, and if `with_opt`)"
    if isinstance(device, int): device = torch.device('cuda', device)
    elif device is None: device = 'cpu'
    state = torch.load(file, map_location=device, **torch_load_kwargs)
    hasopt = set(state)=={'model', 'opt'}
    model_state = state['model'] if hasopt else state
    get_model(model).load_state_dict(model_state, strict=strict)
    if hasopt and with_opt:
        try: opt.load_state_dict(state['opt'])
        except:
            if with_opt: warn("Could not load the optimizer state.")
    elif with_opt: warn("Saved filed doesn't contain an optimizer state.")```