ollama_evaluate.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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. import json
  8. import psutil
  9. from tqdm import tqdm
  10. import urllib.request
  11. def query_model(prompt, model="llama3", url="http://localhost:11434/api/chat"):
  12. # Create the data payload as a dictionary
  13. data = {
  14. "model": model,
  15. "seed": 123, # for deterministic responses
  16. "temperature": 0, # for deterministic responses
  17. "messages": [
  18. {"role": "user", "content": prompt}
  19. ]
  20. }
  21. # Convert the dictionary to a JSON formatted string and encode it to bytes
  22. payload = json.dumps(data).encode("utf-8")
  23. # Create a request object, setting the method to POST and adding necessary headers
  24. request = urllib.request.Request(url, data=payload, method="POST")
  25. request.add_header("Content-Type", "application/json")
  26. # Send the request and capture the response
  27. response_data = ""
  28. with urllib.request.urlopen(request) as response:
  29. # Read and decode the response
  30. while True:
  31. line = response.readline().decode("utf-8")
  32. if not line:
  33. break
  34. response_json = json.loads(line)
  35. response_data += response_json["message"]["content"]
  36. return response_data
  37. def check_if_running(process_name):
  38. running = False
  39. for proc in psutil.process_iter(["name"]):
  40. if process_name in proc.info["name"]:
  41. running = True
  42. break
  43. return running
  44. def format_input(entry):
  45. instruction_text = (
  46. f"Below is an instruction that describes a task. "
  47. f"Write a response that appropriately completes the request."
  48. f"\n\n### Instruction:\n{entry['instruction']}"
  49. )
  50. input_text = f"\n\n### Input:\n{entry['input']}" if entry["input"] else ""
  51. return instruction_text + input_text
  52. def main(file_path):
  53. ollama_running = check_if_running("ollama")
  54. if not ollama_running:
  55. raise RuntimeError("Ollama not running. Launch ollama before proceeding.")
  56. print("Ollama running:", check_if_running("ollama"))
  57. with open(file_path, "r") as file:
  58. test_data = json.load(file)
  59. model = "llama3"
  60. scores = generate_model_scores(test_data, "model_response", model)
  61. print(f"Number of scores: {len(scores)} of {len(test_data)}")
  62. print(f"Average score: {sum(scores)/len(scores):.2f}\n")
  63. def generate_model_scores(json_data, json_key, model="llama3"):
  64. scores = []
  65. for entry in tqdm(json_data, desc="Scoring entries"):
  66. if entry[json_key] == "":
  67. scores.append(0)
  68. else:
  69. prompt = (
  70. f"Given the input `{format_input(entry)}` "
  71. f"and correct output `{entry['output']}`, "
  72. f"score the model response `{entry[json_key]}`"
  73. f" on a scale from 0 to 100, where 100 is the best score. "
  74. f"Respond with the integer number only."
  75. )
  76. score = query_model(prompt, model)
  77. try:
  78. scores.append(int(score))
  79. except ValueError:
  80. print(f"Could not convert score: {score}")
  81. continue
  82. return scores
  83. if __name__ == "__main__":
  84. import argparse
  85. parser = argparse.ArgumentParser(
  86. description="Evaluate model responses with ollama"
  87. )
  88. parser.add_argument(
  89. "--file_path",
  90. required=True,
  91. help=(
  92. "The path to the test dataset `.json` file with the"
  93. " `'output'` and `'model_response'` keys"
  94. )
  95. )
  96. args = parser.parse_args()
  97. main(file_path=args.file_path)