MishaGGG commited on
Commit
5a07453
·
verified ·
1 Parent(s): ae1dca2

Upload 10 files

Browse files
added_tokens.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "</system>": 50260,
3
+ "<system>": 50259,
4
+ "<|assistant|>": 50258,
5
+ "<|user|>": 50257
6
+ }
config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "Dront-200m",
3
+ "activation_function": "gelu_new",
4
+ "architectures": [
5
+ "GPT2LMHeadModel"
6
+ ],
7
+ "attn_pdrop": 0.1,
8
+ "bos_token_id": 50256,
9
+ "embd_pdrop": 0.1,
10
+ "eos_token_id": 50256,
11
+ "initializer_range": 0.02,
12
+ "layer_norm_epsilon": 1e-05,
13
+ "model_type": "gpt2",
14
+ "n_ctx": 1024,
15
+ "n_embd": 768,
16
+ "n_head": 12,
17
+ "n_inner": null,
18
+ "n_layer": 23,
19
+ "n_positions": 1024,
20
+ "reorder_and_upcast_attn": false,
21
+ "resid_pdrop": 0.1,
22
+ "scale_attn_by_inverse_layer_idx": false,
23
+ "scale_attn_weights": true,
24
+ "summary_activation": null,
25
+ "summary_first_dropout": 0.1,
26
+ "summary_proj_to_labels": true,
27
+ "summary_type": "cls_index",
28
+ "summary_use_proj": true,
29
+ "torch_dtype": "float32",
30
+ "transformers_version": "4.46.3",
31
+ "use_cache": false,
32
+ "vocab_size": 50261
33
+ }
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 50256,
4
+ "eos_token_id": 50256,
5
+ "transformers_version": "4.46.3",
6
+ "use_cache": false
7
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:74b40943cf702e8e8a9021850e82ad2fce6c4f2feccbd02e66ada732384208b6
3
+ size 809666424
special_tokens_map.json ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ {
4
+ "content": "<|user|>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false
9
+ },
10
+ {
11
+ "content": "<|assistant|>",
12
+ "lstrip": false,
13
+ "normalized": false,
14
+ "rstrip": false,
15
+ "single_word": false
16
+ },
17
+ {
18
+ "content": "<system>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ {
25
+ "content": "</system>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ {
32
+ "content": "<|endoftext|>",
33
+ "lstrip": false,
34
+ "normalized": false,
35
+ "rstrip": false,
36
+ "single_word": false
37
+ }
38
+ ],
39
+ "bos_token": {
40
+ "content": "<|endoftext|>",
41
+ "lstrip": false,
42
+ "normalized": false,
43
+ "rstrip": false,
44
+ "single_word": false
45
+ },
46
+ "eos_token": {
47
+ "content": "<|endoftext|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": false,
51
+ "single_word": false
52
+ },
53
+ "pad_token": {
54
+ "content": "<|endoftext|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false
59
+ },
60
+ "unk_token": {
61
+ "content": "<|endoftext|>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false
66
+ }
67
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "50256": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "50257": {
13
+ "content": "<|user|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "50258": {
21
+ "content": "<|assistant|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "50259": {
29
+ "content": "<system>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "50260": {
37
+ "content": "</system>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ }
44
+ },
45
+ "additional_special_tokens": [
46
+ "<|user|>",
47
+ "<|assistant|>",
48
+ "<system>",
49
+ "</system>",
50
+ "<|endoftext|>"
51
+ ],
52
+ "bos_token": "<|endoftext|>",
53
+ "clean_up_tokenization_spaces": false,
54
+ "eos_token": "<|endoftext|>",
55
+ "model_max_length": 1024,
56
+ "pad_token": "<|endoftext|>",
57
+ "tokenizer_class": "GPT2Tokenizer",
58
+ "unk_token": "<|endoftext|>"
59
+ }
use.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer, StoppingCriteria, StoppingCriteriaList
3
+
4
+ # Settings
5
+ MODEL_PATH = "DrontChat-200m" # path to local model
6
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
7
+ TEMPERATURE = 0.3
8
+ MAX_NEW_TOKENS = 256
9
+ TOP_P = 0.90
10
+ TOP_K = 50
11
+
12
+
13
+ class StopOnTokens(StoppingCriteria):
14
+ """Class to stop generation when encountering stop tokens"""
15
+
16
+ def __init__(self, stop_token_ids):
17
+ self.stop_token_ids = set(stop_token_ids)
18
+
19
+ def __call__(self, input_ids, scores, **kwargs):
20
+ # Check the last generated token
21
+ if input_ids.shape[-1] > 0:
22
+ last_token = input_ids[0, -1].item()
23
+ if last_token in self.stop_token_ids:
24
+ return True
25
+ return False
26
+
27
+
28
+ class LocalChatBot:
29
+ def __init__(self, model_path):
30
+ print(f"Loading model from {model_path}...")
31
+
32
+ # Load tokenizer and model
33
+ self.tokenizer = AutoTokenizer.from_pretrained(
34
+ model_path,
35
+ trust_remote_code=True,
36
+ padding_side="left"
37
+ )
38
+
39
+ # Define special tokens
40
+ special_tokens = {
41
+ "pad_token": "<|endoftext|>",
42
+ "eos_token": "<|endoftext|>",
43
+ "sep_token": "<|endoftext|>",
44
+ "additional_special_tokens": ["<|user|>", "<|assistant|>", "<system>", "</system>"]
45
+ }
46
+
47
+ # Add special tokens
48
+ self.tokenizer.add_special_tokens(special_tokens)
49
+
50
+ self.model = AutoModelForCausalLM.from_pretrained(
51
+ model_path,
52
+ torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
53
+ device_map="auto",
54
+ trust_remote_code=True,
55
+ low_cpu_mem_usage=True
56
+ )
57
+
58
+ # If new tokens were added, resize embeddings
59
+ if len(self.tokenizer) > self.model.config.vocab_size:
60
+ self.model.resize_token_embeddings(len(self.tokenizer))
61
+
62
+ self.model.eval()
63
+
64
+ # Get stop token IDs
65
+ self.stop_token_ids = self._get_stop_token_ids()
66
+
67
+ if DEVICE == "cuda":
68
+ print(f"Model loaded on GPU: {torch.cuda.get_device_name()}")
69
+ else:
70
+ print("WARNING: CUDA not available, using CPU!")
71
+
72
+ def _get_stop_token_ids(self):
73
+ """Get IDs of all stop tokens"""
74
+ stop_tokens = [
75
+ "<|endoftext|>",
76
+ "<|user|>", # Stop if model starts generating for user
77
+ "<|assistant|>", # Stop if model generates new response
78
+ "<system>", # Stop if model starts new system prompt
79
+ ]
80
+
81
+ stop_ids = []
82
+ for token in stop_tokens:
83
+ token_id = self.tokenizer.convert_tokens_to_ids(token)
84
+ if token_id is not None and token_id != -1:
85
+ stop_ids.append(token_id)
86
+ print(f"Stop token '{token}' -> ID: {token_id}")
87
+ else:
88
+ print(f"Warning: token '{token}' not found in tokenizer")
89
+
90
+ return stop_ids
91
+
92
+ def format_prompt(self, system_message, user_input, history=[]):
93
+ """Format prompt with conversation history"""
94
+ prompt = f"<system>{system_message}</system>"
95
+
96
+ # Add conversation history
97
+ for user_msg, assistant_msg in history:
98
+ prompt += f"<|user|>{user_msg}<|endoftext|>"
99
+ prompt += f"<|assistant|>{assistant_msg}<|endoftext|>"
100
+
101
+ # Add current message
102
+ prompt += f"<|user|>{user_input}<|endoftext|>"
103
+ prompt += "<|assistant|>"
104
+
105
+ return prompt
106
+
107
+ def generate_response(self, prompt):
108
+ """Generate model response with proper stopping"""
109
+ inputs = self.tokenizer.encode(
110
+ prompt,
111
+ return_tensors="pt",
112
+ truncation=True,
113
+ max_length=2048,
114
+ add_special_tokens=False
115
+ ).to(DEVICE)
116
+
117
+ # Create stopping criteria
118
+ stopping_criteria = StoppingCriteriaList([StopOnTokens(self.stop_token_ids)])
119
+
120
+ with torch.no_grad():
121
+ outputs = self.model.generate(
122
+ inputs,
123
+ max_new_tokens=MAX_NEW_TOKENS,
124
+ temperature=TEMPERATURE,
125
+ do_sample=True if TEMPERATURE > 0 else False,
126
+ top_p=TOP_P,
127
+ top_k=TOP_K,
128
+ pad_token_id=self.tokenizer.pad_token_id,
129
+ eos_token_id=self.tokenizer.eos_token_id,
130
+ repetition_penalty=1.1,
131
+ num_return_sequences=1,
132
+ stopping_criteria=stopping_criteria, # Add stopping criteria
133
+ )
134
+
135
+ # Decode only new tokens
136
+ response = self.tokenizer.decode(
137
+ outputs[0][inputs.shape[1]:],
138
+ skip_special_tokens=True
139
+ ).strip()
140
+
141
+ # Additional cleanup from possible markers
142
+ response = self._clean_response(response)
143
+
144
+ return response
145
+
146
+ def _clean_response(self, response):
147
+ """Clean response from service tokens"""
148
+ # List of markers for cleanup
149
+ markers = [
150
+ "<|endoftext|>",
151
+ "<|user|>",
152
+ "<|assistant|>",
153
+ "<system>",
154
+ "</system>"
155
+ ]
156
+
157
+ for marker in markers:
158
+ if marker in response:
159
+ response = response.split(marker)[0].strip()
160
+
161
+ return response
162
+
163
+ def chat(self):
164
+ """Interactive chat"""
165
+ print("\n" + "=" * 50)
166
+ print("Local chat bot started!")
167
+ print(f"Temperature: {TEMPERATURE}")
168
+ print(f"Device: {DEVICE}")
169
+ print("Commands: 'clear' - clear history, 'exit' - exit")
170
+ print("=" * 50 + "\n")
171
+
172
+ system_message = "You are a AI, you can smol talk, you have name DrontAI."
173
+ history = []
174
+
175
+ while True:
176
+ try:
177
+ user_input = input("You: ").strip()
178
+
179
+ if not user_input:
180
+ continue
181
+
182
+ if user_input.lower() == 'exit':
183
+ print("Goodbye!")
184
+ break
185
+
186
+ if user_input.lower() == 'clear':
187
+ history = []
188
+ print("Conversation history cleared.")
189
+ continue
190
+
191
+ if user_input.lower().startswith('system:'):
192
+ system_message = user_input[7:].strip()
193
+ print(f"System message updated: {system_message}")
194
+ continue
195
+
196
+ # Format prompt
197
+ prompt = self.format_prompt(system_message, user_input, history)
198
+
199
+ # Generate response
200
+ response = self.generate_response(prompt)
201
+
202
+ # Check if response is not empty
203
+ if not response:
204
+ response = "(empty response)"
205
+
206
+ # Save to history
207
+ history.append((user_input, response))
208
+
209
+ # Limit history to last 5 exchanges
210
+ if len(history) > 5:
211
+ history = history[-5:]
212
+
213
+ print(f"Bot: {response}\n")
214
+
215
+ except KeyboardInterrupt:
216
+ print("\nInterrupted by user.")
217
+ break
218
+ except Exception as e:
219
+ print(f"Error: {e}")
220
+ continue
221
+
222
+
223
+ def main():
224
+ """Main function"""
225
+ try:
226
+ # Check CUDA availability
227
+ if torch.cuda.is_available():
228
+ print(f"CUDA available: {torch.cuda.get_device_name(0)}")
229
+ print(f"GPU Memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB")
230
+
231
+ # Clear CUDA cache
232
+ torch.cuda.empty_cache()
233
+ else:
234
+ print("CUDA not available. Will use CPU (slow).")
235
+
236
+ # Create and run bot
237
+ bot = LocalChatBot(MODEL_PATH)
238
+ bot.chat()
239
+
240
+ except Exception as e:
241
+ print(f"Critical error: {e}")
242
+ import traceback
243
+ traceback.print_exc()
244
+
245
+
246
+ if __name__ == "__main__":
247
+ main()
vocab.json ADDED
The diff for this file is too large to render. See raw diff