44from __future__ import annotations
55
66import argparse
7+ import gc
78import importlib
89import json
910import math
11+ import multiprocessing
1012import shutil
1113import subprocess
1214import sys
@@ -670,6 +672,9 @@ def run_model(report_dir: Path, model_cfg: dict[str, Any], input_audio: Path, sa
670672 ffmpeg_to_mono_wav (input_audio , input_wav , model_sample_rate , log_path , name )
671673 encode_decode_hf (model_cfg , input_wav , hf_codes , hf_ref_wav , model_sample_rate , log_path , model , encoder_fn , decoder_fn )
672674
675+ del model , encoder_fn , decoder_fn
676+ gc .collect ()
677+
673678 n_q = int (model_cfg .get ("n_q" , 0 ))
674679 if model_cfg .get ("decode_only" ):
675680 run_decode (gguf_path , hf_codes , cpp_out_wav , n_q , log_path , name )
@@ -817,6 +822,46 @@ def parse_model_selection(raw_values: list[str] | None) -> list[str]:
817822 return selected
818823
819824
825+ def _run_model_worker (
826+ result_queue : multiprocessing .Queue ,
827+ report_dir : Path ,
828+ model_cfg : dict [str , Any ],
829+ input_audio : Path ,
830+ sample_rate : int ,
831+ ) -> None :
832+ result = run_model (report_dir , model_cfg , input_audio , sample_rate )
833+ result_queue .put (result )
834+
835+
836+ def _run_model_isolated (
837+ report_dir : Path ,
838+ model_cfg : dict [str , Any ],
839+ input_audio : Path ,
840+ sample_rate : int ,
841+ ) -> ModelResult :
842+ """Run a single model test in an isolated subprocess so all memory
843+ (PyTorch allocator pools, imported modules, HF caches) is reclaimed
844+ by the OS when the child exits."""
845+ q : multiprocessing .Queue = multiprocessing .Queue ()
846+ p = multiprocessing .Process (
847+ target = _run_model_worker ,
848+ args = (q , report_dir , model_cfg , input_audio , sample_rate ),
849+ )
850+ p .start ()
851+ p .join ()
852+ if not q .empty ():
853+ return q .get_nowait ()
854+ name = model_cfg ["name" ]
855+ return ModelResult (
856+ name = name ,
857+ status = "failed" ,
858+ duration_sec = 0.0 ,
859+ log_path = str (report_dir / f"{ name } .log" ),
860+ reason = f"worker process died (exit code { p .exitcode } )" ,
861+ return_code = p .exitcode ,
862+ )
863+
864+
820865def main () -> int :
821866 args = parse_args ()
822867 require_tools ()
@@ -842,7 +887,7 @@ def main() -> int:
842887
843888 results : list [ModelResult ] = []
844889 for model_cfg in selected_cfgs :
845- result = run_model (report_dir , model_cfg , input_audio , int (args .sample_rate ))
890+ result = _run_model_isolated (report_dir , model_cfg , input_audio , int (args .sample_rate ))
846891 results .append (result )
847892 print (f"[{ result .name } ] result: { result .status } " )
848893 if result .reason :
0 commit comments