Download inference.py from KhalidKhader/GPU-Project-phi-2-BZU-optimized-inference_opt-optimized: direct link, hf CLI and curl.
- Browser
- Download file 1.63 kB
-
https://huggingface.co/KhalidKhader/GPU-Project-phi-2-BZU-optimized-inference_opt-optimized/resolve/main/inference.py
- Command line
-
hf download hf://KhalidKhader/GPU-Project-phi-2-BZU-optimized-inference_opt-optimized/inference.py
-
curl -L -o inference.py https://huggingface.co/KhalidKhader/GPU-Project-phi-2-BZU-optimized-inference_opt-optimized/resolve/main/inference.py
1.63 kB
| """ | |
| Optimized Model Inference Script | |
| Method: inference_opt | |
| Performance: 954.14ms average | |
| """ | |
| import torch | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| print("Loading optimized model...") | |
| # Load tokenizer and model | |
| tokenizer = AutoTokenizer.from_pretrained("./") | |
| model = AutoModelForCausalLM.from_pretrained("./", torch_dtype=torch.float16).to("cuda") | |
| # Apply optimizations | |
| model.eval() | |
| torch.backends.cudnn.benchmark = True | |
| # Optimization method: inference_opt | |
| # Using basic optimizations | |
| # Disable gradients for inference | |
| with torch.no_grad(): | |
| for param in model.parameters(): | |
| param.requires_grad_(False) | |
| def generate_text(prompt, max_new_tokens=50, temperature=0.7): | |
| """Generate text with the optimized model""" | |
| inputs = tokenizer(prompt, return_tensors="pt").to("cuda") | |
| with torch.no_grad(): | |
| outputs = model.generate( | |
| inputs['input_ids'], | |
| max_new_tokens=max_new_tokens, | |
| temperature=temperature, | |
| do_sample=True, | |
| pad_token_id=tokenizer.eos_token_id | |
| ) | |
| return tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| # Test function | |
| def test_model(): | |
| """Test the optimized model""" | |
| test_prompts = [ | |
| "The future of AI is", | |
| "Machine learning will", | |
| "In the next decade, technology" | |
| ] | |
| print("Testing optimized model:") | |
| for prompt in test_prompts: | |
| result = generate_text(prompt, max_new_tokens=30) | |
| print(f"Prompt: {prompt}") | |
| print(f"Output: {result}") | |
| print("-" * 40) | |
| if __name__ == "__main__": | |
| test_model() | |