{"slug": "how-to-save-my-model-to-use-it-later", "title": "How to save my model to use it later", "summary": "A Hugging Face forum user new to machine learning reported that `torch.save(trainer, 'my_model')` failed with an `AttributeError: Can't pickle local object 'get_linear_schedule_with_warmup.<locals>.lr_lambda'` after fine-tuning DistilBERT for multilabel text classification, and was advised by Hugging Face's merve to use `trainer.save_model(\"path_to_save\")` instead. The user later hit `AttributeError: 'DistilBertModel' object has no attribute 'logits'` when running inference, which was resolved by loading with `AutoModelForSequenceClassification.from_pretrained(path)` rather than `DistilBertModel.from_pretrained(path)`. Merve explained that BertModel classes lack classification heads, so the head-bearing classes are needed to produce logits.", "body_md": "Hello Amazing people,\n\nThis is my first post and I am really new to machine learning and Hugginface.\n\nI followed this awesome guide here [multilabel Classification with DistilBert](<https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/BERT/Fine_tuning_BERT_(and_friends)_for_multi_label_text_classification.ipynb>)\n\nand used my dataset and the results are very good.  I am having a hard time know trying to understand how to save the model I trainned and all the  artifacts needed to use my model later.\n\nI tried at the end of the tutorial:  `torch.save(trainer, 'my_model')` but I got this error msg:\n\n`AttributeError: Can't pickle local object 'get_linear_schedule_with_warmup.<locals>.lr_lambda'`\n\nI have the following files saved for each epoch:\n\n```\nconfig.json\n    optimizer.pt\n    pytorch_model.bin\n    rng_state.pth\n    special_tokens_map.json\n    tokenizer.json\n    tokenizer_config.json\n    trainer_state.json\n    training_args.bin\n    vocab.txt\n```\n\nCan someone kindly guide me how to save this model to later use?\n\nThank you very much\n\n \n \n[merve](https://discuss.huggingface.co/u/merve)\n2\n \nHello there,\n\nYou can save models with `trainer.save_model(\"path_to_save\")`. Another cool thing you can do is you can push your model to the Hugging Face Hub as well. I added couple of lines to notebook to show you, [here](https://colab.research.google.com/drive/1U7SX7jNYsNQG5BY1xEQQHu48Pn6Vgnyt?usp=sharing). You can find pushing there.\n\n \n \nThank you very much for helping me Merve.  Huge Thanks.\n\nJust one more question if you don’t mind:  I’ll now use my model locally at first.  You helped me to save all the files I need to load it again.\n\nSo to use the same model I save with `trainer.save_model(path)`  I just need to use `trainer.load(path)`?\n\nThank you very much \n\n \n \n[merve](https://discuss.huggingface.co/u/merve)\n4\n \nHello again,\n\nYou can simply load the model using the model class’ `from_pretrained(model_path)` method like below:\n\n(you can either save locally and load from local or push to Hub and load from Hub)\n\n``` python\nfrom transformers import BertConfig, BertModel\n# if model is on hugging face Hub\nmodel = BertModel.from_pretrained(\"bert-base-uncased\")\n# from local folder\nmodel = BertModel.from_pretrained(\"./test/saved_model/\")\n```\n\nAnother cool thing you can use is [pipeline API](https://huggingface.co/docs/transformers/main_classes/pipelines), it will make your life much easier . With pipelines, you will not have to deal with internals of the model or tokenizer to infer with the model, you simply give the folder and it will make the model ready to infer for you.\n\n \n \nYou are amazing merve   I’ll try do to this steps now.  Let’s see how it goes.\n\nThank you again\n\n \n \nHello again,\n\nSo I followed that tutorial to train my model(using distilert-base-uncased).\n\nsaved the model with:\n\n`trainer.save_model(\"./my_model\")`\n\nand then I loaded the model:\n\n``` python\nfrom transformers import DistilBertConfig, DistilBertModel\npath = 'path_to_my_model'\nmodel = DistilBertModel.from_pretrained(path)\n```\n\nNow I followed the same tutorial for inference but then I run:\n\n```\nencoding = tokenizer(text, return_tensors=\"pt\")\n\nencoding = {k: v.to(trainer.model.device) for k,v in encoding.items()}\noutputs = trainer.model(**encoding)\n```\n\nand then:\n\n`logits = outputs.logits` **raises the followin error:**\n\n`AttributeError: 'DistilBertModel' object has no attribute 'logits'`\n\nHow can I fix this step?\n\nThank you very much\n\n \n \nI found the error:  instead of\n\n`model = DistilBertModel.from_pretrained(path)`\n\nI changed to\n\n`model = AutoModelForSequenceClassification.from_pretrained(path)`\n\n \n \n[merve](https://discuss.huggingface.co/u/merve)\n8\n \n[@slowturtle](https://discuss.huggingface.co/u/slowturtle) Just to avoid confusion for future, the BertModel classes are simply BERT models without classification heads on top, so the heads include classification heads (and thus logit processors).\n\n \n \nHi Merve!\n\nI might be late but the tutorial that you have shared is excellent. My only questions is that can the same model be trained for a Multiclass text classification problem as well? If so, what parameters do I need to keep in mind while training this model? and also will this be successful for smaller datasets (<1000 records). It will be great to see if you have a notebook for this problem statement as well that I have just described\n\nThanks\n\nIshan\n\n \n \nHi!\n\nI run out of CUDA memory when saving a larger model using this. Is there a way I can move a gpu trained model to ‘cpu’ before saving using trainer.save_model(_). Appreciate the help, thanks!\n\n \n \nHello. After running a distilbert model, finetuned with my own custom dataset for classification purposes, i try to save the model in a .pth file format (e.g. distilmodel.pth). After training the model using the Trainer from the pytorch library, it saves a couples of archives into a checkpoint output folder, as declared into the Trainer’s arguments.\n\nAny help to convert the checkpoint into a model.pth format file?\n\nThanks in advance.\n\n \n \nWhat if we want to take a base model from HuggingFace, train it, save the fine-tune model, and then train it further? I want to train the model iteratively on subsets of my data so I don’t have to train it all at once because it will take a few weeks to do it all at once and I am afraid it will crash towards the end and waste the experiment, as well as I want to be able to test the output in between subsets of data.\n\nCurrently, when I try to load a custom model and tokenizer, though I can generate text with the model no problem, I get the below error when I attempt to train it further:\n\n```\nExpected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat2 in method wrapper_CUDA_mm)\n```\n\nThe thing is, this is not an issue when I train the base model model initially, but I have even tried forcing the data to be on the GPU before training and then just get the same error complaining about cuda:0 and cuda:3. I think the data moves to the GPU after training.Train() is called, and all my settings are the same besides the fact I am referencing my locally saved model and tokenizer path instead of the HuggingFace web path. Do I need to push my model to huggingface and then download from there? I looked at the folders that are cached from downloading the model and there are quite a few extra files that are cached aside from the files created when I save the model to a local folder, but any help would be very appreciated.\n\n \n \nI am using this repo to run a translation task. Especially I’m using it to build a diacritization model. I need to save the model after the process is done. How can I do that?\n\n```\nCUDA_VISIBLE_DEVICES=0 python run_translation.py --model_name_or_path Davlan/oyo-t5-small --do_train --do_eval --source_lang unyo --target_lang dcyo --source_prefix \"<unyo2dcyo>: \" --train_file data_prep_eng/output_data/bible_train.json --validation_file data_prep_eng/output_data/dev.json --test_file data_prep_eng/output_data/test.json --output_dir oyot5_small_unyo_dcyo_bible --max_source_length 512 --max_target_length 512 --per_device_train_batch_size=24 --per_device_eval_batch_size=24 --num_train_epochs 3 --overwrite_output_dir --predict_with_generate --save_steps 10000 --num_beams 10 --do_predict\n```\n\nAm I missing a flag like `--save-model`? I need the saved model to be part of the directory.\n\nSee what I have now:\n\n \n \nYes, you can. Assuming you are using torch:\n\nDEVICE = “cpu”\n\n#assuming huggingface model\n\nyour_model.to(DEVICE)\n\n# \n\nGPU_DEVICE = “cuda” if torch.cuda.is_available() else “cpu”\n\n \n \n[Greykxu](https://discuss.huggingface.co/u/Greykxu)\n15\n \nHi, thanks for the answer. But is there a method or convention to **NOT** use `trainer` to save models?\n\nI prefer to finetune my model by training in the traditional pytorch way because it’s more flexiable to add my own creativity. But I find it difficult to save it. The error message says that I shouldn’t use the identical checkpointing as the original model. What does it mean? Is there any method to solve it?\n\n \n \nI have a question about saving models. If I use `model.save_pretrained()`, will it save the original weights that weren’t optimized during training?\n\n \n \n[@Coalbbb](https://discuss.huggingface.co/u/coalbbb) Yes. For a standard Transformers model, `model.save_pretrained(\"./my-model\")` saves the model’s current weights, including both the weights updated during fine-tuning and the frozen weights. You can call it directly after a custom PyTorch training loop without using `Trainer`.\n\nIf you’re using LoRA through PEFT, `save_pretrained()` saves the adapter weights. You’ll also need the original base model when you reload it.", "url": "https://wpnews.pro/news/how-to-save-my-model-to-use-it-later", "canonical_source": "https://discuss.huggingface.co/t/how-to-save-my-model-to-use-it-later/20568#post_19", "published_at": "2026-12-01 04:14:59+00:00", "updated_at": "2026-12-01 04:44:19.986477+00:00", "lang": "en", "topics": ["machine-learning", "natural-language-processing", "ai-tools"], "entities": ["Hugging Face", "merve", "DistilBERT", "PyTorch", "Transformers"], "also_reported_by": [], "takeaway": "Save a fine-tuned Transformers model with `trainer.save_model(path)` instead of pickling the trainer, and reload it with `AutoModelForSequenceClassification.from_pretrained(path)` so the classification head and logits are available.", "recommendation": {"advice": "After fine-tuning, call `trainer.save_model(path)` rather than `torch.save(trainer)`, and reload with `AutoModelForSequenceClassification.from_pretrained(path)` to keep the classification head that produces logits.", "playbook": "training-data", "playbook_url": "https://wpnews.pro/playbooks/training-data"}, "alternates": {"html": "https://wpnews.pro/news/how-to-save-my-model-to-use-it-later", "markdown": "https://wpnews.pro/news/how-to-save-my-model-to-use-it-later.md", "text": "https://wpnews.pro/news/how-to-save-my-model-to-use-it-later.txt", "jsonld": "https://wpnews.pro/news/how-to-save-my-model-to-use-it-later.jsonld"}}