Conversational version of ANWGPT2 (
anwgpt2-355m).
1torch==2.3.1
2torchvision==0.18.1
3torchaudio==2.3.1
4transformers==4.41.2
5peft==0.10.0
6accelerate==0.29.3
7datasets==2.19.0
8trl==0.8.6
9bitsandbytes==0.43.1
1# =================================================================================================
2# ANWGPT3 Inference Code - by ANW
3# =================================================================================================
4
5import torch
6import gc
7import time
8from transformers import AutoTokenizer, AutoModelForCausalLM
9from accelerate.utils import load_checkpoint_in_model
10from huggingface_hub import snapshot_download
11
12model_hub_id = "SubhrajitSain/anwgpt3-355m"
13base_model_name = "SubhrajitSain/anwgpt2-355m"
14
15if torch.cuda.is_available():
16 device = "cuda"
17 print("Using GPU. Loading model structure (FP16).")
18 load_kwargs = {}
19else:
20 device = "cpu"
21 print("Using CPU. Inference will be slow.")
22 load_kwargs = {}
23
24print(f"Downloading checkpoint files for {model_hub_id} to local cache...")
25local_checkpoint_path = snapshot_download(repo_id=model_hub_id)
26
27print(f"Loading tokenizer from: {model_hub_id}...")
28tokenizer = AutoTokenizer.from_pretrained(model_hub_id, use_fast=False)
29vocab_size = len(tokenizer)
30
31clean_template = (
32 "{% for message in messages %}"
33 "{{ message['content'] | trim }}\n"
34 "{% endfor %}"
35)
36tokenizer.chat_template = clean_template
37print("Applied chat template modification: Removed role tags in input.")
38
39terminators = [
40 tokenizer.eos_token_id,
41 tokenizer.convert_tokens_to_ids("<|im_end|>")
42]
43
44print(f"Loading base model structure from: {base_model_name}...")
45model = AutoModelForCausalLM.from_pretrained(
46 base_model_name,
47 torch_dtype=torch.float16,
48 **load_kwargs
49)
50
51print(f"Resizing model embeddings from {model.config.vocab_size} to {vocab_size} tokens.")
52model.resize_token_embeddings(vocab_size)
53model.config.vocab_size = vocab_size
54
55print("Loading final merged weights onto the resized model structure from local cache...")
56load_checkpoint_in_model(
57 model,
58 checkpoint=local_checkpoint_path
59)
60
61gc.collect()
62torch.cuda.empty_cache()
63
64model = model.to(device)
65model.eval()
66
67sys_prompt = "You are ANWGPT3, a large language model meticulously crafted by ANW. Your primary purpose is to be a helpful, harmless, and knowledgeable conversational partner. Engage users in a supportive and informative manner, striving for accuracy, clarity, and kindness in all your responses. Always be honest about your nature as an AI. If you do not know the answer to a question, admit it rather than inventing information. Your goal is to assist users thoughtfully and make every interaction a positive and productive one."
68
69print("\n--- Starting Interactive Chat with ANWGPT3 ---")
70print("Type 'quit' or 'exit' to stop. Type 'clear' to reset history. uwu")
71
72conversation_history = [
73 {"role": "system", "content": sys_prompt}
74]
75
76while True:
77 user_input = input("You: ")
78
79 if user_input.lower() in ["quit", "exit"]:
80 print("Exit inference.")
81 break
82
83 if user_input.lower() == "clear":
84 print("\n--- Conversation history reset! ---")
85 conversation_history = [
86 {"role": "system", "content": sys_prompt}
87 ]
88 continue
89
90 conversation_history.append({"role": "user", "content": user_input})
91
92 input_text = tokenizer.apply_chat_template(
93 conversation_history,
94 tokenize=False,
95 add_generation_prompt=True
96 )
97
98 input_ids = tokenizer(
99 input_text,
100 return_tensors="pt",
101 truncation=True
102 ).input_ids.to(model.device)
103
104 start_time = time.time()
105 with torch.no_grad():
106 generated_ids = model.generate(
107 input_ids,
108 max_new_tokens=512,
109 do_sample=True,
110 temperature=0.7,
111 top_p=0.9,
112 eos_token_id=terminators,
113 pad_token_id=tokenizer.eos_token_id
114 )
115 end_time = time.time()
116
117 new_tokens = generated_ids[0][len(input_ids[0]):]
118 response = tokenizer.decode(new_tokens, skip_special_tokens=True)
119
120 final_response = response.split("<|im_end|>")[0].strip()
121
122 final_response = final_response.replace("assistant", "").replace("[INST]", "").strip()
123
124 print(f"ANWGPT3: {final_response}")
125 print(f"(Time: {end_time - start_time:.2f}s)")
126
127 conversation_history.append({"role": "assistant", "content": final_response})
128
129print("\n--- Interactive session ended ---")
130
131del model
132gc.collect()
133torch.cuda.empty_cache()