import ast from datasets import load_dataset from transformers import AutoModelForCausalLM, AutoTokenizer import torch print("1. Loading LogistikaBench from Hugging Face...") # Replace with your actual Hugging Face repo path and file name if different dataset = load_dataset("berdymurad/LogistikaBench", data_files="logistikabench.csv") test_data = dataset["train"] print(f"Loaded {len(test_data)} evaluation items successfully!") print("\n2. Loading test model (Qwen2.5-1.5B-Instruct)...") model_id = "Qwen/Qwen2-7B-Instruct" # Changed model_id to a more powerful model tokenizer = AutoTokenizer.from_pretrained(model_id) try: model = AutoModelForCausalLM.from_pretrained( model_id, torch_dtype=torch.float16, device_map="auto" ) except Exception as e: print(f"Error loading model: {e}") raise # Re-raise the exception after printing for full traceback correct_predictions = 0 total_evaluated = 0 print("\n3. Starting benchmark loop...") for i, item in enumerate(test_data): question = item.get('question', '') # Safely parse choices and answers from string representation (e.g., "['Choice A', 'Choice B']") raw_choices = item.get('choices', '[]') if isinstance(raw_choices, str): choices_list = ast.literal_eval(raw_choices) else: choices_list = raw_choices raw_answer = item.get('answer', '[]') if isinstance(raw_answer, str): true_indices = ast.literal_eval(raw_answer) else: true_indices = raw_answer # Map zero-based indices [0, 1, 2] to letters ['A', 'B', 'C'] letter_mapping = {idx: chr(65 + idx) for idx in range(len(choices_list))} true_letters = set([letter_mapping[idx] for idx in true_indices if idx in letter_mapping]) # Format choices into a readable multiple-choice block (A. Choice text...) formatted_choices = "\n".join([f"{letter_mapping[idx]}: {choice}" for idx, choice in enumerate(choices_list)]) # Construct prompt instructing the model to output choice letters prompt = ( f"Answer the following logistics and supply chain multiple-choice question. " f"Note that there may be ONE or MORE correct answers. " f"Provide the letters of all correct options together (e.g., A, or AB, or A, C).\n\n" f"Question: {question}\n\n" f"Choices:\n{formatted_choices}\n\n" f"Answers (give only the letters):" ) inputs = tokenizer(prompt, return_tensors="pt").to(model.device) outputs = model.generate( **inputs, max_new_tokens=15, temperature=0.0, do_sample=False ) response = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True).upper().strip() # Define the set of valid answer letters for this specific question valid_choice_letters = set(letter_mapping.values()) # Extract predicted uppercase letters from the response, strictly from the beginning # and only until a non-answer-related character is encountered. predicted_letters_temp = set() for char in response: if char in valid_choice_letters: predicted_letters_temp.add(char) elif char.isspace() or char == ',': # Allow spaces and commas as separators within the answer sequence continue else: # Stop if any other character is encountered, assuming the answer sequence has ended break predicted_letters = predicted_letters_temp # Strict match check (model must pick the exact set of correct letters) if predicted_letters == true_letters: correct_predictions += 1 total_evaluated += 1 # Debug print statements removed if (i + 1) % 50 == 0: print(f"Processed {i + 1} / {len(test_data)} questions...") # Final Score Calculation accuracy = (correct_predictions / total_evaluated) * 100 print("\n================================") print(f"🏁 BENCHMARK COMPLETE!") print(f"Total Questions Evaluated: {total_evaluated}") print(f"Strict Match Accuracy: {accuracy:.2f}%") print("================================")