Nexus-Walker commited on
Commit
08153b5
·
verified ·
1 Parent(s): 39f2da9

Upload chat.py

Browse files

👉 For a conversational CLI with memory, run [chat.py](./chat.py).

Files changed (1) hide show
  1. chat.py +162 -0
chat.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ RESON-LLAMA Chat con MEMORIA CONVERSAZIONALE - PULIZIA MINIMALE
4
+ """
5
+
6
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
7
+ from peft import PeftModel
8
+ import torch
9
+ import warnings
10
+ import re
11
+
12
+ warnings.filterwarnings("ignore", category=UserWarning)
13
+
14
+ conversation_turns = []
15
+ MAX_MEMORY_TURNS = 4
16
+
17
+ def load_reson_model(model_path=r"C:\Users\dacan\OneDrive\Desktop\Meta\Reson4.5\Reson4.5"):
18
+ print(f"🧠 Caricamento RESON-LLAMA da {model_path}...")
19
+
20
+ base_model_name = "meta-llama/Llama-2-7b-chat-hf"
21
+
22
+ bnb_config = BitsAndBytesConfig(
23
+ load_in_4bit=True,
24
+ bnb_4bit_compute_dtype=torch.float16,
25
+ bnb_4bit_quant_type="nf4",
26
+ bnb_4bit_use_double_quant=True,
27
+ )
28
+
29
+ tokenizer = AutoTokenizer.from_pretrained(base_model_name, trust_remote_code=True)
30
+ if tokenizer.pad_token is None:
31
+ tokenizer.pad_token = tokenizer.eos_token
32
+ tokenizer.pad_token_id = tokenizer.eos_token_id
33
+
34
+ base_model = AutoModelForCausalLM.from_pretrained(
35
+ base_model_name,
36
+ quantization_config=bnb_config,
37
+ torch_dtype=torch.float16,
38
+ device_map="auto",
39
+ trust_remote_code=True,
40
+ use_cache=False,
41
+ low_cpu_mem_usage=True
42
+ )
43
+
44
+ model = PeftModel.from_pretrained(base_model, model_path)
45
+
46
+ print("✅ RESON-LLAMA V4 caricato con memoria!")
47
+ return model, tokenizer
48
+
49
+ def minimal_clean_response(response):
50
+ """Pulizia MINIMALE - rimuove tutto tra parentesi quadre"""
51
+
52
+ # Rimuovi QUALSIASI cosa tra parentesi quadre [...]
53
+ cleaned = re.sub(r'\[.*?\]', '', response)
54
+
55
+ # Pulizia spazi multipli
56
+ cleaned = re.sub(r'[ \t]+', ' ', cleaned)
57
+ cleaned = re.sub(r' *\n *', '\n', cleaned)
58
+ cleaned = re.sub(r'\n{3,}', '\n\n', cleaned)
59
+ cleaned = cleaned.strip()
60
+
61
+ return cleaned
62
+
63
+ def format_conversation_prompt(conversation_turns, current_question):
64
+ prompt_parts = []
65
+
66
+ for turn in conversation_turns[-MAX_MEMORY_TURNS:]:
67
+ prompt_parts.append(f"[INST] {turn['question']} [/INST] {turn['answer']}")
68
+
69
+ prompt_parts.append(f"[INST] {current_question} [/INST]")
70
+
71
+ full_prompt = " ".join(prompt_parts)
72
+ return full_prompt
73
+
74
+ def generate_response(model, tokenizer, prompt):
75
+ inputs = tokenizer(
76
+ prompt,
77
+ return_tensors="pt",
78
+ padding=True,
79
+ truncation=True,
80
+ max_length=2048
81
+ )
82
+ inputs = {k: v.to(model.device) for k, v in inputs.items()}
83
+
84
+ input_length = inputs['input_ids'].shape[1]
85
+
86
+ with torch.no_grad():
87
+ outputs = model.generate(
88
+ **inputs,
89
+ max_new_tokens=300,
90
+ temperature=0.60,
91
+ do_sample=True,
92
+ top_p=0.94,
93
+ top_k=40,
94
+ min_p=0.05,
95
+ repetition_penalty=1.15,
96
+ no_repeat_ngram_size=3,
97
+ min_length=60,
98
+ pad_token_id=tokenizer.pad_token_id,
99
+ eos_token_id=tokenizer.eos_token_id,
100
+ use_cache=True
101
+ )
102
+
103
+ new_tokens = outputs[0][input_length:]
104
+ raw_response = tokenizer.decode(new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False).strip()
105
+
106
+ # Pulizia minimale - mantieni tutto il contenuto interessante
107
+ clean_response = minimal_clean_response(raw_response)
108
+
109
+ return clean_response
110
+
111
+ def chat_with_memory(model, tokenizer):
112
+ global conversation_turns
113
+ conversation_turns = []
114
+
115
+ print("\n🧠 RESON-LLAMA V4 CHAT CON MEMORIA")
116
+ print("Comandi: 'quit' = esci, 'clear' = cancella memoria")
117
+
118
+ while True:
119
+ try:
120
+ user_input = input(f"\n🧑 Tu: ").strip()
121
+
122
+ if user_input.lower() == 'quit':
123
+ print("👋 Arrivederci!")
124
+ break
125
+
126
+ elif user_input.lower() == 'clear':
127
+ conversation_turns = []
128
+ print("🧠 Memoria cancellata!")
129
+ continue
130
+
131
+ if not user_input:
132
+ continue
133
+
134
+ print("🧠 RESON sta riflettendo...")
135
+
136
+ prompt = format_conversation_prompt(conversation_turns, user_input)
137
+ response = generate_response(model, tokenizer, prompt)
138
+
139
+ print(f"\n🤖 RESON: {response}")
140
+
141
+ conversation_turns.append({
142
+ 'question': user_input,
143
+ 'answer': response
144
+ })
145
+
146
+ if len(conversation_turns) > MAX_MEMORY_TURNS:
147
+ conversation_turns = conversation_turns[-MAX_MEMORY_TURNS:]
148
+
149
+ except KeyboardInterrupt:
150
+ print("\n👋 Chat interrotta!")
151
+ break
152
+ except Exception as e:
153
+ print(f"❌ Errore: {e}")
154
+
155
+ def main():
156
+ print("🧠 RESON-LLAMA V4 CON MEMORIA")
157
+
158
+ model, tokenizer = load_reson_model()
159
+ chat_with_memory(model, tokenizer)
160
+
161
+ if __name__ == "__main__":
162
+ main()