Lesson 2: Deploy to HF Spaces: pkl file needs to be compatible

For those who are experiencing a torch serialization issue of TypeError: code expected at most 16 arguments, got 18 when running load_learner(): This is caused by a mismatch of the model.pkl with the environment of your HuggingFace space.

I overcame this problem by finetuning the cat/dog classifier model on my local machine using specific versions for Python and the required packages:

  • python==3.11
  • torch==2.5.1
  • fastai==2.7.19

Now you can export the model.pkl file.

For your HuggingFace Space, use the same versions mentioned above. I.e. in your README.md, add a line of python_version: 3.11. In your requirements.txt, add this:

torch==2.5.1
fastai==2.7.19
gradio==5.29.0

The gradio version does not matter, but I decided to specify it as well. I hope that is helpful.

Hello,

Those encountering the torch serialization error — TypeError: code expected at most 16 arguments, got 18 when running load_learner() — are likely facing a version mismatch between the exported model.pkl and the environment in their HuggingFace Space. I resolved this by finetuning the cat/dog classifier locally using specific versions of Python and the necessary libraries: python==3.11, torch==2.5.1, and fastai==2.7.19. After training, I exported a fresh model.pkl. To ensure compatibility on HuggingFace, use the same versions in your Space by adding python_version: 3.11 to your README.md and including these exact versions in your requirements.txt.

Best Regards
E-ZPass New Hampshire