@@ -102,6 +102,30 @@ def __init__(self, models: Dict[str, "ExecuTorchModule"], config: "PretrainedCon
102102 setattr (self , key , value )
103103
104104 self .stats = Stats ()
105+
106+ # Initialize cleanup tracking
107+ self ._temp_dir = None
108+
109+ def __del__ (self ):
110+ """Clean up temporary files when the model instance is destroyed."""
111+ self ._cleanup_temp_resources ()
112+
113+ def _cleanup_temp_resources (self ):
114+ """Clean up temporary directory and files."""
115+ if hasattr (self , '_temp_dir' ) and self ._temp_dir is not None :
116+ try :
117+ if hasattr (self ._temp_dir , 'cleanup' ):
118+ # It's a TemporaryDirectory object
119+ self ._temp_dir .cleanup ()
120+ elif hasattr (self ._temp_dir , 'rmtree' ) or isinstance (self ._temp_dir , (str , Path )):
121+ # It's a path
122+ import shutil
123+ shutil .rmtree (self ._temp_dir , ignore_errors = True )
124+ except Exception :
125+ # Ignore cleanup errors to avoid issues during shutdown
126+ pass
127+ finally :
128+ self ._temp_dir = None
105129
106130 @abstractmethod
107131 def forward (self , * args , ** kwargs ):
@@ -274,7 +298,7 @@ def _export(
274298 for name , _ in executorch_progs .items ():
275299 models .update (cls ._from_pretrained (save_dir_path , file_name = f"{ name } .pte" , config = config ))
276300
277- return models
301+ return models , save_dir
278302
279303 def _save_pretrained (self , save_directory ):
280304 """
@@ -345,8 +369,9 @@ def from_pretrained(
345369 f"Could not infer whether the model was already converted or not to the ExecuTorch IR, keeping `export={ export } `.\n { exception } "
346370 )
347371
372+ temp_dir = None
348373 if _export :
349- models_dict = cls ._export (
374+ models_dict , temp_dir = cls ._export (
350375 model_id = model_id ,
351376 config = config ,
352377 revision = revision ,
@@ -376,7 +401,13 @@ def from_pretrained(
376401 )
377402 )
378403
379- return cls (models_dict , config )
404+ model_instance = cls (models_dict , config )
405+
406+ # Store the TemporaryDirectory reference to prevent GC
407+ if temp_dir is not None :
408+ model_instance ._temp_dir = temp_dir
409+
410+ return model_instance
380411
381412
382413class ExecuTorchModelForSeq2SeqLM (ExecuTorchModelBase ):
0 commit comments