File size: 1,625 Bytes
e7b819c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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()