Yong Liu commited on
Commit ·
4aa4d08
1
Parent(s): 093ad9c
update handler
Browse files24 unmodified lines2526272829303132333435363738103 unmodified lines1421431441451461471481499 unmodified lines15916016116216316416516616716816924 unmodified lines# Load tokenizerself.tokenizer = AutoTokenizer.from_pretrained(self.model_path)# Load model directly without pipelineself.model = AutoModelForCausalLM.from_pretrained(self.model_path,torch_dtype=torch.float16,device_map="auto")print("Model loaded successfully")def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:"""Handle inference request in OpenAI-like format or HuggingFace Inference API format"""try:103 unmodified linesprompt = inputs["prompt"]params = inputs["generation_params"]# Tokenize inputinput_ids = self.tokenizer.encode(prompt, return_tensors="pt").to(self.model.device)# Count input tokensinput_tokens = input_ids.shape[1]9 unmodified lines}# Generate outputwith torch.no_grad():outputs = self.model.generate(input_ids,**generation_kwargs)# Decode outputgenerated_texts = []24 unmodified lines25262728293031323334353637383940414243444546474849505152535455565758596061103 unmodified lines1651661671681691701711721731741751761779 unmodified lines18718818919019119219319419519619719819920020120220320420520620720820921021121221321421521624 unmodified lines# Load tokenizerself.tokenizer = AutoTokenizer.from_pretrained(self.model_path)# Determine the device to useself.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")print(f"Using device: {self.device}")# Load model directly without pipelineself.model = AutoModelForCausalLM.from_pretrained(self.model_path,torch_dtype=torch.float16,device_map="auto")# Ensure model is on the correct deviceif torch.cuda.is_available():self.model = self.model.cuda()print("Model loaded successfully")# For Phi3 models, monkey patch the RotaryEmbeddingtry:from transformers.models.phi3.modeling_phi3 import PhiRotaryEmbeddingoriginal_forward = PhiRotaryEmbedding.forwarddef patched_forward(self, position_ids, query, key, value=None):# Ensure position_ids is on the same device as queryposition_ids = position_ids.to(query.device)return original_forward(self, position_ids, query, key, value)PhiRotaryEmbedding.forward = patched_forwardprint("Successfully patched PhiRotaryEmbedding.forward")except Exception as e:print(f"Could not patch PhiRotaryEmbedding: {str(e)}")def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:"""Handle inference request in OpenAI-like format or HuggingFace Inference API format"""try:103 unmodified linesprompt = inputs["prompt"]params = inputs["generation_params"]# Get the model's devicedevice = next(self.model.parameters()).deviceprint(f"Model is on device: {device}")# Tokenize input and ensure it's on the correct deviceinput_ids = self.tokenizer.encode(prompt, return_tensors="pt").to(device)print(f"Input tensor device: {input_ids.device}")# Count input tokensinput_tokens = input_ids.shape[1]9 unmodified lines}# Generate outputtry:with torch.no_grad():outputs = self.model.generate(input_ids,**generation_kwargs)print(f"Output tensor device: {outputs.device}")except RuntimeError as e:if "Expected all tensors to be on the same device" in str(e):print("Caught device mismatch error, trying to fix...")# A more drastic approach: move the model completely to CPU if there's a device issueif torch.cuda.is_available():print("Moving everything to CPU as a fallback")self.model = self.model.cpu()input_ids = input_ids.cpu()with torch.no_grad():outputs = self.model.generate(input_ids,**generation_kwargs)else:raiseelse:raise# Decode outputgenerated_texts = []
handler.py+54-7