File size: 2,201 Bytes
297bef1 |
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 |
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import os
def load_model_and_tokenizer(model_path):
# First, try loading from the directory
try:
print(f"Attempting to load model from directory: {model_path}")
model = AutoModelForCausalLM.from_pretrained(model_path)
except Exception as e:
print(f"Failed to load from directory. Error: {e}")
# If that fails, try loading the specific .safetensors file
safetensors_path = os.path.join(model_path, "model.safetensors")
if os.path.exists(safetensors_path):
print(f"Attempting to load model from file: {safetensors_path}")
model = AutoModelForCausalLM.from_pretrained(safetensors_path)
else:
raise ValueError(f"Could not find model at {model_path} or {safetensors_path}")
# Load the tokenizer from the original DistilGPT2 model
tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
return model, tokenizer
def generate_text(model, tokenizer, prompt, max_length=125, num_return_sequences=1):
input_ids = tokenizer.encode(prompt, return_tensors='pt')
# Generate text
output = model.generate(
input_ids,
max_length=max_length,
num_return_sequences=num_return_sequences,
no_repeat_ngram_size=6,
top_k=25,
top_p=0.99,
temperature=0.34
)
return [tokenizer.decode(seq, skip_special_tokens=True) for seq in output]
def main():
model_path = r"literalpathtothefoldernamed\checkpoint-4000" #change this to where you have the folder on your computer
print(f"Attempting to load model...")
model, tokenizer = load_model_and_tokenizer(model_path)
print("Model loaded successfully. Enter prompts to generate text. Type 'quit' to exit.")
while True:
prompt = input("Enter a prompt: ")
if prompt.lower() == 'quit':
break
generated_texts = generate_text(model, tokenizer, prompt)
print("\nGenerated Text:")
for i, text in enumerate(generated_texts, 1):
print(f"{i}. {text}\n")
if __name__ == "__main__":
main() |