|
| 1 | +# Copyright (c) Sebastian Raschka under Apache License 2.0 (see LICENSE.txt). |
| 2 | +# Source for "Build a Large Language Model From Scratch" |
| 3 | +# - https://www.manning.com/books/build-a-large-language-model-from-scratch |
| 4 | +# Code: https://github.com/rasbt/LLMs-from-scratch |
| 5 | +# |
| 6 | +# A minimal instruction finetuning file based on the code in chapter 7 |
| 7 | + |
| 8 | +import json |
| 9 | +import psutil |
| 10 | +from tqdm import tqdm |
| 11 | +import urllib.request |
| 12 | + |
| 13 | + |
| 14 | +def query_model(prompt, model="llama3", url="http://localhost:11434/api/chat"): |
| 15 | + # Create the data payload as a dictionary |
| 16 | + data = { |
| 17 | + "model": model, |
| 18 | + "messages": [ |
| 19 | + {"role": "user", "content": prompt} |
| 20 | + ], |
| 21 | + "options": { # Settings below are required for deterministic responses |
| 22 | + "seed": 123, |
| 23 | + "temperature": 0, |
| 24 | + "num_ctx": 2048 |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + # Convert the dictionary to a JSON formatted string and encode it to bytes |
| 29 | + payload = json.dumps(data).encode("utf-8") |
| 30 | + |
| 31 | + # Create a request object, setting the method to POST and adding necessary headers |
| 32 | + request = urllib.request.Request(url, data=payload, method="POST") |
| 33 | + request.add_header("Content-Type", "application/json") |
| 34 | + |
| 35 | + # Send the request and capture the response |
| 36 | + response_data = "" |
| 37 | + with urllib.request.urlopen(request) as response: |
| 38 | + # Read and decode the response |
| 39 | + while True: |
| 40 | + line = response.readline().decode("utf-8") |
| 41 | + if not line: |
| 42 | + break |
| 43 | + response_json = json.loads(line) |
| 44 | + response_data += response_json["message"]["content"] |
| 45 | + |
| 46 | + return response_data |
| 47 | + |
| 48 | + |
| 49 | +def check_if_running(process_name): |
| 50 | + running = False |
| 51 | + for proc in psutil.process_iter(["name"]): |
| 52 | + if process_name in proc.info["name"]: |
| 53 | + running = True |
| 54 | + break |
| 55 | + return running |
| 56 | + |
| 57 | + |
| 58 | +def format_input(entry): |
| 59 | + instruction_text = ( |
| 60 | + f"Below is an instruction that describes a task. " |
| 61 | + f"Write a response that appropriately completes the request." |
| 62 | + f"\n\n### Instruction:\n{entry['instruction']}" |
| 63 | + ) |
| 64 | + |
| 65 | + input_text = f"\n\n### Input:\n{entry['input']}" if entry["input"] else "" |
| 66 | + |
| 67 | + return instruction_text + input_text |
| 68 | + |
| 69 | + |
| 70 | +def main(file_path): |
| 71 | + ollama_running = check_if_running("ollama") |
| 72 | + |
| 73 | + if not ollama_running: |
| 74 | + raise RuntimeError("Ollama not running. Launch ollama before proceeding.") |
| 75 | + print("Ollama running:", check_if_running("ollama")) |
| 76 | + |
| 77 | + with open(file_path, "r") as file: |
| 78 | + test_data = json.load(file) |
| 79 | + |
| 80 | + model = "llama3" |
| 81 | + scores = generate_model_scores(test_data, "model_response", model) |
| 82 | + print(f"Number of scores: {len(scores)} of {len(test_data)}") |
| 83 | + print(f"Average score: {sum(scores)/len(scores):.2f}\n") |
| 84 | + |
| 85 | + |
| 86 | +def generate_model_scores(json_data, json_key, model="llama3"): |
| 87 | + scores = [] |
| 88 | + for entry in tqdm(json_data, desc="Scoring entries"): |
| 89 | + if entry[json_key] == "": |
| 90 | + scores.append(0) |
| 91 | + else: |
| 92 | + prompt = ( |
| 93 | + f"Given the input `{format_input(entry)}` " |
| 94 | + f"and correct output `{entry['output']}`, " |
| 95 | + f"score the model response `{entry[json_key]}`" |
| 96 | + f" on a scale from 0 to 100, where 100 is the best score. " |
| 97 | + f"Respond with the integer number only." |
| 98 | + ) |
| 99 | + score = query_model(prompt, model) |
| 100 | + try: |
| 101 | + scores.append(int(score)) |
| 102 | + except ValueError: |
| 103 | + print(f"Could not convert score: {score}") |
| 104 | + continue |
| 105 | + |
| 106 | + return scores |
| 107 | + |
| 108 | + |
| 109 | +if __name__ == "__main__": |
| 110 | + |
| 111 | + import argparse |
| 112 | + |
| 113 | + parser = argparse.ArgumentParser( |
| 114 | + description="Evaluate model responses with ollama" |
| 115 | + ) |
| 116 | + parser.add_argument( |
| 117 | + "--file_path", |
| 118 | + required=True, |
| 119 | + help=( |
| 120 | + "The path to the test dataset `.json` file with the" |
| 121 | + " `'output'` and `'model_response'` keys" |
| 122 | + ) |
| 123 | + ) |
| 124 | + args = parser.parse_args() |
| 125 | + |
| 126 | + main(file_path=args.file_path) |
0 commit comments