1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| class LLMService: def __init__(self, model_path, config): self.config = config self.model = self.load_model(model_path) self.tokenizer = AutoTokenizer.from_pretrained(config["model_name"]) if config.get("use_flash_attention"): self.model = self.optimize_model() self.monitor = InferenceMonitor() def load_model(self, model_path): """加载模型""" model = AutoModelForCausalLM.from_pretrained( model_path, torch_dtype=torch.float16, device_map="auto" ) if self.config.get("quantized"): model = self.quantize_model(model) return model def optimize_model(self): """优化模型""" self.model = self.model.to(dtype=torch.bfloat16) if self.config.get("use_torch_compile"): self.model = torch.compile(self.model) return self.model def quantize_model(self, model): """量化模型""" from transformers import BitsAndBytesConfig bnb_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4", ) return AutoModelForCausalLM.from_pretrained( self.config["model_name"], quantization_config=bnb_config, device_map="auto" ) async def generate(self, request): """生成文本""" start_time = time.time() inputs = self.tokenizer( request.prompt, return_tensors="pt" ).to(self.model.device) with torch.no_grad(): outputs = self.model.generate( **inputs, max_new_tokens=request.max_new_tokens, temperature=request.temperature, top_p=request.top_p, do_sample=True ) response = self.tokenizer.decode( outputs[0], skip_special_tokens=True ) tokens_generated = outputs.shape[1] - inputs["input_ids"].shape[1] time_taken = time.time() - start_time self.monitor.record_request(tokens_generated, time_taken) return { "response": response, "tokens_generated": tokens_generated, "time_taken": time_taken }
|