Spaces:
Sleeping
Sleeping
add reset_model_cache to prevent memory leak, force cpu_only and disable 8-bit quant for Phi-4
Browse files106 unmodified lines10710810911011111211311411511611711811912012112212312412512642 unmodified lines16917017117217317417517617717817918018118218318418518618718818919028 unmodified lines21922022122222322422522622722822923023123223323423523623774 unmodified lines312313314315316317406 unmodified lines724725726727728729106 unmodified linesdef initialize_model_once(model_key):with MODEL_CACHE["init_lock"]:current_model = MODEL_CACHE["model_name"]if MODEL_CACHE["model"] is None or current_model != model_key:# Clear previous modelif MODEL_CACHE["model"] is not None:del MODEL_CACHE["model"]if MODEL_CACHE["tokenizer"] is not None:del MODEL_CACHE["tokenizer"]torch.cuda.empty_cache() if torch.cuda.is_available() else Nonemodel_info = MODEL_CONFIG[model_key]model_name = model_info["name"]MODEL_CACHE["model_name"] = model_keytry:print(f"Loading model: {model_name}")# Check if this is a GGUF model42 unmodified lineslow_cpu_mem_usage=True)MODEL_CACHE["is_gguf"] = False# Special handling for models that cause memory issueselif model_key in ["Phi-4 Mini Instruct", "DeepSeek Lite Chat"]:# Reduce memory footprintos.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:64"# For CPU-only environments, load with 8-bit quantizationMODEL_CACHE["tokenizer"] = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)MODEL_CACHE["model"] = AutoModelForCausalLM.from_pretrained(model_name,load_in_8bit=True, # Use 8-bit instead of 4-bitdevice_map="auto" if torch.cuda.is_available() else None,low_cpu_mem_usage=True,trust_remote_code=True)MODEL_CACHE["is_gguf"] = False# Handle standard HF modelselse:28 unmodified linesMODEL_CACHE["is_gguf"] = Falseprint(f"Model {model_name} loaded successfully")except Exception as e:import tracebackprint(f"Error loading model {model_name}: {str(e)}")print(traceback.format_exc())raise RuntimeError(f"Failed to load model {model_name}: {str(e)}")# Final verification that model loaded correctlyif MODEL_CACHE["model"] is None:print(f"WARNING: Model {model_name} appears to be None after loading")# Try to free memory before returningtorch.cuda.empty_cache() if torch.cuda.is_available() else Nonegc.collect()return MODEL_CACHE["tokenizer"], MODEL_CACHE["model"], MODEL_CACHE.get("is_gguf", False)def get_fallback_model(current_model):74 unmodified linesprint(traceback.format_exc())raise RuntimeError(f"Failed to create pipeline: {str(e)}")# Modified handle_model_loading_error functiondef handle_model_loading_error(model_key, session_id):"""Handle model loading errors by providing alternative model suggestions or fallbacks"""406 unmodified lines# Reset handler - enables model selection againdef reset_session():return None, False, [], gr.update(interactive=True)reset_button.click(106 unmodified lines10710810911011111211311411511611711811912012112212312412512612712812913042 unmodified lines17317417517617717817918018118218318418518618718818919019119219319419519619719819920020120228 unmodified lines23123223323423523623723823924024124224324424524624724824925025125225325425525674 unmodified lines331332333334335336337338339340341342343344345346347348349350351352406 unmodified lines759760761762763764765106 unmodified linesdef initialize_model_once(model_key):with MODEL_CACHE["init_lock"]:try:current_model = MODEL_CACHE["model_name"]if MODEL_CACHE["model"] is None or current_model != model_key:# Clear previous modelif MODEL_CACHE["model"] is not None:del MODEL_CACHE["model"]if MODEL_CACHE["tokenizer"] is not None:del MODEL_CACHE["tokenizer"]# Force garbage collectiongc.collect()torch.cuda.empty_cache() if torch.cuda.is_available() else Nonetime.sleep(1) # Give system time to release memorymodel_info = MODEL_CONFIG[model_key]model_name = model_info["name"]MODEL_CACHE["model_name"] = model_keyprint(f"Loading model: {model_name}")# Check if this is a GGUF model42 unmodified lineslow_cpu_mem_usage=True)MODEL_CACHE["is_gguf"] = False# For Phi-4 specificallyelif "Phi-4" in model_key:MODEL_CACHE["tokenizer"] = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)MODEL_CACHE["model"] = AutoModelForCausalLM.from_pretrained(model_name,device_map="cpu", # Force CPU explicitlytorch_dtype=torch.float32, # Use float32 for CPUlow_cpu_mem_usage=True,trust_remote_code=True)MODEL_CACHE["is_gguf"] = False# Special handling for DeepSeek Lite Chatelif model_key == "DeepSeek Lite Chat":MODEL_CACHE["tokenizer"] = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)MODEL_CACHE["model"] = AutoModelForCausalLM.from_pretrained(model_name,device_map="cpu", # Force CPUtorch_dtype=torch.float32, # Use float32 for CPUlow_cpu_mem_usage=True,trust_remote_code=True)MODEL_CACHE["is_gguf"] = False# Handle standard HF modelselse:28 unmodified linesMODEL_CACHE["is_gguf"] = Falseprint(f"Model {model_name} loaded successfully")# Final verification that model loaded correctlyif MODEL_CACHE["model"] is None:print(f"WARNING: Model {model_name} appears to be None after loading")# Try to free memory before returningtorch.cuda.empty_cache() if torch.cuda.is_available() else Nonegc.collect()except Exception as e:# Reset model cache on errorMODEL_CACHE["model"] = NoneMODEL_CACHE["tokenizer"] = None# Force garbage collectiongc.collect()torch.cuda.empty_cache() if torch.cuda.is_available() else Noneimport tracebackprint(f"Error loading model {model_key}: {str(e)}")print(traceback.format_exc())raise RuntimeError(f"Failed to load model {model_key}: {str(e)}")return MODEL_CACHE["tokenizer"], MODEL_CACHE["model"], MODEL_CACHE.get("is_gguf", False)def get_fallback_model(current_model):74 unmodified linesprint(traceback.format_exc())raise RuntimeError(f"Failed to create pipeline: {str(e)}")# add a reset function to clear models between sessionsdef reset_model_cache():"""Force clear all model cache"""with MODEL_CACHE["init_lock"]:if MODEL_CACHE["model"] is not None:del MODEL_CACHE["model"]if MODEL_CACHE["tokenizer"] is not None:del MODEL_CACHE["tokenizer"]MODEL_CACHE["model"] = NoneMODEL_CACHE["tokenizer"] = NoneMODEL_CACHE["model_name"] = NoneMODEL_CACHE["is_gguf"] = Falsegc.collect()torch.cuda.empty_cache() if torch.cuda.is_available() else Nonetime.sleep(1)# Modified handle_model_loading_error functiondef handle_model_loading_error(model_key, session_id):"""Handle model loading errors by providing alternative model suggestions or fallbacks"""406 unmodified lines# Reset handler - enables model selection againdef reset_session():reset_model_cache() # call reset model cachereturn None, False, [], gr.update(interactive=True)reset_button.click(
app.py+69-33