DevHunterAI commited on
Commit
242bbe4
·
verified ·
1 Parent(s): c610c1d

Upload hssm_pretrained_chat.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. hssm_pretrained_chat.py +722 -0
hssm_pretrained_chat.py ADDED
@@ -0,0 +1,722 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import sys
4
+ from pathlib import Path
5
+ import re
6
+
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from transformers import AutoTokenizer
10
+
11
+ try:
12
+ from tokenizers import Tokenizer as HFTokenizer
13
+ except ImportError:
14
+ HFTokenizer = None
15
+
16
+ DEFAULT_CHECKPOINT = r"D:\Downloads\hssm_fineweb_edu_final.pt"
17
+ DEFAULT_TOKENIZER = r"D:\Downloads\simple_tokenizer_20k.json"
18
+ RUBINET_HSSM_PATH = r"C:\Users\ASUS\.anaconda"
19
+
20
+ sys.path.append(RUBINET_HSSM_PATH)
21
+ from RubiNet_HSSM import HierarchicalSSM
22
+ from hssm_v2_gpu_pretrain import HSSMV2Config, HSSMV2LM
23
+
24
+ if hasattr(sys.stdout, "reconfigure"):
25
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
26
+ if hasattr(sys.stderr, "reconfigure"):
27
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
28
+
29
+
30
+ class CompatibleTokenizer:
31
+ def __init__(self, tokenizer_path: str):
32
+ path = Path(tokenizer_path)
33
+ with path.open("r", encoding="utf-8") as f:
34
+ data = json.load(f)
35
+
36
+ self.backend = None
37
+ if HFTokenizer is not None:
38
+ try:
39
+ self.backend = HFTokenizer.from_file(str(path))
40
+ except Exception:
41
+ self.backend = None
42
+
43
+ if "model" in data and isinstance(data["model"], dict) and "vocab" in data["model"]:
44
+ vocab = data["model"]["vocab"]
45
+ elif "vocab" in data:
46
+ vocab = data["vocab"]
47
+ else:
48
+ raise ValueError(f"Unsupported tokenizer format: {path}")
49
+
50
+ self.vocab = {str(token): int(idx) for token, idx in vocab.items()}
51
+ self.id_to_token = {idx: token for token, idx in self.vocab.items()}
52
+ self.vocab_size = len(self.vocab)
53
+ self.pad_token_id = self._resolve_token_id(["<PAD>", "[PAD]"], fallback=0)
54
+ self.unk_token_id = self._resolve_token_id(["<UNK>", "[UNK]"], fallback=3)
55
+
56
+ print(f"[TOKENIZER] Loaded vocab tokenizer - Vocab: {self.vocab_size:,}")
57
+
58
+ def _resolve_token_id(self, candidates, fallback: int):
59
+ for token in candidates:
60
+ token_id = self.vocab.get(token)
61
+ if token_id is not None:
62
+ return token_id
63
+ return fallback
64
+
65
+ def encode(self, text, max_length=128):
66
+ if self.backend is not None:
67
+ ids = self.backend.encode(text).ids[:max_length]
68
+ else:
69
+ words = text.split()
70
+ ids = [self.vocab.get(word, self.unk_token_id) for word in words][:max_length]
71
+ if len(ids) < max_length:
72
+ ids += [self.pad_token_id] * (max_length - len(ids))
73
+ return ids
74
+
75
+ def decode(self, ids):
76
+ filtered = [int(i) for i in ids if int(i) != self.pad_token_id]
77
+ if self.backend is not None:
78
+ return self.backend.decode(filtered, skip_special_tokens=False)
79
+ return " ".join(self.id_to_token.get(i, "<UNK>") for i in filtered)
80
+
81
+
82
+ class HFTokenizerAdapter:
83
+ def __init__(self, tokenizer_name: str):
84
+ self.backend = AutoTokenizer.from_pretrained(tokenizer_name, use_fast=True)
85
+ if self.backend.pad_token is None:
86
+ self.backend.pad_token = self.backend.eos_token or self.backend.unk_token
87
+ self.vocab = self.backend.get_vocab()
88
+ self.id_to_token = {idx: token for token, idx in self.vocab.items()}
89
+ self.vocab_size = int(self.backend.vocab_size)
90
+ self.pad_token_id = int(self.backend.pad_token_id)
91
+ self.unk_token_id = int(self.backend.unk_token_id if self.backend.unk_token_id is not None else self.pad_token_id)
92
+
93
+ def encode(self, text, max_length=128):
94
+ ids = self.backend.encode(text, add_special_tokens=False, truncation=True, max_length=max_length)
95
+ if len(ids) < max_length:
96
+ ids += [self.pad_token_id] * (max_length - len(ids))
97
+ return ids
98
+
99
+ def decode(self, ids):
100
+ filtered = [int(i) for i in ids if int(i) != self.pad_token_id]
101
+ return self.backend.decode(filtered, skip_special_tokens=True)
102
+
103
+
104
+ def build_model(tokenizer):
105
+ return HierarchicalSSM(
106
+ vocab_size=tokenizer.vocab_size,
107
+ d_model=512,
108
+ d_state=32,
109
+ num_blocks=6,
110
+ num_experts=8,
111
+ top_k=2,
112
+ chunk_size=4,
113
+ expert_dim=1024,
114
+ )
115
+
116
+
117
+ def build_hssm_v2_model(tokenizer, checkpoint_config: dict):
118
+ config = HSSMV2Config(
119
+ vocab_size=int(checkpoint_config.get("vocab_size", tokenizer.vocab_size)),
120
+ d_model=int(checkpoint_config.get("d_model", 288)),
121
+ n_layers=int(checkpoint_config.get("n_layers", 10)),
122
+ d_ff=int(checkpoint_config.get("d_ff", 512)),
123
+ state_rank=int(checkpoint_config.get("state_rank", 128)),
124
+ chunk_size=int(checkpoint_config.get("chunk_size", 8)),
125
+ dropout=float(checkpoint_config.get("dropout", 0.0)),
126
+ max_seq_len=int(checkpoint_config.get("max_seq_len", 1024)),
127
+ tie_embeddings=bool(checkpoint_config.get("tie_embeddings", True)),
128
+ num_experts=int(checkpoint_config.get("num_experts", 64)),
129
+ experts_per_token=int(checkpoint_config.get("experts_per_token", 1)),
130
+ expert_dim=int(checkpoint_config.get("expert_dim", 2048)),
131
+ moe_every=int(checkpoint_config.get("moe_every", 4)),
132
+ aux_loss_coef=float(checkpoint_config.get("aux_loss_coef", 1e-2)),
133
+ )
134
+ return HSSMV2LM(config)
135
+
136
+
137
+ def _looks_like_hf_tokenizer_reference(tokenizer_path: str) -> bool:
138
+ path = Path(tokenizer_path)
139
+ return not path.exists()
140
+
141
+
142
+ def _load_tokenizer(tokenizer_path: str):
143
+ if _looks_like_hf_tokenizer_reference(tokenizer_path):
144
+ return HFTokenizerAdapter(tokenizer_path)
145
+ return CompatibleTokenizer(tokenizer_path)
146
+
147
+
148
+ def _is_hssm_v2_checkpoint(checkpoint: dict) -> bool:
149
+ config = checkpoint.get("config") if isinstance(checkpoint, dict) else None
150
+ if not isinstance(config, dict):
151
+ return False
152
+ required_keys = {"d_model", "n_layers", "state_rank", "chunk_size"}
153
+ return required_keys.issubset(config.keys())
154
+
155
+
156
+ def load_pretrained(checkpoint_path: str, tokenizer_path: str, device: str):
157
+ checkpoint_file = Path(checkpoint_path)
158
+
159
+ if not checkpoint_file.exists():
160
+ raise FileNotFoundError(f"Checkpoint not found: {checkpoint_file}")
161
+
162
+ if not _looks_like_hf_tokenizer_reference(tokenizer_path):
163
+ tokenizer_file = Path(tokenizer_path)
164
+ if not tokenizer_file.exists():
165
+ raise FileNotFoundError(f"Tokenizer not found: {tokenizer_file}")
166
+
167
+ tokenizer = _load_tokenizer(tokenizer_path)
168
+
169
+ checkpoint = torch.load(str(checkpoint_file), map_location=device, weights_only=False)
170
+ state_dict = checkpoint["model_state_dict"] if "model_state_dict" in checkpoint else checkpoint
171
+ if _is_hssm_v2_checkpoint(checkpoint):
172
+ model = build_hssm_v2_model(tokenizer, checkpoint.get("config", {}))
173
+ else:
174
+ model = build_model(tokenizer)
175
+ missing, unexpected = model.load_state_dict(state_dict, strict=False)
176
+
177
+ model = model.to(device)
178
+ model.eval()
179
+
180
+ print("Loaded HSSM checkpoint")
181
+ print(f" Path: {checkpoint_file}")
182
+ print(f" Missing keys: {len(missing)}")
183
+ print(f" Unexpected keys: {len(unexpected)}")
184
+ if "epoch" in checkpoint:
185
+ print(f" Epoch: {checkpoint['epoch']}")
186
+ if "loss" in checkpoint:
187
+ print(f" Loss: {checkpoint['loss']}")
188
+ print(f" Model type: {'HSSM v2' if _is_hssm_v2_checkpoint(checkpoint) else 'RubiNet HSSM'}")
189
+
190
+ return tokenizer, model
191
+
192
+
193
+ def _model_chunk_size(model) -> int:
194
+ if hasattr(model, "chunk_size"):
195
+ return int(model.chunk_size)
196
+ if hasattr(model, "config") and hasattr(model.config, "chunk_size"):
197
+ return int(model.config.chunk_size)
198
+ return 1
199
+
200
+
201
+ def _next_token_logits(model, input_tensor: torch.Tensor, current_len: int) -> torch.Tensor:
202
+ outputs = model(input_tensor)
203
+ if isinstance(outputs, dict):
204
+ logits = outputs.get("logits")
205
+ if logits is None:
206
+ raise ValueError("Model returned a dict without logits")
207
+ return logits[0, current_len - 1, :].clone()
208
+ chunk_size = _model_chunk_size(model)
209
+ chunk_idx = max((current_len - 1) // chunk_size, 0)
210
+ return outputs[0, chunk_idx, :].clone()
211
+
212
+
213
+ def build_prompt(user_text: str, cot_mode: bool = False) -> str:
214
+ cleaned_user_text = user_text.strip()
215
+ if cot_mode:
216
+ return (
217
+ "system: Reply only in correct English. "
218
+ "Follow English grammar, spelling, punctuation, and sentence structure strictly. "
219
+ "Do not output fragments, corrupted tokens, mixed-language text, or placeholder symbols. "
220
+ "Think step by step briefly and keep the output clean. "
221
+ "Output exactly two lines in this format: "
222
+ "Reasoning: <very short reasoning>. "
223
+ "Answer: <final answer>. "
224
+ "Keep both lines grammatical and concise.\n"
225
+ f"user: {cleaned_user_text}\n"
226
+ "assistant:"
227
+ )
228
+ return (
229
+ "system: Reply only in correct English. "
230
+ "Follow English grammar, spelling, punctuation, and sentence structure strictly. "
231
+ "Use short complete sentences. "
232
+ "Do not output broken words, malformed tokens, mixed-language text, or placeholder symbols.\n"
233
+ f"user: {cleaned_user_text}\n"
234
+ "assistant:"
235
+ )
236
+
237
+
238
+ def safe_print(text: str):
239
+ try:
240
+ print(text)
241
+ except UnicodeEncodeError:
242
+ sanitized = text.encode("utf-8", errors="replace").decode("utf-8", errors="replace")
243
+ print(sanitized)
244
+
245
+
246
+ def _apply_top_p_filter(logits: torch.Tensor, top_p: float) -> torch.Tensor:
247
+ if top_p >= 1.0:
248
+ return logits
249
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
250
+ sorted_probs = F.softmax(sorted_logits, dim=-1)
251
+ cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
252
+ sorted_indices_to_remove = cumulative_probs > top_p
253
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
254
+ sorted_indices_to_remove[..., 0] = False
255
+ indices_to_remove = sorted_indices[sorted_indices_to_remove]
256
+ logits[indices_to_remove] = float("-inf")
257
+ return logits
258
+
259
+
260
+ def _has_repeat_ngram(token_ids, next_token_id: int, ngram_size: int) -> bool:
261
+ if ngram_size <= 1 or len(token_ids) < ngram_size - 1:
262
+ return False
263
+ candidate = token_ids[-(ngram_size - 1):] + [next_token_id]
264
+ for i in range(len(token_ids) - ngram_size + 1):
265
+ if token_ids[i:i + ngram_size] == candidate:
266
+ return True
267
+ return False
268
+
269
+
270
+ def _normalize_word(word: str) -> str:
271
+ return re.sub(r"[^a-z0-9]+", "", word.lower())
272
+
273
+
274
+ def _recent_word_counts(text: str, window: int = 12):
275
+ words = [_normalize_word(part) for part in text.split()]
276
+ words = [word for word in words if word]
277
+ recent = words[-window:]
278
+ counts = {}
279
+ for word in recent:
280
+ counts[word] = counts.get(word, 0) + 1
281
+ return counts
282
+
283
+
284
+ def _violates_word_repeat(decoded_text: str, candidate_piece: str) -> bool:
285
+ candidate_word = _normalize_word(candidate_piece)
286
+ if not candidate_word:
287
+ return False
288
+ counts = _recent_word_counts(decoded_text, window=12)
289
+ return counts.get(candidate_word, 0) >= 2
290
+
291
+
292
+ def _resolve_special_token_ids(tokenizer):
293
+ special_ids = set()
294
+ for token in ["<BOS>", "[BOS]", "<PAD>", "[PAD]", "<SEP>", "[SEP]", "<EOS>", "[EOS]", "<UNK>", "[UNK]", "<CLS>", "[CLS]", "<MASK>", "[MASK]", "<MASK>"]:
295
+ token_id = tokenizer.vocab.get(token)
296
+ if token_id is not None:
297
+ special_ids.add(int(token_id))
298
+ if getattr(tokenizer, "pad_token_id", None) is not None:
299
+ special_ids.add(int(tokenizer.pad_token_id))
300
+ if getattr(tokenizer, "unk_token_id", None) is not None:
301
+ special_ids.add(int(tokenizer.unk_token_id))
302
+ return special_ids
303
+
304
+
305
+ def _contains_special_marker(text: str) -> bool:
306
+ upper_text = text.upper()
307
+ markers = ["<BOS>", "[BOS]", "<PAD>", "[PAD]", "<SEP>", "[SEP]", "<EOS>", "[EOS]", "<UNK>", "[UNK]", "<CLS>", "[CLS]", "<MASK>", "[MASK]"]
308
+ return any(marker in upper_text for marker in markers)
309
+
310
+
311
+ def _looks_like_artifact(text: str) -> bool:
312
+ stripped = text.strip()
313
+ if not stripped:
314
+ return False
315
+ if "##" in stripped:
316
+ return True
317
+ if stripped.startswith("##") or stripped.endswith("##"):
318
+ return True
319
+ if stripped.count("#") >= 1 and len(stripped) <= 4:
320
+ return True
321
+ if "�" in stripped:
322
+ return True
323
+ if any(ch in stripped for ch in ["�", ""]):
324
+ return True
325
+ if re.search(r"(.)\1{3,}", stripped.lower()):
326
+ return True
327
+ if re.fullmatch(r"[A-Za-z]{1,4}\d{2,}", stripped):
328
+ return True
329
+ if re.fullmatch(r"[#\-_=~`|.]+", stripped):
330
+ return True
331
+ return False
332
+
333
+
334
+ def _strip_special_markers(text: str) -> str:
335
+ cleaned = text
336
+ for pattern in [r"<\s*BOS\s*>", r"\[\s*BOS\s*\]", r"<\s*PAD\s*>", r"\[\s*PAD\s*\]", r"<\s*SEP\s*>", r"\[\s*SEP\s*\]", r"<\s*EOS\s*>", r"\[\s*EOS\s*\]", r"<\s*UNK\s*>", r"\[\s*UNK\s*\]", r"<\s*CLS\s*>", r"\[\s*CLS\s*\]", r"<\s*MASK\s*>", r"\[\s*MASK\s*\]"]:
337
+ cleaned = re.sub(pattern, " ", cleaned, flags=re.IGNORECASE)
338
+ cleaned = re.sub(r"#{2,}", " ", cleaned)
339
+ cleaned = re.sub(r"(?<!\w)#(?!\w)", " ", cleaned)
340
+ cleaned = cleaned.replace("�", " ")
341
+ cleaned = re.sub(r"\b([A-Za-z]+)(\s+\1\b){2,}", r"\1", cleaned, flags=re.IGNORECASE)
342
+ cleaned = re.sub(r"\b(\w{1,20})(\w{1,20})\1\b", r"\1", cleaned)
343
+ cleaned = re.sub(r"\s*([,;:.!?])\s*", r"\1 ", cleaned)
344
+ cleaned = re.sub(r"\s+", " ", cleaned)
345
+ return cleaned.strip()
346
+
347
+
348
+ def _cleanup_english_grammar(text: str) -> str:
349
+ cleaned = text.strip()
350
+ if not cleaned:
351
+ return cleaned
352
+
353
+ replacements = {
354
+ " im ": " I'm ",
355
+ " ive ": " I've ",
356
+ " ill ": " I'll ",
357
+ " id ": " I'd ",
358
+ " dont ": " don't ",
359
+ " cant ": " can't ",
360
+ " wont ": " won't ",
361
+ " didnt ": " didn't ",
362
+ " doesnt ": " doesn't ",
363
+ " isnt ": " isn't ",
364
+ " arent ": " aren't ",
365
+ " wasnt ": " wasn't ",
366
+ " werent ": " weren't ",
367
+ " thats ": " that's ",
368
+ " whats ": " what's ",
369
+ " theres ": " there's ",
370
+ " ive ": " I've ",
371
+ }
372
+
373
+ padded = f" {cleaned} "
374
+ for source, target in replacements.items():
375
+ padded = re.sub(re.escape(source), target, padded, flags=re.IGNORECASE)
376
+ cleaned = padded.strip()
377
+
378
+ cleaned = re.sub(r"\bi\b", "I", cleaned)
379
+ cleaned = re.sub(r"\b([A-Za-z]+)(\s+\1\b){1,}", r"\1", cleaned, flags=re.IGNORECASE)
380
+ cleaned = re.sub(r"\s+([,;:.!?])", r"\1", cleaned)
381
+ cleaned = re.sub(r"([,;:.!?])(?!\s|$)", r"\1 ", cleaned)
382
+ cleaned = re.sub(r"\s+", " ", cleaned).strip()
383
+
384
+ if cleaned:
385
+ cleaned = cleaned[0].upper() + cleaned[1:]
386
+
387
+ sentences = re.split(r"(?<=[.!?])\s+", cleaned)
388
+ normalized_sentences = []
389
+ for sentence in sentences:
390
+ sentence = sentence.strip()
391
+ if not sentence:
392
+ continue
393
+ if len(sentence) == 1:
394
+ normalized_sentences.append(sentence.upper())
395
+ else:
396
+ normalized_sentences.append(sentence[0].upper() + sentence[1:])
397
+ cleaned = " ".join(normalized_sentences).strip()
398
+
399
+ if cleaned and cleaned[-1] not in ".!?":
400
+ cleaned += "."
401
+
402
+ return cleaned
403
+
404
+
405
+ def _is_strict_english_output(text: str, cot_mode: bool = False) -> bool:
406
+ cleaned = text.strip()
407
+ if not cleaned:
408
+ return False
409
+ if any(token in cleaned for token in ["[", "]", "{", "}", "|", "<UNK>", "[UNK]", "<PAD>", "[PAD]"]):
410
+ return False
411
+ if re.search(r"[^A-Za-z0-9\s,.;:!?\-\'\"()\n]", cleaned):
412
+ return False
413
+ words = re.findall(r"[A-Za-z']+", cleaned)
414
+ if len(words) < 2:
415
+ return False
416
+ long_weird_words = [word for word in words if len(word) > 18]
417
+ if long_weird_words:
418
+ return False
419
+ if re.search(r"([A-Za-z]{2,})([A-Z][a-z]+)", cleaned):
420
+ return False
421
+ common_markers = {
422
+ "the", "a", "an", "is", "are", "am", "i", "you", "we", "they", "it", "to", "of", "and",
423
+ "that", "this", "can", "will", "do", "not", "yes", "no", "my", "your", "in", "on", "for"
424
+ }
425
+ lowered_words = [word.lower() for word in words]
426
+ if not any(word in common_markers for word in lowered_words):
427
+ return False
428
+ if cot_mode:
429
+ lines = [line.strip() for line in cleaned.splitlines() if line.strip()]
430
+ if len(lines) != 2:
431
+ return False
432
+ if not lines[0].startswith("Reasoning:"):
433
+ return False
434
+ if not lines[1].startswith("Answer:"):
435
+ return False
436
+ sentences = [segment.strip() for segment in re.split(r"(?<=[.!?])\s+", cleaned) if segment.strip()]
437
+ if not sentences:
438
+ return False
439
+ for sentence in sentences:
440
+ if not sentence[0].isupper():
441
+ return False
442
+ if sentence[-1] not in ".!?":
443
+ return False
444
+ return True
445
+
446
+
447
+ def _force_cot_shape(text: str) -> str:
448
+ cleaned = text.strip()
449
+ if not cleaned:
450
+ return cleaned
451
+ lines = [line.strip() for line in cleaned.splitlines() if line.strip()]
452
+ if len(lines) >= 2 and lines[0].startswith("Reasoning:") and lines[1].startswith("Answer:"):
453
+ return f"{lines[0]}\n{lines[1]}"
454
+ parts = re.split(r"(?<=[.!?])\s+", cleaned, maxsplit=1)
455
+ if len(parts) == 2:
456
+ reasoning, answer = parts
457
+ else:
458
+ reasoning, answer = "Reasoning: Briefly considered the request.", f"Answer: {cleaned}"
459
+ return f"{reasoning}\n{answer}"
460
+ reasoning = reasoning if reasoning.startswith("Reasoning:") else f"Reasoning: {reasoning.strip()}"
461
+ answer = answer if answer.startswith("Answer:") else f"Answer: {answer.strip()}"
462
+ return f"{reasoning}\n{answer}"
463
+
464
+
465
+ def _ban_low_quality_candidates(tokenizer, logits: torch.Tensor):
466
+ for token_id in range(logits.size(0)):
467
+ piece = tokenizer.decode([token_id]).strip()
468
+ if not piece:
469
+ continue
470
+ if _contains_special_marker(piece):
471
+ logits[token_id] = float("-inf")
472
+
473
+
474
+ def _select_candidate_id(tokenizer, probs: torch.Tensor, generated, prompt_token_count: int, no_repeat_ngram_size: int):
475
+ candidate_count = min(24, probs.size(0))
476
+ top_probs, top_ids = torch.topk(probs, candidate_count)
477
+ decoded_so_far = tokenizer.decode(generated[prompt_token_count:]).strip()
478
+
479
+ fallback_clean_id = None
480
+ fallback_clean_prob = -1.0
481
+ fallback_any_id = None
482
+ fallback_any_prob = -1.0
483
+ for prob_value, candidate_id_tensor in zip(top_probs.tolist(), top_ids.tolist()):
484
+ candidate_id = int(candidate_id_tensor)
485
+ candidate_piece = tokenizer.decode([candidate_id]).strip()
486
+ if not candidate_piece:
487
+ continue
488
+ if _contains_special_marker(candidate_piece):
489
+ continue
490
+ if fallback_any_id is None or prob_value > fallback_any_prob:
491
+ fallback_any_id = candidate_id
492
+ fallback_any_prob = prob_value
493
+ if _looks_like_artifact(candidate_piece):
494
+ continue
495
+ if _violates_word_repeat(decoded_so_far, candidate_piece):
496
+ continue
497
+ if _has_repeat_ngram(generated, candidate_id, max(no_repeat_ngram_size, 4)):
498
+ continue
499
+ normalized_piece = _normalize_word(candidate_piece)
500
+ if normalized_piece and decoded_so_far:
501
+ recent_words = [_normalize_word(part) for part in decoded_so_far.split()[-8:]]
502
+ recent_words = [word for word in recent_words if word]
503
+ if recent_words.count(normalized_piece) >= 1:
504
+ continue
505
+ if fallback_clean_id is None or prob_value > fallback_clean_prob:
506
+ fallback_clean_id = candidate_id
507
+ fallback_clean_prob = prob_value
508
+
509
+ if fallback_clean_id is not None:
510
+ return fallback_clean_id
511
+ return fallback_any_id
512
+
513
+
514
+ def _generate_fallback_reply(model, tokenizer, prompt_tokens, blocked_special_ids, max_length: int):
515
+ device = next(model.parameters()).device
516
+ generated = list(prompt_tokens)
517
+
518
+ with torch.no_grad():
519
+ for _ in range(min(max_length, 16)):
520
+ current_len = len(generated)
521
+ chunk_size = _model_chunk_size(model)
522
+ pad_len = (chunk_size - current_len % chunk_size) % chunk_size
523
+ padded_input = generated + [tokenizer.pad_token_id] * pad_len
524
+ input_tensor = torch.tensor([padded_input], device=device)
525
+ next_token_logits = _next_token_logits(model, input_tensor, current_len)
526
+
527
+ for special_id in blocked_special_ids:
528
+ if 0 <= special_id < next_token_logits.size(0):
529
+ next_token_logits[special_id] = float("-inf")
530
+
531
+ next_token_id = int(torch.argmax(next_token_logits).item())
532
+ if next_token_id == tokenizer.pad_token_id:
533
+ break
534
+
535
+ next_piece = tokenizer.decode([next_token_id]).strip()
536
+ if not next_piece or _contains_special_marker(next_piece):
537
+ break
538
+
539
+ generated.append(next_token_id)
540
+
541
+ return generated
542
+
543
+
544
+ def generate_reply(
545
+ model,
546
+ tokenizer,
547
+ prompt: str,
548
+ max_length: int,
549
+ temperature: float,
550
+ top_k: int,
551
+ top_p: float,
552
+ repetition_penalty: float,
553
+ no_repeat_ngram_size: int,
554
+ cot_mode: bool = False,
555
+ ):
556
+ model.eval()
557
+ device = next(model.parameters()).device
558
+
559
+ formatted_prompt = build_prompt(prompt, cot_mode=cot_mode)
560
+ prompt_ids = tokenizer.encode(formatted_prompt, max_length=128)
561
+ generated = [tok for tok in prompt_ids if tok != tokenizer.pad_token_id]
562
+ prompt_token_count = len(generated)
563
+ blocked_special_ids = _resolve_special_token_ids(tokenizer)
564
+ bos_token_id = tokenizer.vocab.get("<BOS>")
565
+ if not generated:
566
+ generated = [tokenizer.unk_token_id]
567
+ prompt_token_count = len(generated)
568
+
569
+ with torch.no_grad():
570
+ for _ in range(max_length):
571
+ current_len = len(generated)
572
+ chunk_size = _model_chunk_size(model)
573
+ pad_len = (chunk_size - current_len % chunk_size) % chunk_size
574
+ padded_input = generated + [tokenizer.pad_token_id] * pad_len
575
+ input_tensor = torch.tensor([padded_input], device=device)
576
+
577
+ next_token_logits = _next_token_logits(model, input_tensor, current_len)
578
+
579
+ if temperature > 0:
580
+ next_token_logits = next_token_logits / temperature
581
+
582
+ for special_id in blocked_special_ids:
583
+ if 0 <= special_id < next_token_logits.size(0):
584
+ next_token_logits[special_id] = float("-inf")
585
+
586
+ if bos_token_id is not None and 0 <= int(bos_token_id) < next_token_logits.size(0):
587
+ next_token_logits[int(bos_token_id)] = float("-inf")
588
+
589
+ _ban_low_quality_candidates(tokenizer, next_token_logits)
590
+
591
+ recent_tokens = generated[-48:]
592
+ recent_weights = {}
593
+ for idx, token_id in enumerate(recent_tokens):
594
+ distance_weight = 1.0 + (idx / max(len(recent_tokens), 1))
595
+ recent_weights[token_id] = max(recent_weights.get(token_id, 1.0), distance_weight)
596
+
597
+ for token_id, distance_weight in recent_weights.items():
598
+ if 0 <= token_id < next_token_logits.size(0):
599
+ penalty = repetition_penalty * distance_weight
600
+ if next_token_logits[token_id] > 0:
601
+ next_token_logits[token_id] /= penalty
602
+ else:
603
+ next_token_logits[token_id] *= penalty
604
+
605
+ for token_id in range(next_token_logits.size(0)):
606
+ if _has_repeat_ngram(generated, token_id, no_repeat_ngram_size):
607
+ next_token_logits[token_id] = float("-inf")
608
+
609
+ if top_k > 0 and top_k < next_token_logits.size(0):
610
+ threshold = torch.topk(next_token_logits, top_k)[0][..., -1]
611
+ next_token_logits[next_token_logits < threshold] = float("-inf")
612
+
613
+ next_token_logits = _apply_top_p_filter(next_token_logits, top_p)
614
+ probs = F.softmax(next_token_logits, dim=-1)
615
+
616
+ if torch.isnan(probs).any() or torch.isinf(probs).any() or probs.sum() <= 0:
617
+ break
618
+
619
+ next_token = _select_candidate_id(
620
+ tokenizer,
621
+ probs,
622
+ generated,
623
+ prompt_token_count,
624
+ no_repeat_ngram_size,
625
+ )
626
+
627
+ if next_token is None:
628
+ break
629
+
630
+ if next_token == tokenizer.pad_token_id:
631
+ break
632
+ generated.append(next_token)
633
+
634
+ decoded_output = tokenizer.decode(generated[prompt_token_count:]).strip()
635
+ if len(decoded_output.split()) >= 6:
636
+ tail_words = [_normalize_word(part) for part in decoded_output.split()[-4:]]
637
+ tail_words = [word for word in tail_words if word]
638
+ if len(tail_words) >= 4 and len(set(tail_words)) == 1:
639
+ break
640
+
641
+ output_ids = generated[prompt_token_count:]
642
+ cleaned_output = _strip_special_markers(tokenizer.decode(output_ids).strip())
643
+ if cleaned_output:
644
+ normalized_output = _cleanup_english_grammar(cleaned_output)
645
+ if cot_mode:
646
+ normalized_output = _force_cot_shape(normalized_output)
647
+ return normalized_output
648
+
649
+ fallback_generated = _generate_fallback_reply(
650
+ model,
651
+ tokenizer,
652
+ generated[:prompt_token_count],
653
+ blocked_special_ids,
654
+ max_length,
655
+ )
656
+ fallback_output_ids = fallback_generated[prompt_token_count:]
657
+ fallback_output = _strip_special_markers(tokenizer.decode(fallback_output_ids).strip())
658
+ normalized_fallback_output = _cleanup_english_grammar(fallback_output)
659
+ if cot_mode:
660
+ normalized_fallback_output = _force_cot_shape(normalized_fallback_output)
661
+ return normalized_fallback_output
662
+
663
+
664
+ def main():
665
+ parser = argparse.ArgumentParser(description="Chat/test with pretrained RubiNet HSSM checkpoint")
666
+ parser.add_argument("--checkpoint", default=DEFAULT_CHECKPOINT)
667
+ parser.add_argument("--tokenizer", default=DEFAULT_TOKENIZER)
668
+ parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
669
+ parser.add_argument("--max-length", type=int, default=40)
670
+ parser.add_argument("--temperature", type=float, default=0.0)
671
+ parser.add_argument("--top-k", type=int, default=4)
672
+ parser.add_argument("--top-p", type=float, default=0.65)
673
+ parser.add_argument("--repetition-penalty", type=float, default=1.9)
674
+ parser.add_argument("--no-repeat-ngram-size", type=int, default=6)
675
+ parser.add_argument("--cot-mode", action="store_true")
676
+ parser.add_argument("--no-cot-mode", action="store_false", dest="cot_mode")
677
+ parser.set_defaults(cot_mode=False)
678
+ parser.add_argument("--message", default="")
679
+ args = parser.parse_args()
680
+
681
+ tokenizer, model = load_pretrained(args.checkpoint, args.tokenizer, args.device)
682
+
683
+ if args.message:
684
+ output = generate_reply(
685
+ model,
686
+ tokenizer,
687
+ args.message,
688
+ args.max_length,
689
+ args.temperature,
690
+ args.top_k,
691
+ args.top_p,
692
+ args.repetition_penalty,
693
+ args.no_repeat_ngram_size,
694
+ args.cot_mode,
695
+ )
696
+ safe_print(output)
697
+ return
698
+
699
+ print("Interactive HSSM chat/test. Type 'exit' to quit.")
700
+ while True:
701
+ user_text = input("You: ").strip()
702
+ if not user_text:
703
+ continue
704
+ if user_text.lower() in {"exit", "quit"}:
705
+ break
706
+ output = generate_reply(
707
+ model,
708
+ tokenizer,
709
+ user_text,
710
+ args.max_length,
711
+ args.temperature,
712
+ args.top_k,
713
+ args.top_p,
714
+ args.repetition_penalty,
715
+ args.no_repeat_ngram_size,
716
+ args.cot_mode,
717
+ )
718
+ safe_print(f"HSSM: {output}\n")
719
+
720
+
721
+ if __name__ == "__main__":
722
+ main()