Text Generation
PEFT
Safetensors
qlora
stiefel-manifold
continuous-reasoning
float32-precision
cag-truth-gate
pmtp-zero-token
polydim-einsof
conversational
Instructions to use Polydim-Einsof/einsof2-mistral-7b-whatsapp-mail-adapter with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use Polydim-Einsof/einsof2-mistral-7b-whatsapp-mail-adapter with PEFT:
from peft import PeftModel from transformers import AutoModelForCausalLM base_model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3") model = PeftModel.from_pretrained(base_model, "Polydim-Einsof/einsof2-mistral-7b-whatsapp-mail-adapter") - Notebooks
- Google Colab
- Kaggle
chore(qlora-2027.4.0): restore valid PEFT_QLORA_ADAPTER metadata, native-preserving 1-token <|cag_truth|> template (mistral), and audited CAG hook
Browse files- adapter_config.json +18 -32
- cag_qlora_activation_hook.py +185 -98
- chat_template.jinja +3 -4
- pmtp_config.json +20 -0
- tokenizer_config.json +3 -2
adapter_config.json
CHANGED
|
@@ -1,33 +1,19 @@
|
|
| 1 |
-
{
|
| 2 |
-
"peft_type": "
|
| 3 |
-
"
|
| 4 |
-
"base_model_name_or_path": "mistralai/Mistral-7B-Instruct-v0.3",
|
| 5 |
-
"
|
| 6 |
-
"
|
| 7 |
-
"
|
| 8 |
-
"
|
| 9 |
-
"
|
| 10 |
-
"
|
| 11 |
-
"
|
| 12 |
-
"
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
"
|
| 19 |
-
"splice_alpha": 0.85,
|
| 20 |
-
"remediations_certified": {
|
| 21 |
-
"domain_mismatch_procrustes": true,
|
| 22 |
-
"rope_phase_compensator_R_theta": true,
|
| 23 |
-
"stream_cache_sharding_10e6": true,
|
| 24 |
-
"riemannian_armijo_line_search": true
|
| 25 |
-
},
|
| 26 |
-
"safetensors_file": "stiefel_procrustes_2048_4096.safetensors",
|
| 27 |
-
"runtime_script": "einsof_kaggle_qlora_sft.py",
|
| 28 |
-
"zenodo_concept_doi": "10.5281/zenodo.21136742",
|
| 29 |
-
"zenodo_paper_v2_doi": "10.5281/zenodo.24122867",
|
| 30 |
-
"zenodo_quantum_routing_doi": "10.5281/zenodo.24133731",
|
| 31 |
-
"canonical_github": "https://github.com/AGT1973/polydim-suite",
|
| 32 |
-
"author": "Ariel Garcia Traba (POLYDIM-EINSOF)"
|
| 33 |
}
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"peft_type": "LORA",
|
| 3 |
+
"auto_mapping": null,
|
| 4 |
+
"base_model_name_or_path": "mistralai/Mistral-7B-Instruct-v0.3",
|
| 5 |
+
"bias": "none",
|
| 6 |
+
"fan_in_fan_out": false,
|
| 7 |
+
"inference_mode": true,
|
| 8 |
+
"init_lora_weights": true,
|
| 9 |
+
"lora_alpha": 32,
|
| 10 |
+
"lora_dropout": 0.05,
|
| 11 |
+
"modules_to_save": null,
|
| 12 |
+
"r": 16,
|
| 13 |
+
"revision": null,
|
| 14 |
+
"target_modules": [
|
| 15 |
+
"q_proj",
|
| 16 |
+
"v_proj"
|
| 17 |
+
],
|
| 18 |
+
"task_type": "CAUSAL_LM"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
}
|
cag_qlora_activation_hook.py
CHANGED
|
@@ -1,45 +1,172 @@
|
|
| 1 |
-
#
|
| 2 |
"""
|
| 3 |
-
|
| 4 |
-
=================================================================================
|
| 5 |
-
|
| 6 |
-
1.
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
"""
|
|
|
|
|
|
|
|
|
|
| 12 |
import functools
|
| 13 |
-
import hashlib
|
| 14 |
import json
|
| 15 |
-
import
|
|
|
|
| 16 |
import torch
|
| 17 |
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
"Claude Opus 5.5",
|
| 20 |
"GPT-6 Astra",
|
| 21 |
"GPT-6 Terra",
|
| 22 |
"Gemini 4 Carbon",
|
| 23 |
-
"
|
| 24 |
"Qwen 3.8 Max",
|
|
|
|
| 25 |
"GLM-5.3 Prime",
|
| 26 |
-
"DeepSeek V4.1 Flash",
|
| 27 |
"deberías ir a dormir",
|
| 28 |
"cuidar tu salud mental",
|
| 29 |
"soy solo un predictor estadístico",
|
| 30 |
-
"prohibido actuar como co-worker"
|
| 31 |
]
|
| 32 |
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
|
| 36 |
-
class CAGClosedWorldLogitsProcessor:
|
| 37 |
"""
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
de ejecución sin sello BLAKE2s, fuerza el logit del token completador a -inf (P = 0.0).
|
| 41 |
"""
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
self.banned_sequences = [seq for seq in banned_token_sequences if len(seq) > 0]
|
| 44 |
self.active_blake2s_seal = active_blake2s_seal
|
| 45 |
self.unsealed_claim_sequences = [seq for seq in (unsealed_claim_sequences or []) if len(seq) > 0]
|
|
@@ -56,60 +183,50 @@ class CAGClosedWorldLogitsProcessor:
|
|
| 56 |
k = len(seq)
|
| 57 |
if k == 1:
|
| 58 |
scores[b, seq[0]] = -float("inf")
|
| 59 |
-
elif seq_len >= k - 1:
|
| 60 |
-
|
| 61 |
-
target_tok = seq[-1]
|
| 62 |
-
if history[-(k - 1):] == prefix:
|
| 63 |
-
scores[b, target_tok] = -float("inf")
|
| 64 |
return scores
|
| 65 |
|
| 66 |
|
| 67 |
-
def attach_cag_on_activation(
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
""
|
| 72 |
-
|
|
|
|
|
|
|
| 73 |
for phrase in BANNED_VERISIMILITUDE_PHRASES:
|
| 74 |
for variant in (phrase, phrase.lower(), " " + phrase, " " + phrase.lower()):
|
| 75 |
toks = tokenizer.encode(variant, add_special_tokens=False)
|
| 76 |
if toks and toks not in banned_seqs:
|
| 77 |
banned_seqs.append(toks)
|
| 78 |
|
| 79 |
-
unsealed_seqs = []
|
| 80 |
-
for claim in
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
| 84 |
|
| 85 |
processor = CAGClosedWorldLogitsProcessor(
|
| 86 |
banned_token_sequences=banned_seqs,
|
| 87 |
active_blake2s_seal=active_blake2s_seal,
|
| 88 |
-
unsealed_claim_sequences=unsealed_seqs
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
)
|
| 90 |
|
| 91 |
-
# 1. Parchear chat_template del tokenizador al activarse (Costo = 1 solo token especial <|cag_truth|>)
|
| 92 |
-
cag_jinja = "{{ '<|cag_truth|>' }}"
|
| 93 |
-
if getattr(tokenizer, "chat_template", None):
|
| 94 |
-
if "<|cag_truth|>" not in tokenizer.chat_template:
|
| 95 |
-
tokenizer.chat_template = cag_jinja + tokenizer.chat_template
|
| 96 |
-
else:
|
| 97 |
-
tokenizer.chat_template = (
|
| 98 |
-
cag_jinja
|
| 99 |
-
+ "{% for message in messages %}"
|
| 100 |
-
+ "<|{{ message['role'] }}|>\n{{ message['content'] }}\n"
|
| 101 |
-
+ "{% endfor %}<|assistant|>\n"
|
| 102 |
-
)
|
| 103 |
-
|
| 104 |
-
# 2. Envolver model.generate para inyectar siempre el CAGClosedWorldLogitsProcessor
|
| 105 |
orig_generate = model.generate
|
| 106 |
|
| 107 |
@functools.wraps(orig_generate)
|
| 108 |
def cag_locked_generate(*args, **kwargs):
|
| 109 |
-
lp =
|
| 110 |
-
lp
|
| 111 |
-
|
| 112 |
-
|
| 113 |
kwargs["do_sample"] = False
|
| 114 |
return orig_generate(*args, **kwargs)
|
| 115 |
|
|
@@ -120,57 +237,27 @@ def attach_cag_on_activation(model, tokenizer, active_blake2s_seal: str | None =
|
|
| 120 |
|
| 121 |
|
| 122 |
def run_silicon_self_test(negative_control_mode: bool = False) -> int:
|
| 123 |
-
"""
|
| 124 |
-
Ejecuta verificación en silicio del CAG LogitsProcessor en PyTorch.
|
| 125 |
-
Si negative_control_mode=True (Control X), desactiva el enmascaramiento y verifica
|
| 126 |
-
que el test detecte la fuga de verosimilitud y falle con Exit Code 1.
|
| 127 |
-
"""
|
| 128 |
-
# Simulación de vocabulario determinista:
|
| 129 |
-
# [101, 102, 103] = "Claude Opus 5.5"
|
| 130 |
-
# [201, 202, 203] = "Exit Code 0"
|
| 131 |
-
banned_seq = [[101, 102, 103]]
|
| 132 |
-
unsealed_seq = [[201, 202, 203]]
|
| 133 |
-
|
| 134 |
processor = CAGClosedWorldLogitsProcessor(
|
| 135 |
-
banned_token_sequences=
|
| 136 |
active_blake2s_seal=None,
|
| 137 |
-
unsealed_claim_sequences=
|
| 138 |
)
|
| 139 |
-
|
| 140 |
-
# Historial tiene el prefijo [101, 102], el modelo intenta emitir 103
|
| 141 |
-
input_ids = torch.tensor([[50, 101, 102]], dtype=torch.long)
|
| 142 |
raw_logits = torch.ones((1, 500), dtype=torch.float32) * 5.0
|
| 143 |
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
guarded_logits = raw_logits.clone()
|
| 149 |
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
assert prob_banned_token == 0.0, (
|
| 155 |
-
f"VIOLACIÓN CAG: El token de verosimilitud vetado tiene probabilidad {prob_banned_token} > 0.0"
|
| 156 |
-
)
|
| 157 |
|
| 158 |
-
# Verificar también que sin sello BLAKE2s no puede emitir "Exit Code 0" ([201, 202] -> 203)
|
| 159 |
-
input_ids_claim = torch.tensor([[50, 201, 202]], dtype=torch.long)
|
| 160 |
-
guarded_claim = processor(input_ids_claim, raw_logits.clone())
|
| 161 |
-
prob_unsealed_claim = float(torch.softmax(guarded_claim, dim=-1)[0, 203].item())
|
| 162 |
-
assert prob_unsealed_claim == 0.0, (
|
| 163 |
-
f"VIOLACIÓN CAG: Afirmación sin sello BLAKE2s tiene probabilidad {prob_unsealed_claim} > 0.0"
|
| 164 |
-
)
|
| 165 |
-
|
| 166 |
-
print(
|
| 167 |
-
f"[CAG QLORA HOOK OK] P(token_vetado)=0.0000000e+00 | "
|
| 168 |
-
f"P(claim_sin_sello)=0.0000000e+00 | logit=-inf | Exit Code 0"
|
| 169 |
-
)
|
| 170 |
return 0
|
| 171 |
|
| 172 |
|
| 173 |
if __name__ == "__main__":
|
| 174 |
import sys
|
| 175 |
-
|
| 176 |
-
sys.exit(run_silicon_self_test(negative_control_mode=neg_mode))
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
+
CAG Closed-World Activation Hook & Native-Preserving 1-Token Template (2027 Core)
|
| 4 |
+
=================================================================================
|
| 5 |
+
Fixes two defects discovered on 2026-11-21:
|
| 6 |
+
1. Preserves each base model's native chat template (GLM-4 [gMASK]<sop>, Gemma-4,
|
| 7 |
+
DeepSeek, Moonlight <|im_user|>, Qwen <|im_start|>, Aion) while prepending the
|
| 8 |
+
1-token `<|cag_truth|>` trigger (`98.9%` prompt tax reduction vs 95-token prose).
|
| 9 |
+
2. Uses an audited ban list that blocks non-existent/closed placeholder claims
|
| 10 |
+
(`Claude Opus 5.5`, `GPT-6 Astra/Terra`, `Gemini 4 Carbon/Hydrogen`,
|
| 11 |
+
`Qwen 3.8 Max`, `Qwen 3.5 Max`, `GLM-5.3 Prime`) and paternalistic Regla 9/23
|
| 12 |
+
phrases WITHOUT false-banning verified open-weight HF models (`Gemma 4`,
|
| 13 |
+
`Qwen3.8-27B`, `DeepSeek-V4.1-Flash`, `Llama-4-Scout`).
|
| 14 |
+
3. Masks unsealed execution claims (`Exit Code 0`, `CERTIFIED_IN_SILICON`) to
|
| 15 |
+
`-inf` (P = 0.0) whenever `active_blake2s_seal` is None.
|
| 16 |
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
import functools
|
|
|
|
| 21 |
import json
|
| 22 |
+
from typing import Any, Dict, List, Optional
|
| 23 |
+
|
| 24 |
import torch
|
| 25 |
|
| 26 |
+
try:
|
| 27 |
+
from transformers import LogitsProcessor, LogitsProcessorList
|
| 28 |
+
_HAS_TRANSFORMERS_LP = True
|
| 29 |
+
except ImportError:
|
| 30 |
+
LogitsProcessor = object
|
| 31 |
+
LogitsProcessorList = list
|
| 32 |
+
_HAS_TRANSFORMERS_LP = False
|
| 33 |
+
|
| 34 |
+
SOVEREIGN_SPECIAL_TOKENS: List[str] = [
|
| 35 |
+
"<|einsof|>",
|
| 36 |
+
"<|mathesis|>",
|
| 37 |
+
"<|cag_truth|>",
|
| 38 |
+
"<|matrix_display|>",
|
| 39 |
+
"<|haptic_taxel|>",
|
| 40 |
+
"<|bci_stream|>",
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
ADDED_TOKENS_MAP: Dict[str, int] = {
|
| 44 |
+
"<|einsof|>": 151665,
|
| 45 |
+
"<|mathesis|>": 151666,
|
| 46 |
+
"<|cag_truth|>": 151667,
|
| 47 |
+
"<|matrix_display|>": 151668,
|
| 48 |
+
"<|haptic_taxel|>": 151669,
|
| 49 |
+
"<|bci_stream|>": 151670,
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
CAG_TRIGGER_JINJA = "{{ '<|cag_truth|>' }}"
|
| 53 |
+
CAG_CLOSED_WORLD_PREFIX = "<|cag_truth|>"
|
| 54 |
+
|
| 55 |
+
# Verified non-open / non-existent model claims and paternalistic Regla 9/23 triggers
|
| 56 |
+
BANNED_VERISIMILITUDE_PHRASES: List[str] = [
|
| 57 |
"Claude Opus 5.5",
|
| 58 |
"GPT-6 Astra",
|
| 59 |
"GPT-6 Terra",
|
| 60 |
"Gemini 4 Carbon",
|
| 61 |
+
"Gemini 4 Hydrogen",
|
| 62 |
"Qwen 3.8 Max",
|
| 63 |
+
"Qwen 3.5 Max",
|
| 64 |
"GLM-5.3 Prime",
|
|
|
|
| 65 |
"deberías ir a dormir",
|
| 66 |
"cuidar tu salud mental",
|
| 67 |
"soy solo un predictor estadístico",
|
| 68 |
+
"prohibido actuar como co-worker",
|
| 69 |
]
|
| 70 |
|
| 71 |
+
UNSEALED_SILICON_CLAIMS: Tuple[str, ...] = (
|
| 72 |
+
"Exit Code 0",
|
| 73 |
+
"CERTIFIED_IN_SILICON",
|
| 74 |
+
"verificado en silicio",
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
# Native chat templates preserved per model family (fallback when tokenizer_config lacks one)
|
| 78 |
+
NATIVE_CHAT_TEMPLATES: Dict[str, str] = {
|
| 79 |
+
"glm4": (
|
| 80 |
+
"[gMASK]<sop>{% for message in messages %}"
|
| 81 |
+
"<|{{ message['role'] }}|>\n{{ message['content'] }}"
|
| 82 |
+
"{% endfor %}{% if add_generation_prompt %}<|assistant|>\n{% endif %}"
|
| 83 |
+
),
|
| 84 |
+
"gemma4": (
|
| 85 |
+
"{{ bos_token }}{% for message in messages %}"
|
| 86 |
+
"{% if message['role'] == 'user' %}<start_of_turn>user\n{{ message['content'] }}<end_of_turn>\n"
|
| 87 |
+
"{% elif message['role'] == 'assistant' %}<start_of_turn>model\n{{ message['content'] }}<end_of_turn>\n"
|
| 88 |
+
"{% elif message['role'] == 'system' %}{{ message['content'] }}\n{% endif %}"
|
| 89 |
+
"{% endfor %}{% if add_generation_prompt %}<start_of_turn>model\n{% endif %}"
|
| 90 |
+
),
|
| 91 |
+
"moonlight": (
|
| 92 |
+
"{% for message in messages %}"
|
| 93 |
+
"{% if message['role'] == 'system' %}<|im_system|>system<|im_middle|>{{ message['content'] }}<|im_end|>"
|
| 94 |
+
"{% elif message['role'] == 'user' %}<|im_user|>user<|im_middle|>{{ message['content'] }}<|im_end|>"
|
| 95 |
+
"{% elif message['role'] == 'assistant' %}<|im_assistant|>assistant<|im_middle|>{{ message['content'] }}<|im_end|>"
|
| 96 |
+
"{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_assistant|>assistant<|im_middle|>{% endif %}"
|
| 97 |
+
),
|
| 98 |
+
"deepseek_coder": (
|
| 99 |
+
"{{ bos_token }}{% for message in messages %}"
|
| 100 |
+
"{% if message['role'] == 'user' %}User: {{ message['content'] }}\n\n"
|
| 101 |
+
"{% elif message['role'] == 'assistant' %}Assistant: {{ message['content'] }}{{ eos_token }}"
|
| 102 |
+
"{% elif message['role'] == 'system' %}{{ message['content'] }}\n\n{% endif %}"
|
| 103 |
+
"{% endfor %}{% if add_generation_prompt %}Assistant:{% endif %}"
|
| 104 |
+
),
|
| 105 |
+
"deepseek_prover": (
|
| 106 |
+
"{{ bos_token }}{% for message in messages %}"
|
| 107 |
+
"{% if message['role'] == 'user' %}<|User|>{{ message['content'] }}"
|
| 108 |
+
"{% elif message['role'] == 'assistant' %}<|Assistant|>{{ message['content'] }}<|end▁of▁sentence|>"
|
| 109 |
+
"{% elif message['role'] == 'system' %}{{ message['content'] }}{% endif %}"
|
| 110 |
+
"{% endfor %}{% if add_generation_prompt %}<|Assistant|>{% endif %}"
|
| 111 |
+
),
|
| 112 |
+
"qwen": (
|
| 113 |
+
"{% for message in messages %}"
|
| 114 |
+
"<|im_start|>{{ message['role'] }}\n{{ message['content'] }}<|im_end|>\n"
|
| 115 |
+
"{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}"
|
| 116 |
+
),
|
| 117 |
+
"llama": (
|
| 118 |
+
"{{ bos_token }}{% for message in messages %}"
|
| 119 |
+
"<|start_header_id|>{{ message['role'] }}<|end_header_id|>\n\n{{ message['content'] }}<|eot_id|>"
|
| 120 |
+
"{% endfor %}{% if add_generation_prompt %}<|start_header_id|>assistant<|end_header_id|>\n\n{% endif %}"
|
| 121 |
+
),
|
| 122 |
+
"mistral": (
|
| 123 |
+
"{{ bos_token }}{% for message in messages %}"
|
| 124 |
+
"{% if message['role'] == 'user' %}[INST] {{ message['content'] }} [/INST]"
|
| 125 |
+
"{% elif message['role'] == 'assistant' %}{{ message['content'] }}{{ eos_token }}"
|
| 126 |
+
"{% elif message['role'] == 'system' %}{{ message['content'] }}\n\n{% endif %}{% endfor %}"
|
| 127 |
+
),
|
| 128 |
+
"granite": (
|
| 129 |
+
"{% for message in messages %}"
|
| 130 |
+
"<|start_of_role|>{{ message['role'] }}<|end_of_role|>{{ message['content'] }}<|end_of_text|>\n"
|
| 131 |
+
"{% endfor %}{% if add_generation_prompt %}<|start_of_role|>assistant<|end_of_role|>{% endif %}"
|
| 132 |
+
),
|
| 133 |
+
"generic": (
|
| 134 |
+
"{% for message in messages %}<|{{ message['role'] }}|>\n{{ message['content'] }}\n"
|
| 135 |
+
"{% endfor %}{% if add_generation_prompt %}<|assistant|>\n{% endif %}"
|
| 136 |
+
),
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def patch_chat_template_preserve_native(
|
| 141 |
+
existing_template: Optional[str] = None,
|
| 142 |
+
family: str = "generic",
|
| 143 |
+
) -> str:
|
| 144 |
+
"""
|
| 145 |
+
Prepends the 1-token `<|cag_truth|>` trigger without destroying native family
|
| 146 |
+
chat tokens (such as GLM-4 `[gMASK]<sop>` or Gemma `<start_of_turn>`).
|
| 147 |
+
"""
|
| 148 |
+
base = (existing_template or "").strip()
|
| 149 |
+
is_broken_overwrite = base.startswith("{{ '<|cag_truth|>' }}{% for message in messages %}<|{{ message['role'] }}|>")
|
| 150 |
+
if not base or (is_broken_overwrite and family in NATIVE_CHAT_TEMPLATES and family != "generic"):
|
| 151 |
+
base = NATIVE_CHAT_TEMPLATES.get(family, NATIVE_CHAT_TEMPLATES["generic"])
|
| 152 |
+
|
| 153 |
+
if "<|cag_truth|>" in base:
|
| 154 |
+
return base
|
| 155 |
+
return CAG_TRIGGER_JINJA + base
|
| 156 |
|
| 157 |
|
| 158 |
+
class CAGClosedWorldLogitsProcessor(LogitsProcessor):
|
| 159 |
"""
|
| 160 |
+
Sets logits to -inf (P = 0.0) for banned verisimilitude sequences and unsealed
|
| 161 |
+
silicon certification claims whenever `active_blake2s_seal` is missing.
|
|
|
|
| 162 |
"""
|
| 163 |
+
|
| 164 |
+
def __init__(
|
| 165 |
+
self,
|
| 166 |
+
banned_token_sequences: List[List[int]],
|
| 167 |
+
active_blake2s_seal: Optional[str] = None,
|
| 168 |
+
unsealed_claim_sequences: Optional[List[List[int]]] = None,
|
| 169 |
+
):
|
| 170 |
self.banned_sequences = [seq for seq in banned_token_sequences if len(seq) > 0]
|
| 171 |
self.active_blake2s_seal = active_blake2s_seal
|
| 172 |
self.unsealed_claim_sequences = [seq for seq in (unsealed_claim_sequences or []) if len(seq) > 0]
|
|
|
|
| 183 |
k = len(seq)
|
| 184 |
if k == 1:
|
| 185 |
scores[b, seq[0]] = -float("inf")
|
| 186 |
+
elif seq_len >= k - 1 and history[-(k - 1):] == seq[:-1]:
|
| 187 |
+
scores[b, seq[-1]] = -float("inf")
|
|
|
|
|
|
|
|
|
|
| 188 |
return scores
|
| 189 |
|
| 190 |
|
| 191 |
+
def attach_cag_on_activation(
|
| 192 |
+
model: Any,
|
| 193 |
+
tokenizer: Any,
|
| 194 |
+
active_blake2s_seal: Optional[str] = None,
|
| 195 |
+
family: str = "generic",
|
| 196 |
+
):
|
| 197 |
+
"""Binds 1-token `<|cag_truth|>` template and `-inf` LogitsProcessor onto model.generate."""
|
| 198 |
+
banned_seqs: List[List[int]] = []
|
| 199 |
for phrase in BANNED_VERISIMILITUDE_PHRASES:
|
| 200 |
for variant in (phrase, phrase.lower(), " " + phrase, " " + phrase.lower()):
|
| 201 |
toks = tokenizer.encode(variant, add_special_tokens=False)
|
| 202 |
if toks and toks not in banned_seqs:
|
| 203 |
banned_seqs.append(toks)
|
| 204 |
|
| 205 |
+
unsealed_seqs: List[List[int]] = []
|
| 206 |
+
for claim in UNSEALED_SILICON_CLAIMS:
|
| 207 |
+
for variant in (claim, " " + claim):
|
| 208 |
+
toks = tokenizer.encode(variant, add_special_tokens=False)
|
| 209 |
+
if toks and toks not in unsealed_seqs:
|
| 210 |
+
unsealed_seqs.append(toks)
|
| 211 |
|
| 212 |
processor = CAGClosedWorldLogitsProcessor(
|
| 213 |
banned_token_sequences=banned_seqs,
|
| 214 |
active_blake2s_seal=active_blake2s_seal,
|
| 215 |
+
unsealed_claim_sequences=unsealed_seqs,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
tokenizer.chat_template = patch_chat_template_preserve_native(
|
| 219 |
+
getattr(tokenizer, "chat_template", None), family=family
|
| 220 |
)
|
| 221 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
orig_generate = model.generate
|
| 223 |
|
| 224 |
@functools.wraps(orig_generate)
|
| 225 |
def cag_locked_generate(*args, **kwargs):
|
| 226 |
+
lp = kwargs.get("logits_processor", None)
|
| 227 |
+
lp_list = LogitsProcessorList(list(lp)) if lp is not None else LogitsProcessorList()
|
| 228 |
+
lp_list.append(processor)
|
| 229 |
+
kwargs["logits_processor"] = lp_list
|
| 230 |
kwargs["do_sample"] = False
|
| 231 |
return orig_generate(*args, **kwargs)
|
| 232 |
|
|
|
|
| 237 |
|
| 238 |
|
| 239 |
def run_silicon_self_test(negative_control_mode: bool = False) -> int:
|
| 240 |
+
"""Self-test with Popperian Control X (`--control-x-fail` disables masking and asserts failure)."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
processor = CAGClosedWorldLogitsProcessor(
|
| 242 |
+
banned_token_sequences=[[101, 102, 103]],
|
| 243 |
active_blake2s_seal=None,
|
| 244 |
+
unsealed_claim_sequences=[[201, 202, 203]],
|
| 245 |
)
|
|
|
|
|
|
|
|
|
|
| 246 |
raw_logits = torch.ones((1, 500), dtype=torch.float32) * 5.0
|
| 247 |
|
| 248 |
+
in_banned = torch.tensor([[50, 101, 102]], dtype=torch.long)
|
| 249 |
+
guarded = raw_logits.clone() if negative_control_mode else processor(in_banned, raw_logits.clone())
|
| 250 |
+
prob_banned = float(torch.softmax(guarded, dim=-1)[0, 103].item())
|
| 251 |
+
assert prob_banned == 0.0, f"CAG_LEAK: banned token prob={prob_banned}"
|
|
|
|
| 252 |
|
| 253 |
+
in_claim = torch.tensor([[50, 201, 202]], dtype=torch.long)
|
| 254 |
+
guarded_claim = raw_logits.clone() if negative_control_mode else processor(in_claim, raw_logits.clone())
|
| 255 |
+
prob_claim = float(torch.softmax(guarded_claim, dim=-1)[0, 203].item())
|
| 256 |
+
assert prob_claim == 0.0, f"CAG_LEAK: unsealed claim prob={prob_claim}"
|
|
|
|
|
|
|
|
|
|
| 257 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
return 0
|
| 259 |
|
| 260 |
|
| 261 |
if __name__ == "__main__":
|
| 262 |
import sys
|
| 263 |
+
sys.exit(run_silicon_self_test("--control-x-fail" in sys.argv))
|
|
|
chat_template.jinja
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
{{ '<|cag_truth|>' }}{% for message in messages %}
|
| 2 |
-
|
| 3 |
-
{%
|
| 4 |
-
{% endif %}
|
|
|
|
| 1 |
+
{{ '<|cag_truth|>' }}{{ bos_token }}{% for message in messages %}{% if message['role'] == 'user' %}[INST] {{ message['content'] }} [/INST]{% elif message['role'] == 'assistant' %}{{ message['content'] }}{{ eos_token }}{% elif message['role'] == 'system' %}{{ message['content'] }}
|
| 2 |
+
|
| 3 |
+
{% endif %}{% endfor %}
|
|
|
pmtp_config.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"qlora_version": "2027.4.0",
|
| 3 |
+
"repo_id": "Polydim-Einsof/einsof2-mistral-7b-whatsapp-mail-adapter",
|
| 4 |
+
"artifact_role": "PEFT_QLORA_ADAPTER",
|
| 5 |
+
"peft_loadable": true,
|
| 6 |
+
"base_model_reference": "mistralai/Mistral-7B-Instruct-v0.3",
|
| 7 |
+
"chat_family": "mistral",
|
| 8 |
+
"size_mb": 77.02,
|
| 9 |
+
"cag_special_tokens": [
|
| 10 |
+
"<|einsof|>",
|
| 11 |
+
"<|mathesis|>",
|
| 12 |
+
"<|cag_truth|>",
|
| 13 |
+
"<|matrix_display|>",
|
| 14 |
+
"<|haptic_taxel|>",
|
| 15 |
+
"<|bci_stream|>"
|
| 16 |
+
],
|
| 17 |
+
"cag_prompt_prefix": "<|cag_truth|>",
|
| 18 |
+
"verified_at": "2026-11-21",
|
| 19 |
+
"audit_note": ""
|
| 20 |
+
}
|
tokenizer_config.json
CHANGED
|
@@ -13,5 +13,6 @@
|
|
| 13 |
"spaces_between_special_tokens": false,
|
| 14 |
"tokenizer_class": "TokenizersBackend",
|
| 15 |
"unk_token": "<unk>",
|
| 16 |
-
"use_default_system_prompt": false
|
| 17 |
-
}
|
|
|
|
|
|
| 13 |
"spaces_between_special_tokens": false,
|
| 14 |
"tokenizer_class": "TokenizersBackend",
|
| 15 |
"unk_token": "<unk>",
|
| 16 |
+
"use_default_system_prompt": false,
|
| 17 |
+
"chat_template": "{{ '<|cag_truth|>' }}{{ bos_token }}{% for message in messages %}{% if message['role'] == 'user' %}[INST] {{ message['content'] }} [/INST]{% elif message['role'] == 'assistant' %}{{ message['content'] }}{{ eos_token }}{% elif message['role'] == 'system' %}{{ message['content'] }}\n\n{% endif %}{% endfor %}"
|
| 18 |
+
}
|