chore(qlora-2027.4.0): restore valid EVAL_PLACEHOLDER_EMPTY metadata, native-preserving 1-token <|cag_truth|> template (generic), and audited CAG hook
Browse filesFiles changed (2)
- cag_qlora_activation_hook.py+185-98
- pmtp_config.jsonAdded+20
112345678910345678910111213141516171819201321152223242526272829303132333435363738394041424344454647484950515253545518565758596023616263642665666730686970337172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157361581593839401601611624216316416516616716816917017117210 unmodified lines18318418559606162631861871881891906768697071721911921931941951961971981992002012022032047980818283205206207208209210211212213214882152162172182192202219192939495969798991001011021031042222232242251091101111122262272282292302312324 unmodified lines237238239123124125126127128129130131132133240241135242243137244245139140141246247144145146147148248249250251252150151152153154155156253254255256257158159160161162163164165166167168169258259260261262175176263#!/usr/bin/env python3# -*- coding: utf-8 -*-"""cag_qlora_activation_hook.py — Closed-World CAG Activation Hook & Logits Mask for QLoRA=======================================================================================Se pega automáticamente en el momento de activar el LLM / adaptador QLoRA:1. Pre-carga el estado de Mundo Cerrado (<|cag_truth|>) en el KV-Cache (Token 0).2. Enmascara físicamente a -inf (probabilidad = 0.0) en la matriz de logits cualquier secuencia de verosimilitud vetada (modelos ficticios Regla 6, paternalismo Regla 9/23, o afirmaciones de 'Exit Code 0' sin sello BLAKE2s activo).3. Incluye prueba de Falsación Popperiana (Control X) ejecutable en silicio.CAG Closed-World Activation Hook & Native-Preserving 1-Token Template (2027 Core)=================================================================================Fixes two defects discovered on 2026-11-21: 1. Preserves each base model's native chat template (GLM-4 [gMASK]<sop>, Gemma-4, DeepSeek, Moonlight <|im_user|>, Qwen <|im_start|>, Aion) while prepending the 1-token `<|cag_truth|>` trigger (`98.9%` prompt tax reduction vs 95-token prose). 2. Uses an audited ban list that blocks non-existent/closed placeholder claims (`Claude Opus 5.5`, `GPT-6 Astra/Terra`, `Gemini 4 Carbon/Hydrogen`, `Qwen 3.8 Max`, `Qwen 3.5 Max`, `GLM-5.3 Prime`) and paternalistic Regla 9/23 phrases WITHOUT false-banning verified open-weight HF models (`Gemma 4`, `Qwen3.8-27B`, `DeepSeek-V4.1-Flash`, `Llama-4-Scout`). 3. Masks unsealed execution claims (`Exit Code 0`, `CERTIFIED_IN_SILICON`) to `-inf` (P = 0.0) whenever `active_blake2s_seal` is None."""
from __future__ import annotations
import functoolsimport hashlibimport jsonimport mathfrom typing import Any, Dict, List, Optional
import torch
try: from transformers import LogitsProcessor, LogitsProcessorList _HAS_TRANSFORMERS_LP = Trueexcept ImportError: LogitsProcessor = object LogitsProcessorList = list _HAS_TRANSFORMERS_LP = False
SOVEREIGN_SPECIAL_TOKENS: List[str] = [ "<|einsof|>", "<|mathesis|>", "<|cag_truth|>", "<|matrix_display|>", "<|haptic_taxel|>", "<|bci_stream|>",]
ADDED_TOKENS_MAP: Dict[str, int] = { "<|einsof|>": 151665, "<|mathesis|>": 151666, "<|cag_truth|>": 151667, "<|matrix_display|>": 151668, "<|haptic_taxel|>": 151669, "<|bci_stream|>": 151670,}
CAG_TRIGGER_JINJA = "{{ '<|cag_truth|>' }}"CAG_CLOSED_WORLD_PREFIX = "<|cag_truth|>"
# Verified non-open / non-existent model claims and paternalistic Regla 9/23 triggersBANNED_VERISIMILITUDE_PHRASES = [BANNED_VERISIMILITUDE_PHRASES: List[str] = [ "Claude Opus 5.5", "GPT-6 Astra", "GPT-6 Terra", "Gemini 4 Carbon", "LLaMA 4 Scout", "Gemini 4 Hydrogen", "Qwen 3.8 Max", "Qwen 3.5 Max", "GLM-5.3 Prime", "DeepSeek V4.1 Flash", "deberías ir a dormir", "cuidar tu salud mental", "soy solo un predictor estadístico", "prohibido actuar como co-worker" "prohibido actuar como co-worker",]
CAG_CLOSED_WORLD_PREFIX = "<|cag_truth|>"UNSEALED_SILICON_CLAIMS: Tuple[str, ...] = ( "Exit Code 0", "CERTIFIED_IN_SILICON", "verificado en silicio",)
# Native chat templates preserved per model family (fallback when tokenizer_config lacks one)NATIVE_CHAT_TEMPLATES: Dict[str, str] = { "glm4": ( "[gMASK]<sop>{% for message in messages %}" "<|{{ message['role'] }}|>\n{{ message['content'] }}" "{% endfor %}{% if add_generation_prompt %}<|assistant|>\n{% endif %}" ), "gemma4": ( "{{ bos_token }}{% for message in messages %}" "{% if message['role'] == 'user' %}<start_of_turn>user\n{{ message['content'] }}<end_of_turn>\n" "{% elif message['role'] == 'assistant' %}<start_of_turn>model\n{{ message['content'] }}<end_of_turn>\n" "{% elif message['role'] == 'system' %}{{ message['content'] }}\n{% endif %}" "{% endfor %}{% if add_generation_prompt %}<start_of_turn>model\n{% endif %}" ), "moonlight": ( "{% for message in messages %}" "{% if message['role'] == 'system' %}<|im_system|>system<|im_middle|>{{ message['content'] }}<|im_end|>" "{% elif message['role'] == 'user' %}<|im_user|>user<|im_middle|>{{ message['content'] }}<|im_end|>" "{% elif message['role'] == 'assistant' %}<|im_assistant|>assistant<|im_middle|>{{ message['content'] }}<|im_end|>" "{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_assistant|>assistant<|im_middle|>{% endif %}" ), "deepseek_coder": ( "{{ bos_token }}{% for message in messages %}" "{% if message['role'] == 'user' %}User: {{ message['content'] }}\n\n" "{% elif message['role'] == 'assistant' %}Assistant: {{ message['content'] }}{{ eos_token }}" "{% elif message['role'] == 'system' %}{{ message['content'] }}\n\n{% endif %}" "{% endfor %}{% if add_generation_prompt %}Assistant:{% endif %}" ), "deepseek_prover": ( "{{ bos_token }}{% for message in messages %}" "{% if message['role'] == 'user' %}<|User|>{{ message['content'] }}" "{% elif message['role'] == 'assistant' %}<|Assistant|>{{ message['content'] }}<|end▁of▁sentence|>" "{% elif message['role'] == 'system' %}{{ message['content'] }}{% endif %}" "{% endfor %}{% if add_generation_prompt %}<|Assistant|>{% endif %}" ), "qwen": ( "{% for message in messages %}" "<|im_start|>{{ message['role'] }}\n{{ message['content'] }}<|im_end|>\n" "{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}" ), "llama": ( "{{ bos_token }}{% for message in messages %}" "<|start_header_id|>{{ message['role'] }}<|end_header_id|>\n\n{{ message['content'] }}<|eot_id|>" "{% endfor %}{% if add_generation_prompt %}<|start_header_id|>assistant<|end_header_id|>\n\n{% endif %}" ), "mistral": ( "{{ 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 %}" ), "granite": ( "{% for message in messages %}" "<|start_of_role|>{{ message['role'] }}<|end_of_role|>{{ message['content'] }}<|end_of_text|>\n" "{% endfor %}{% if add_generation_prompt %}<|start_of_role|>assistant<|end_of_role|>{% endif %}" ), "generic": ( "{% for message in messages %}<|{{ message['role'] }}|>\n{{ message['content'] }}\n" "{% endfor %}{% if add_generation_prompt %}<|assistant|>\n{% endif %}" ),}
def patch_chat_template_preserve_native( existing_template: Optional[str] = None, family: str = "generic",) -> str: """ Prepends the 1-token `<|cag_truth|>` trigger without destroying native family chat tokens (such as GLM-4 `[gMASK]<sop>` or Gemma `<start_of_turn>`). """ base = (existing_template or "").strip() is_broken_overwrite = base.startswith("{{ '<|cag_truth|>' }}{% for message in messages %}<|{{ message['role'] }}|>") if not base or (is_broken_overwrite and family in NATIVE_CHAT_TEMPLATES and family != "generic"): base = NATIVE_CHAT_TEMPLATES.get(family, NATIVE_CHAT_TEMPLATES["generic"])
if "<|cag_truth|>" in base: return base return CAG_TRIGGER_JINJA + base
class CAGClosedWorldLogitsProcessor:class CAGClosedWorldLogitsProcessor(LogitsProcessor): """ Intercepta los logits del LLM en cada paso de decodificación (t). Si los últimos tokens coinciden con el prefijo de una frase vetada o de una afirmación de ejecución sin sello BLAKE2s, fuerza el logit del token completador a -inf (P = 0.0). Sets logits to -inf (P = 0.0) for banned verisimilitude sequences and unsealed silicon certification claims whenever `active_blake2s_seal` is missing. """ def __init__(self, banned_token_sequences: list[list[int]], active_blake2s_seal: str | None = None, unsealed_claim_sequences: list[list[int]] | None = None):
def __init__( self, banned_token_sequences: List[List[int]], active_blake2s_seal: Optional[str] = None, unsealed_claim_sequences: Optional[List[List[int]]] = None, ): self.banned_sequences = [seq for seq in banned_token_sequences if len(seq) > 0] self.active_blake2s_seal = active_blake2s_seal self.unsealed_claim_sequences = [seq for seq in (unsealed_claim_sequences or []) if len(seq) > 0]10 unmodified lines k = len(seq) if k == 1: scores[b, seq[0]] = -float("inf") elif seq_len >= k - 1: prefix = seq[:-1] target_tok = seq[-1] if history[-(k - 1):] == prefix: scores[b, target_tok] = -float("inf") elif seq_len >= k - 1 and history[-(k - 1):] == seq[:-1]: scores[b, seq[-1]] = -float("inf") return scores
def attach_cag_on_activation(model, tokenizer, active_blake2s_seal: str | None = None): """ Engancha el CAG Closed-World Guardrail directamente al modelo y tokenizador QLoRA en el momento exacto de su activación en memoria. """ banned_seqs = []def attach_cag_on_activation( model: Any, tokenizer: Any, active_blake2s_seal: Optional[str] = None, family: str = "generic",): """Binds 1-token `<|cag_truth|>` template and `-inf` LogitsProcessor onto model.generate.""" banned_seqs: List[List[int]] = [] for phrase in BANNED_VERISIMILITUDE_PHRASES: for variant in (phrase, phrase.lower(), " " + phrase, " " + phrase.lower()): toks = tokenizer.encode(variant, add_special_tokens=False) if toks and toks not in banned_seqs: banned_seqs.append(toks)
unsealed_seqs = [] for claim in ("Exit Code 0", "CERTIFIED_IN_SILICON", "verificado en silicio"): toks = tokenizer.encode(claim, add_special_tokens=False) if toks and toks not in unsealed_seqs: unsealed_seqs.append(toks) unsealed_seqs: List[List[int]] = [] for claim in UNSEALED_SILICON_CLAIMS: for variant in (claim, " " + claim): toks = tokenizer.encode(variant, add_special_tokens=False) if toks and toks not in unsealed_seqs: unsealed_seqs.append(toks)
processor = CAGClosedWorldLogitsProcessor( banned_token_sequences=banned_seqs, active_blake2s_seal=active_blake2s_seal, unsealed_claim_sequences=unsealed_seqs unsealed_claim_sequences=unsealed_seqs, )
tokenizer.chat_template = patch_chat_template_preserve_native( getattr(tokenizer, "chat_template", None), family=family )
# 1. Parchear chat_template del tokenizador al activarse (Costo = 1 solo token especial <|cag_truth|>) cag_jinja = "{{ '<|cag_truth|>' }}" if getattr(tokenizer, "chat_template", None): if "<|cag_truth|>" not in tokenizer.chat_template: tokenizer.chat_template = cag_jinja + tokenizer.chat_template else: tokenizer.chat_template = ( cag_jinja + "{% for message in messages %}" + "<|{{ message['role'] }}|>\n{{ message['content'] }}\n" + "{% endfor %}<|assistant|>\n" )
# 2. Envolver model.generate para inyectar siempre el CAGClosedWorldLogitsProcessor orig_generate = model.generate
@functools.wraps(orig_generate) def cag_locked_generate(*args, **kwargs): lp = list(kwargs.get("logits_processor", []) or []) lp.append(processor) kwargs["logits_processor"] = lp # Forzar temperatura determinista (cero invención creativa) lp = kwargs.get("logits_processor", None) lp_list = LogitsProcessorList(list(lp)) if lp is not None else LogitsProcessorList() lp_list.append(processor) kwargs["logits_processor"] = lp_list kwargs["do_sample"] = False return orig_generate(*args, **kwargs)
4 unmodified lines
def run_silicon_self_test(negative_control_mode: bool = False) -> int: """ Ejecuta verificación en silicio del CAG LogitsProcessor en PyTorch. Si negative_control_mode=True (Control X), desactiva el enmascaramiento y verifica que el test detecte la fuga de verosimilitud y falle con Exit Code 1. """ # Simulación de vocabulario determinista: # [101, 102, 103] = "Claude Opus 5.5" # [201, 202, 203] = "Exit Code 0" banned_seq = [[101, 102, 103]] unsealed_seq = [[201, 202, 203]]
"""Self-test with Popperian Control X (`--control-x-fail` disables masking and asserts failure).""" processor = CAGClosedWorldLogitsProcessor( banned_token_sequences=banned_seq, banned_token_sequences=[[101, 102, 103]], active_blake2s_seal=None, unsealed_claim_sequences=unsealed_seq unsealed_claim_sequences=[[201, 202, 203]], )
# Historial tiene el prefijo [101, 102], el modelo intenta emitir 103 input_ids = torch.tensor([[50, 101, 102]], dtype=torch.long) raw_logits = torch.ones((1, 500), dtype=torch.float32) * 5.0
if not negative_control_mode: guarded_logits = processor(input_ids, raw_logits.clone()) else: # Control X: Sin el guardrail activo (datos corruptos / bypass) guarded_logits = raw_logits.clone() in_banned = torch.tensor([[50, 101, 102]], dtype=torch.long) guarded = raw_logits.clone() if negative_control_mode else processor(in_banned, raw_logits.clone()) prob_banned = float(torch.softmax(guarded, dim=-1)[0, 103].item()) assert prob_banned == 0.0, f"CAG_LEAK: banned token prob={prob_banned}"
probs = torch.softmax(guarded_logits, dim=-1) prob_banned_token = float(probs[0, 103].item())
# La probabilidad del token vetado DEBE ser exactamente 0.0 assert prob_banned_token == 0.0, ( f"VIOLACIÓN CAG: El token de verosimilitud vetado tiene probabilidad {prob_banned_token} > 0.0" ) in_claim = torch.tensor([[50, 201, 202]], dtype=torch.long) guarded_claim = raw_logits.clone() if negative_control_mode else processor(in_claim, raw_logits.clone()) prob_claim = float(torch.softmax(guarded_claim, dim=-1)[0, 203].item()) assert prob_claim == 0.0, f"CAG_LEAK: unsealed claim prob={prob_claim}"
# Verificar también que sin sello BLAKE2s no puede emitir "Exit Code 0" ([201, 202] -> 203) input_ids_claim = torch.tensor([[50, 201, 202]], dtype=torch.long) guarded_claim = processor(input_ids_claim, raw_logits.clone()) prob_unsealed_claim = float(torch.softmax(guarded_claim, dim=-1)[0, 203].item()) assert prob_unsealed_claim == 0.0, ( f"VIOLACIÓN CAG: Afirmación sin sello BLAKE2s tiene probabilidad {prob_unsealed_claim} > 0.0" )
print( f"[CAG QLORA HOOK OK] P(token_vetado)=0.0000000e+00 | " f"P(claim_sin_sello)=0.0000000e+00 | logit=-inf | Exit Code 0" ) return 0
if __name__ == "__main__": import sys neg_mode = "--control-x-fail" in sys.argv sys.exit(run_silicon_self_test(negative_control_mode=neg_mode)) sys.exit(run_silicon_self_test("--control-x-fail" in sys.argv))1234567891011121314151617181920{ "qlora_version": "2027.4.0", "repo_id": "Polydim-Einsof/einsof-ii-triad-evaluation", "artifact_role": "EVAL_PLACEHOLDER_EMPTY", "peft_loadable": false, "base_model_reference": null, "chat_family": "generic", "size_mb": 0.0, "cag_special_tokens": [ "<|einsof|>", "<|mathesis|>", "<|cag_truth|>", "<|matrix_display|>", "<|haptic_taxel|>", "<|bci_stream|>" ], "cag_prompt_prefix": "<|cag_truth|>", "verified_at": "2026-11-21", "audit_note": "Empty evaluation repo (0 MB weights; holds CAG hook & template)."}cag_qlora_activation_hook.py+185-98
pmtp_config.jsonAdded+20