File size: 1,668 Bytes
9aa8ed3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
from transformers import AutoTokenizer
from llama_modeling.front_end import LlamaForCausalLM
from llama_modeling.config import LlamaConfig
import json
import sys
from utils.trainutils import load_checkpoint

def generate_text(model, tokenizer, prompt, max_new_tokens=30):
    input_ids = tokenizer.encode(prompt, return_tensors='pt').to("cuda")
    
    with torch.inference_mode():
        outputs = model.generate(
            input_ids,
            max_new_tokens=max_new_tokens,
            temperature=0.7
        )
    
    return tokenizer.decode(outputs[0], skip_special_tokens=True)

def main():
    if len(sys.argv) != 2:
        print("Usage: python inference.py <path_to_model>")
        sys.exit(1)
        
    model_path = sys.argv[1]
    device = "cuda" if torch.cuda.is_available() else "cpu"
    
    with open("config.json") as f:
        config_dict = json.load(f)
    config = LlamaConfig(**{k: v for k, v in config_dict.items() if k in LlamaConfig.__dataclass_fields__})
    
    model = LlamaForCausalLM(config).to(device)
    
    load_checkpoint(model, model_path)
    model.eval()
    
    tokenizer = AutoTokenizer.from_pretrained("./SmolLM2-135M-Instruct")
    
    prompts = [
        "Once upon a time,",
        "The best way to learn programming is",
        "Here's a recipe for chocolate cake:"
    ]
    
    with torch.no_grad(), torch.autocast(device_type='cuda', dtype=None):
        for prompt in prompts:
            print(f"\nPrompt: {prompt}")
            output = generate_text(model, tokenizer, prompt)
            print(f"Generated: {output}")
            print("-" * 50)

if __name__ == "__main__":
    main()