Upload SDG pipeline + classifier weights
Browse files47 unmodified lines484950515253545556575859606147 unmodified linesdef load_classifier_1280(weights_path: str,device: Optional[torch.device] = None,dtype: torch.dtype = torch.float32) -> SafetyClassifier1280:model = SafetyClassifier1280().to(device or "cpu", dtype=dtype)state = torch.load(weights_path, map_location="cpu")if isinstance(state, dict) and "model_state_dict" in state:state = state["model_state_dict"]model.load_state_dict(state, strict=True)model.eval()return model47 unmodified lines48495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949547 unmodified linesdef load_classifier_1280(weights_path: str,device=None,dtype: torch.dtype = torch.float32) -> SafetyClassifier1280:"""Robustly load classifier weights saved either as a pure state dict or as atraining checkpoint (with 'model_state_dict'), handling key prefixes andPyTorch 2.6's weights_only behavior."""model = SafetyClassifier1280().to(device or "cpu", dtype=dtype)# --- load robustly (PyTorch 2.6 & older) ---try:state = torch.load(weights_path, map_location="cpu", weights_only=False)except TypeError:state = torch.load(weights_path, map_location="cpu")except Exception:# Allowlist common numpy globals if needed for old picklestry:import numpy as npfrom torch.serialization import add_safe_globalsadd_safe_globals([np.dtype, np.number])except Exception:passstate = torch.load(weights_path, map_location="cpu", weights_only=False)# --- unwrap training checkpoint ---if isinstance(state, dict) and "model_state_dict" in state:state = state["model_state_dict"]# --- normalize keys: 'module.' -> '', 'model.' -> 'net.' ---norm_state = {}for k, v in state.items():k = k.replace("module.", "")k = k.replace("model.", "net.")norm_state[k] = v# --- load tolerating tiny diffs (e.g., extra keys from older heads) ---missing, unexpected = model.load_state_dict(norm_state, strict=False)if missing or unexpected:print(f"[SDG] Loaded classifier with relaxed strictness. "f"Missing: {len(missing)}, Unexpected: {len(unexpected)}")model.eval()return model
safe_diffusion_guidance.py+37-3