Views
No views yet
1from llama_cpp import Llama
2from huggingface_hub import hf_hub_download
3import os
4import sys
5import contextlib
6
7# Suppress warnings
8@contextlib.contextmanager
9def suppress_stderr():
10 stderr = sys.stderr
11 with open(os.devnull, 'w') as devnull:
12 sys.stderr = devnull
13 try:
14 yield
15 finally:
16 sys.stderr = stderr
17
18# or change the filename to AstroSage-8B-BF16.gguf for BF16 quantization
19def download_model(repo_id="AstroMLab/AstroSage-8B-GGUF", filename="AstroSage-8B-Q8_0.gguf"):
20 try:
21 os.makedirs("models", exist_ok=True)
22 local_path = os.path.join("models", filename)
23 if not os.path.exists(local_path):
24 print(f"Downloading {filename}...")
25 with suppress_stderr():
26 local_path = hf_hub_download(
27 repo_id=repo_id,
28 filename=filename,
29 local_dir="models",
30 local_dir_use_symlinks=False
31 )
32 print("Download complete!")
33 return local_path
34 except Exception as e:
35 print(f"Error downloading model: {e}")
36 raise
37
38def initialize_llm():
39 model_path = download_model()
40 with suppress_stderr():
41 return Llama(
42 model_path=model_path,
43 n_ctx=2048,
44 n_threads=4
45 )
46
47def get_response(llm, prompt, max_tokens=128):
48 response = llm(
49 prompt,
50 max_tokens=max_tokens,
51 temperature=0.7,
52 top_p=0.9,
53 top_k=40,
54 repeat_penalty=1.1,
55 stop=["User:", "\n\n"]
56 )
57 return response['choices'][0]['text']
58
59def main():
60 llm = initialize_llm()
61
62 # Example question about galaxy formation
63 first_question = "How does a galaxy form?"
64 print("\nQuestion:", first_question)
65 print("\nAI:", get_response(llm, first_question).strip(), "\n")
66
67 print("\nYou can now ask more questions! Type 'quit' or 'exit' to end the conversation.\n")
68
69 while True:
70 try:
71 user_input = input("You: ")
72 if user_input.lower() in ['quit', 'exit']:
73 print("\nGoodbye!")
74 break
75
76 print("\nAI:", get_response(llm, user_input).strip(), "\n")
77
78 except KeyboardInterrupt:
79 print("\nGoodbye!")
80 break
81 except Exception as e:
82 print(f"Error: {e}")
83
84if __name__ == "__main__":
85 main()pip install llama-cpp-python huggingface_hubCMAKE_ARGS="-DCMAKE_OSX_ARCHITECTURES=arm64 -DLLAMA_METAL=on" pip install llama-cpp-pythonn_ctx: Context window size (default: 2048)n_threads: Number of CPU threads to use (adjust based on your hardware)temperature: Controls randomnesstop_p: Nucleus sampling parametertop_k: Limits vocabulary choicesrepeat_penalty: Prevents repetitionmax_tokens: Maximum length of response (128 default, increase for longer answers)@preprint{dehaan2024astromlab3,
title={AstroMLab 3: Achieving GPT-4o Level Performance in Astronomy with a Specialized 8B-Parameter Large Language Model},
author={Tijmen de Haan and Yuan-Sen Ting and Tirthankar Ghosal and Tuan Dung Nguyen and Alberto Accomazzi and Azton Wells and Nesar Ramachandra and Rui Pan and Zechang Sun},
year={2024},
eprint={2411.09012},
archivePrefix={arXiv},
primaryClass={astro-ph.IM},
url={https://arxiv.org/abs/2411.09012},
}