MCPcopy Create free account
hub / github.com/algorithmicsuperintelligence/optillm / load_base_model

Method load_base_model

optillm/inference.py:1024–1111  ·  view source on GitHub ↗
(self, model_id: str, quantize: bool = True)

Source from the content-addressed store, hash-verified

1022 return model
1023
1024 def load_base_model(self, model_id: str, quantize: bool = True) -> Tuple[AutoModelForCausalLM, AutoTokenizer]:
1025 def _load_model():
1026 logger.info(f"Loading base model: {model_id}")
1027
1028 device = self.device_manager.get_optimal_device()
1029 logger.info(f"Using device: {device}")
1030
1031 # Load tokenizer
1032 tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True, token=os.getenv("HF_TOKEN"))
1033
1034 # Base kwargs for model loading
1035 model_kwargs = {
1036 "trust_remote_code": True,
1037 "device_map": "auto" if 'cuda' in device else device
1038 }
1039
1040 # Configure device-specific optimizations
1041 if 'cuda' in device:
1042 compute_capability = torch.cuda.get_device_capability(0)
1043 if compute_capability[0] >= 8:
1044 model_kwargs["torch_dtype"] = torch.bfloat16
1045 elif compute_capability[0] >= 7:
1046 model_kwargs["torch_dtype"] = torch.float16
1047
1048 # Check for flash attention availability
1049 try:
1050 import flash_attn
1051 has_flash_attn = True
1052 logger.info("Flash Attention 2 is available")
1053 model_kwargs["attn_implementation"] = "flash_attention_2"
1054 except ImportError:
1055 has_flash_attn = False
1056 logger.info("Flash Attention 2 is not installed - falling back to default attention")
1057
1058 elif 'mps' in device:
1059 # Special handling for Gemma models which have NaN issues with float16 on MPS
1060 if 'gemma' in model_id.lower():
1061 model_kwargs["torch_dtype"] = torch.float32
1062 logger.info("Using MPS device with float32 for Gemma model (float16 causes NaN)")
1063 else:
1064 model_kwargs["torch_dtype"] = torch.float16
1065 logger.info("Using MPS device with float16 precision")
1066 else:
1067 # CPU can use FP16 if available
1068 if hasattr(torch.cpu, 'has_fp16') and torch.cpu.has_fp16:
1069 model_kwargs["torch_dtype"] = torch.float16
1070 logger.info("Using CPU device with float16 precision")
1071 else:
1072 model_kwargs["torch_dtype"] = torch.float32
1073 logger.info("Using CPU device with float32 precision - FP16 not supported")
1074
1075 # Load model with configured optimizations
1076 try:
1077 model = AutoModelForCausalLM.from_pretrained(
1078 model_id,
1079 token=os.getenv("HF_TOKEN"),
1080 **model_kwargs
1081 )

Callers 1

__init__Method · 0.80

Calls 1

get_or_load_modelMethod · 0.80

Tested by

no test coverage detected