Locutusque commited on
Commit
f51b8ab
1 Parent(s): 611b674

Create run_model.py

Browse files
Files changed (1) hide show
  1. run_model.py +39 -0
run_model.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import GPT2Tokenizer, GPT2LMHeadModel
3
+
4
+ tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
5
+ model = GPT2LMHeadModel.from_pretrained('gpt2')
6
+ tokenizer.add_special_tokens({'pad_token': '[PAD]'})
7
+ tokenizer.add_special_tokens({'eos_token': '<|End|>'})
8
+ special_tokens = {
9
+ "additional_special_tokens": ["<|USER|>", "<|SYSTEM|>", "<|ASSISTANT|>"]
10
+ }
11
+ tokenizer.add_special_tokens(special_tokens)
12
+ model.resize_token_embeddings(len(tokenizer))
13
+ model.load_state_dict(torch.load("pytorch_model.bin"))
14
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15
+ model.to(device)
16
+ def generate_text(model, tokenizer, prompt, max_length=1024):
17
+ prompt = f'<|SYSTEM|> You are a helpful AI designed to answer questions <|USER|> {prompt} <|ASSISTANT|> '
18
+ input_ids = tokenizer.encode(prompt, add_special_tokens=True, return_tensors="pt").to(device)
19
+ attention_mask = torch.ones_like(input_ids).to(device)
20
+ output = model.generate(input_ids,
21
+ max_length=max_length,
22
+ do_sample=True,
23
+ top_k=50,
24
+ top_p=0.30,
25
+ pad_token_id=tokenizer.pad_token_id,
26
+ eos_token_id=tokenizer.eos_token_id,
27
+ attention_mask=attention_mask)
28
+ output_ids = tokenizer.decode(output[0], skip_special_tokens=False)
29
+ assistant_token_index = output_ids.index('<|ASSISTANT|>') + len('<|ASSISTANT|>')
30
+ next_token_index = output_ids.find('<|', assistant_token_index)
31
+ output_ids = output_ids[assistant_token_index:next_token_index]
32
+ return output_ids
33
+ # Loop to interact with the model
34
+ while True:
35
+ prompt = input("Enter a prompt (or 'q' to quit): ")
36
+ if prompt == "q":
37
+ break
38
+ output_text = generate_text(model, tokenizer, prompt)
39
+ print(output_text)