Spaces:
No application file
No application file
Clanflare
feat: add timestamped model directories and model selection in interactive testing
c04ffda Download src/interactive_test.py from clanflare/mistral-7b-finetuning-scripts: direct link, hf CLI and curl.
- Browser
- Download file 6.36 kB
-
https://huggingface.co/spaces/clanflare/mistral-7b-finetuning-scripts/resolve/main/src/interactive_test.py
- Command line
-
hf download hf://spaces/clanflare/mistral-7b-finetuning-scripts/src/interactive_test.py
-
curl -L -o interactive_test.py https://huggingface.co/spaces/clanflare/mistral-7b-finetuning-scripts/resolve/main/src/interactive_test.py
6.36 kB
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| from peft import PeftModel | |
| import logging | |
| import argparse | |
| from pathlib import Path | |
| # Set up logging | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(levelname)s - %(message)s' | |
| ) | |
| logger = logging.getLogger(__name__) | |
| def load_model_and_tokenizer(model_path=None, base_model="mistralai/Mistral-7B-v0.1"): | |
| """ | |
| Load the model and tokenizer. | |
| Args: | |
| model_path (str, optional): Path to LoRA weights or full model. If None, uses base model only. | |
| base_model (str): Name or path of the base model to use. | |
| """ | |
| logger.info(f"Loading model from {model_path if model_path else base_model}...") | |
| try: | |
| # Load tokenizer from the appropriate source | |
| tokenizer_path = model_path if model_path else base_model | |
| tokenizer = AutoTokenizer.from_pretrained(tokenizer_path) | |
| tokenizer.pad_token = tokenizer.eos_token | |
| # Load base model | |
| model = AutoModelForCausalLM.from_pretrained( | |
| base_model, | |
| torch_dtype=torch.bfloat16, | |
| device_map="auto", | |
| trust_remote_code=True | |
| ) | |
| # If LoRA weights are specified, load them | |
| if model_path: | |
| logger.info(f"Loading LoRA weights from {model_path}...") | |
| model = PeftModel.from_pretrained(model, model_path) | |
| logger.info("LoRA weights loaded successfully!") | |
| return model, tokenizer | |
| except Exception as e: | |
| logger.error(f"Error loading model: {e}") | |
| raise | |
| def generate_response(model, tokenizer, prompt, max_length=1000, temperature=0.7, top_p=0.9): | |
| """ | |
| Generate a response for the given prompt. | |
| Args: | |
| model: The language model | |
| tokenizer: The tokenizer | |
| prompt (str): Input prompt | |
| max_length (int): Maximum length of generated text | |
| temperature (float): Sampling temperature | |
| top_p (float): Nucleus sampling parameter | |
| """ | |
| # Format the prompt | |
| formatted_prompt = f"""### Instruction: {prompt} | |
| ### Response:""" | |
| # Tokenize input | |
| inputs = tokenizer(formatted_prompt, return_tensors="pt").to(model.device) | |
| # Generate response | |
| with torch.no_grad(): | |
| outputs = model.generate( | |
| **inputs, | |
| max_length=max_length, | |
| temperature=temperature, | |
| top_p=top_p, | |
| do_sample=True, | |
| pad_token_id=tokenizer.pad_token_id, | |
| repetition_penalty=1.2, | |
| no_repeat_ngram_size=3 | |
| ) | |
| # Decode and clean response | |
| response = tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| response = response.split("### Response:")[-1].strip() | |
| return response | |
| def list_available_models(): | |
| """List all available models in the models directory.""" | |
| models_dir = Path("models") | |
| if not models_dir.exists(): | |
| return [] | |
| models = [] | |
| for path in models_dir.iterdir(): | |
| if path.is_dir(): | |
| models.append(path.name) | |
| return models | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Interactive testing script for language models") | |
| parser.add_argument( | |
| "--model_path", | |
| type=str, | |
| help="Path to the model weights (LoRA or full model). Use 'list' to see available models.", | |
| default=None | |
| ) | |
| parser.add_argument( | |
| "--base_model", | |
| type=str, | |
| default="mistralai/Mistral-7B-v0.1", | |
| help="Base model to use (default: mistralai/Mistral-7B-v0.1)" | |
| ) | |
| parser.add_argument( | |
| "--temperature", | |
| type=float, | |
| default=0.7, | |
| help="Sampling temperature (default: 0.7)" | |
| ) | |
| parser.add_argument( | |
| "--top_p", | |
| type=float, | |
| default=0.9, | |
| help="Nucleus sampling parameter (default: 0.9)" | |
| ) | |
| args = parser.parse_args() | |
| # Handle model listing | |
| if args.model_path == "list": | |
| models = list_available_models() | |
| if models: | |
| print("\nAvailable models in 'models' directory:") | |
| for model in models: | |
| print(f"- {model}") | |
| print("\nUse the model path as --model_path argument") | |
| else: | |
| print("\nNo models found in 'models' directory") | |
| return | |
| try: | |
| # Load model and tokenizer | |
| model_path = f"models/{args.model_path}" if args.model_path else None | |
| if model_path and not Path(model_path).exists(): | |
| model_path = args.model_path # Try using the path directly if not found in models directory | |
| model, tokenizer = load_model_and_tokenizer(model_path, args.base_model) | |
| logger.info("Model loaded successfully! Type 'quit' to exit.") | |
| # Print current configuration | |
| print("\nCurrent configuration:") | |
| print(f"Base model: {args.base_model}") | |
| print(f"Model path: {model_path if model_path else 'Using base model only'}") | |
| print(f"Temperature: {args.temperature}") | |
| print(f"Top-p: {args.top_p}") | |
| while True: | |
| try: | |
| # Get user input | |
| prompt = input("\nEnter your prompt (or 'quit' to exit): ") | |
| if prompt.lower() == 'quit': | |
| break | |
| if not prompt.strip(): | |
| print("Please enter a valid prompt.") | |
| continue | |
| # Generate and display response | |
| print("\nGenerating response...") | |
| response = generate_response( | |
| model, | |
| tokenizer, | |
| prompt, | |
| temperature=args.temperature, | |
| top_p=args.top_p | |
| ) | |
| print("\nResponse:") | |
| print(response) | |
| except KeyboardInterrupt: | |
| print("\n\nReceived interrupt signal. Type 'quit' to exit or press Ctrl+C again to force exit.") | |
| continue | |
| except Exception as e: | |
| logger.error(f"Error during testing: {e}") | |
| raise | |
| finally: | |
| print("\nThank you for using the interactive test script!") | |
| if __name__ == "__main__": | |
| main() |