Create Example Inferencing Script.py
Browse files
Example Inferencing Script.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
3 |
+
import os
|
4 |
+
|
5 |
+
def load_model_and_tokenizer(model_path):
|
6 |
+
# First, try loading from the directory
|
7 |
+
try:
|
8 |
+
print(f"Attempting to load model from directory: {model_path}")
|
9 |
+
model = AutoModelForCausalLM.from_pretrained(model_path)
|
10 |
+
except Exception as e:
|
11 |
+
print(f"Failed to load from directory. Error: {e}")
|
12 |
+
# If that fails, try loading the specific .safetensors file
|
13 |
+
safetensors_path = os.path.join(model_path, "model.safetensors")
|
14 |
+
if os.path.exists(safetensors_path):
|
15 |
+
print(f"Attempting to load model from file: {safetensors_path}")
|
16 |
+
model = AutoModelForCausalLM.from_pretrained(safetensors_path)
|
17 |
+
else:
|
18 |
+
raise ValueError(f"Could not find model at {model_path} or {safetensors_path}")
|
19 |
+
|
20 |
+
# Load the tokenizer from the original DistilGPT2 model
|
21 |
+
tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
|
22 |
+
|
23 |
+
return model, tokenizer
|
24 |
+
|
25 |
+
def generate_text(model, tokenizer, prompt, max_length=125, num_return_sequences=1):
|
26 |
+
input_ids = tokenizer.encode(prompt, return_tensors='pt')
|
27 |
+
|
28 |
+
# Generate text
|
29 |
+
output = model.generate(
|
30 |
+
input_ids,
|
31 |
+
max_length=max_length,
|
32 |
+
num_return_sequences=num_return_sequences,
|
33 |
+
no_repeat_ngram_size=6,
|
34 |
+
top_k=25,
|
35 |
+
top_p=0.99,
|
36 |
+
temperature=0.34
|
37 |
+
)
|
38 |
+
|
39 |
+
return [tokenizer.decode(seq, skip_special_tokens=True) for seq in output]
|
40 |
+
|
41 |
+
def main():
|
42 |
+
model_path = r"literalpathtothefoldernamed\checkpoint-4000" #change this to where you have the folder on your computer
|
43 |
+
|
44 |
+
print(f"Attempting to load model...")
|
45 |
+
model, tokenizer = load_model_and_tokenizer(model_path)
|
46 |
+
|
47 |
+
print("Model loaded successfully. Enter prompts to generate text. Type 'quit' to exit.")
|
48 |
+
|
49 |
+
while True:
|
50 |
+
prompt = input("Enter a prompt: ")
|
51 |
+
if prompt.lower() == 'quit':
|
52 |
+
break
|
53 |
+
|
54 |
+
generated_texts = generate_text(model, tokenizer, prompt)
|
55 |
+
|
56 |
+
print("\nGenerated Text:")
|
57 |
+
for i, text in enumerate(generated_texts, 1):
|
58 |
+
print(f"{i}. {text}\n")
|
59 |
+
|
60 |
+
if __name__ == "__main__":
|
61 |
+
main()
|