Datasets:
Download pytorch_fine_tuning_code/chat_f3.py from ysn-rfd/text-dataset-tiny-code-script-py-format: direct link, hf CLI and curl.
- Browser
- Download file 1.81 kB
-
https://huggingface.co/datasets/ysn-rfd/text-dataset-tiny-code-script-py-format/resolve/main/pytorch_fine_tuning_code/chat_f3.py
- Command line
-
hf download hf://datasets/ysn-rfd/text-dataset-tiny-code-script-py-format/pytorch_fine_tuning_code/chat_f3.py
-
curl -L -o chat_f3.py https://huggingface.co/datasets/ysn-rfd/text-dataset-tiny-code-script-py-format/resolve/main/pytorch_fine_tuning_code/chat_f3.py
1.81 kB
| #!/usr/bin/env python | |
| import torch | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| # Define the directory where your fine-tuned model is saved. | |
| model_dir = "./gpt2-finetuned" | |
| # Load the tokenizer and model from the saved directory. | |
| tokenizer = AutoTokenizer.from_pretrained(model_dir) | |
| model = AutoModelForCausalLM.from_pretrained(model_dir) | |
| # If you are using GPU and it's available, move the model to GPU. | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| model.to(device) | |
| print("Chat with the model! Type 'exit' or 'quit' to end the conversation.") | |
| while True: | |
| # Get user input. | |
| user_input = input("You: ") | |
| if user_input.lower() in ["exit", "quit"]: | |
| print("Exiting chat.") | |
| break | |
| # Encode the input text and generate an attention mask. | |
| inputs = tokenizer(user_input, return_tensors="pt", padding=True, truncation=True) | |
| input_ids = inputs["input_ids"].to(device) | |
| attention_mask = inputs["attention_mask"].to(device) # Explicitly set the attention mask | |
| # Generate a response. You can tweak the generation parameters as needed. | |
| output_ids = model.generate( | |
| input_ids, | |
| attention_mask=attention_mask, # Pass the attention mask here | |
| max_length=100, # Maximum length of the generated response. | |
| do_sample=True, # Use sampling; set to False for greedy decoding. | |
| top_p=0.95, # Top-p (nucleus) sampling. | |
| top_k=50, # Top-k sampling. | |
| pad_token_id=tokenizer.eos_token_id # Avoid warnings if no pad token is defined. | |
| ) | |
| # Decode the generated tokens to a string. | |
| response = tokenizer.decode(output_ids[0], skip_special_tokens=True) | |
| print("Bot:", response) | |