Spaces:
No application file
No application file
File size: 6,361 Bytes
3c170e1 c04ffda 3c170e1 c04ffda 3c170e1 c04ffda 3c170e1 c04ffda 3c170e1 c04ffda 3c170e1 c04ffda 3c170e1 c04ffda 3c170e1 c04ffda 3c170e1 c04ffda 3c170e1 c04ffda 3c170e1 c04ffda 3c170e1 | 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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | 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() |