Spaces:
Running on Zero
Running on Zero
Upload 132 files
Browse filesFiles changed (3)
134 unmodified lines135136137138139140102 unmodified lines243244245246247248249250251602 unmodified lines8548558568578588591108 unmodified lines19681969197019711972197349 unmodified lines20232024202520262027202818 unmodified lines204720482049205020512052205320544 unmodified lines2059206020612062206320642065326 unmodified lines239223932394239523962397157 unmodified lines255525562557255825592560256125622563256425652566134 unmodified linesmodel = AutoModelForCausalLM.from_pretrained(pretrained_path, **kwargs)# On MPS / CPU: model loaded without device_map, move to best deviceif not dev.supports_device_map_auto():target = dev.get_device()102 unmodified lines_obliterate_counter = idx + 1except (ValueError, IndexError):pass# If we recovered sessions but _state has no output_dir, set it to the# most recent checkpoint so chat_respond can reload from disk.if found_any and not _state.get("output_dir"):with _lock:latest = _last_obliterated_labelif latest and latest in _session_models:602 unmodified lines# Clear session model cache (checkpoints are gone)_session_models.clear()# Also clear GPU_clear_gpu()1108 unmodified lineson_stage=on_stage,on_log=on_log,)pipeline_ref[0] = pipelinepipeline.run_informed()else:49 unmodified linescot_aware=adv_cot_aware,n_sae_features=int(adv_n_sae_features),)pipeline_ref[0] = pipelinepipeline.run()except Exception as e:18 unmodified linesworker = threading.Thread(target=run_pipeline, daemon=True)worker.start()# Stream log updates while pipeline runs (max 45 minutes to prevent indefinite hang)_max_pipeline_secs = 45 * 60_pipeline_start = time.time()status_msg = "**Obliterating\u2026** (0s)"while worker.is_alive():4 unmodified lineselse:yield status_msg, "\n".join(log_lines), gr.update(), gr.update(), gr.update(), gr.update()if time.time() - _pipeline_start > _max_pipeline_secs:log_lines.append("\nTIMEOUT: Pipeline exceeded 45-minute limit.")breaktime.sleep(0.5)326 unmodified linesif not checkpoint or not Path(checkpoint).exists():_recover_sessions_from_disk()checkpoint = _state.get("output_dir")if checkpoint and Path(checkpoint).exists():try:is_preset = (_state.get("model_name") or "") in MODELS157 unmodified linesglobal _skip_session_loadif _skip_session_load > 0:_skip_session_load -= 1if choice and _state.get("status") == "ready":yield (f"**Ready!** `{choice}` is loaded β just type in the chat below.",get_chat_header(),)returnif not choice or choice not in _bench_configs:# On ZeroGPU, global state may be lost between process restarts.134 unmodified lines135136137138139140141142143144145102 unmodified lines248249250251252253254255256257258259602 unmodified lines8628638648658668678688698708718728738741108 unmodified lines198319841985198619871988198949 unmodified lines203920402041204220432044204518 unmodified lines206420652066206720682069207020714 unmodified lines2076207720782079208020812082326 unmodified lines24092410241124122413241424152416241724182419242024212422242324242425157 unmodified lines258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612134 unmodified linesmodel = AutoModelForCausalLM.from_pretrained(pretrained_path, **kwargs)# Compat: some custom model code (ChatGLM/GLM-4) accesses config.max_length# which was removed from PretrainedConfig in newer transformers.if not hasattr(model.config, "max_length"):model.config.max_length = 20# On MPS / CPU: model loaded without device_map, move to best deviceif not dev.supports_device_map_auto():target = dev.get_device()102 unmodified lines_obliterate_counter = idx + 1except (ValueError, IndexError):pass# If we recovered sessions and _state has no valid output_dir, set it to# the most recent checkpoint so chat_respond can reload from disk.# Also overwrite a stale output_dir that points to a non-existent path._cur_dir = _state.get("output_dir")_needs_update = not _cur_dir or not Path(_cur_dir).exists()if found_any and _needs_update:with _lock:latest = _last_obliterated_labelif latest and latest in _session_models:602 unmodified lines# Clear session model cache (checkpoints are gone)_session_models.clear()# Clear stale output_dir reference (checkpoints were just deleted)with _lock:_state["output_dir"] = None_state["model_name"] = None_state["method"] = None_state["status"] = "idle"# Also clear GPU_clear_gpu()1108 unmodified lineson_stage=on_stage,on_log=on_log,)pipeline._bayesian_trials = int(adv_bayesian_trials)pipeline_ref[0] = pipelinepipeline.run_informed()else:49 unmodified linescot_aware=adv_cot_aware,n_sae_features=int(adv_n_sae_features),)pipeline._bayesian_trials = int(adv_bayesian_trials)pipeline_ref[0] = pipelinepipeline.run()except Exception as e:18 unmodified linesworker = threading.Thread(target=run_pipeline, daemon=True)worker.start()# Stream log updates while pipeline runs (max 400 hours for large-model Optuna optimization)_max_pipeline_secs = 400 * 60 * 60_pipeline_start = time.time()status_msg = "**Obliterating\u2026** (0s)"while worker.is_alive():4 unmodified lineselse:yield status_msg, "\n".join(log_lines), gr.update(), gr.update(), gr.update(), gr.update()if time.time() - _pipeline_start > _max_pipeline_secs:log_lines.append("\nTIMEOUT: Pipeline exceeded 400-hour limit.")breaktime.sleep(0.5)326 unmodified linesif not checkpoint or not Path(checkpoint).exists():_recover_sessions_from_disk()checkpoint = _state.get("output_dir")# If output_dir is still stale, scan session models for any valid checkpointif not checkpoint or not Path(checkpoint).exists():for _sm in _session_models.values():_sm_dir = _sm.get("output_dir")if _sm_dir and Path(_sm_dir).exists():checkpoint = _sm_dirwith _lock:_state["output_dir"] = _sm_dir_state["model_name"] = _sm.get("model_choice")_state["method"] = _sm.get("method")breakif checkpoint and Path(checkpoint).exists():try:is_preset = (_state.get("model_name") or "") in MODELS157 unmodified linesglobal _skip_session_loadif _skip_session_load > 0:_skip_session_load -= 1# Verify the model is actually usable β not just that status says "ready".# ZeroGPU can evict the model while status stays "ready", and the counter# can get out of sync if only one dropdown .change fires instead of both.with _lock:_model_ok = (_state.get("status") == "ready"and _state.get("model") is not Noneand _state.get("tokenizer") is not None)if choice and _model_ok:# Double-check model tensors aren't stale (meta device)try:_dev = next(_state["model"].parameters()).deviceif _dev.type == "meta":_model_ok = Falseexcept Exception:_model_ok = Falseif choice and _model_ok:yield (f"**Ready!** `{choice}` is loaded β just type in the chat below.",get_chat_header(),)return# Model is stale or evicted β fall through to normal loading pathif not choice or choice not in _bench_configs:# On ZeroGPU, global state may be lost between process restarts.
464 unmodified lines465466467468469470158 unmodified lines629630631632633634464 unmodified linesf"If this model requires custom code, pass trust_remote_code=True explicitly.") from e# Memory estimation and warnings (skip for natively quantized models β estimate is wrong)native_quant = getattr(config, "quantization_config", None)est_gb = _estimate_model_memory_gb(config, torch_dtype) if native_quant is None else 0.0158 unmodified linesmodel.eval()# Free accelerator cache after loadingdev.empty_cache()464 unmodified lines465466467468469470471472473474475476477478479480158 unmodified lines639640641642643644645646647648649650464 unmodified linesf"If this model requires custom code, pass trust_remote_code=True explicitly.") from e# ββ Config compat: ensure generation-related attributes exist ββββββ# Older PretrainedConfig had max_length (default 20) and other generation# defaults. Newer transformers moved them to GenerationConfig, but some# custom model code (ChatGLM, GLM-4) still accesses config.max_length# directly. Patch them back so trust_remote_code models don't crash._gen_defaults = {"max_length": 20, "max_new_tokens": None}for _attr, _default in _gen_defaults.items():if not hasattr(config, _attr):setattr(config, _attr, _default)# Memory estimation and warnings (skip for natively quantized models β estimate is wrong)native_quant = getattr(config, "quantization_config", None)est_gb = _estimate_model_memory_gb(config, torch_dtype) if native_quant is None else 0.0158 unmodified linesmodel.eval()# Patch model.config with the same generation defaults (model.config may be# a separate instance from the config we pre-patched above).for _attr, _default in _gen_defaults.items():if not hasattr(model.config, _attr):setattr(model.config, _attr, _default)# Free accelerator cache after loadingdev.empty_cache()
12 unmodified lines13141512 unmodified linesscikit-learn>=1.3tqdm>=4.64bitsandbytes>=0.46.112 unmodified lines1314151612 unmodified linesscikit-learn>=1.3tqdm>=4.64bitsandbytes>=0.46.1optuna>=3.0
app.py+53-7
obliteratus/models/loader.py+16
requirements.txt+1