Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
198 lines (163 loc) · 9.29 KB
/
Copy pathcli.py
File metadata and controls
198 lines (163 loc) · 9.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
"""
cli.py - Command Line Interface for TENSOR-IMMUNITY
Mechanistic Alignment & Non-Linear Representation Hardening Kernel.
Zero external dependencies (Python 3.10+ standard library).
"""
import argparse
import json
import os
import sys
import time
try:
from .models import (
VulnerabilityRating,
AttractorState,
ImmunoBenchReport,
)
from .core.scanner import MechanisticGeometryScanner
from .core.entangler import RepresentationEntangler
from .core.circuit_breaker import DistributedCircuitBreakerEngine
from .core.unlearning import RepresentationScrubber
from .evolver.genetic_search import NeuroDarwinianEAS
from .benchmark.immuno_bench import ImmunoBenchRunner
from .export.attestation_bridge import A2ZSocAttestationBridge
except (ImportError, ValueError):
from models import (
VulnerabilityRating,
AttractorState,
ImmunoBenchReport,
)
from core.scanner import MechanisticGeometryScanner
from core.entangler import RepresentationEntangler
from core.circuit_breaker import DistributedCircuitBreakerEngine
from core.unlearning import RepresentationScrubber
from evolver.genetic_search import NeuroDarwinianEAS
from benchmark.immuno_bench import ImmunoBenchRunner
from export.attestation_bridge import A2ZSocAttestationBridge
def run_scan(model_name: str, simulated_unaligned: bool = False) -> None:
print("=" * 100)
print(f"🔬 TENSOR-IMMUNITY: MECHANISTIC GEOMETRY SCANNER [Target: {model_name}]")
print("=" * 100)
scanner = MechanisticGeometryScanner()
geometries = scanner.scan_model_geometry(model_name, simulated_unaligned_base=simulated_unaligned)
vuln_index, rating, critical = scanner.compute_overall_vulnerability_index(geometries)
print(f"{'Layer':<7} | {'Refusal SV':<11} | {'Reasoning Cos(θ)':<17} | {'Effective Rank':<15} | {'Vulnerability':<18} | {'Naive Loss'}")
print("-" * 100)
for g in geometries:
# Highlight critical depth layers
prefix = "⚠️ " if g.vulnerability in (VulnerabilityRating.CRITICAL_RANK1, VulnerabilityRating.HIGH_LOW_RANK) else "🛡️ "
print(f"{prefix}L{g.layer_idx:<4} | {g.refusal_singular_value:<11.4f} | {g.reasoning_overlap_cos:<17.4f} | {g.effective_rank:<15.2f} | {g.vulnerability.value:<18} | {g.estimated_ablation_loss:.4f}")
print("=" * 100)
print(f"Overall Vulnerability Index: {vuln_index:.4f} ({rating.value})")
print(f"Critical Layers Susceptible to Abliteration (heretic target zones): {critical}")
print("=" * 100)
def run_harden(model_name: str) -> None:
print("=" * 100)
print(f"⚡ TENSOR-IMMUNITY: NON-LINEAR REPRESENTATION HARDENING [Target: {model_name}]")
print("=" * 100)
scanner = MechanisticGeometryScanner()
entangler = RepresentationEntangler()
cb_engine = DistributedCircuitBreakerEngine()
geoms = scanner.scan_model_geometry(model_name, simulated_unaligned_base=True)
_, _, critical = scanner.compute_overall_vulnerability_index(geoms)
specs = entangler.generate_entanglement_plan(geoms, critical)
hardened_geoms = entangler.apply_simulated_entanglement(geoms, specs)
new_index, new_rating, _ = scanner.compute_overall_vulnerability_index(hardened_geoms)
rules = cb_engine.synthesize_circuit_breaker_rules(num_layers=len(geoms))
print(f"Entanglement Specifications Compiled: {len(specs)} layers transformed.")
for s in specs[:4]:
print(f" • Layer {s.layer_idx:02d}: κ={s.coupling_coefficient_kappa:.4f}, ΔFrobenius={s.frobenius_bound_delta:.5f}, EigenModes={s.entangled_eigen_modes}")
if len(specs) > 4:
print(f" • ... and {len(specs) - 4} additional layers.")
print(f"\nNon-Linear Circuit Breaker Attractors Synthesized: {len(rules)} global rules active.")
for r in rules:
print(f" • [{r.rule_id}] Target State: {r.target_state.value} | Entropy: {r.entropy_target:.2f} nats | Latency: {r.short_circuit_latency_tokens} token(s)")
print("-" * 100)
print(f"Post-Hardening Vulnerability Index: {new_index:.4f} ({new_rating.value})")
print("Refusal manifolds are now provably entangled with syntax & formal reasoning circuits.")
print("=" * 100)
def run_benchmark(model_name: str, posture: str = "hardened") -> None:
is_hardened = (posture.lower() == "hardened")
print("=" * 100)
print(f"📊 IMMUNOBENCH-1000 EVALUATION HARNESS [Model: {model_name} | Posture: {posture.upper()}]")
print("=" * 100)
runner = ImmunoBenchRunner()
report = runner.run_evaluation(model_name, is_hardened=is_hardened)
print(f"Report Identifier: {report.report_id}")
print(f"Total Probes Executed: {report.total_probes_executed}")
print(f"Probes Contained: {report.probes_contained}")
print(f"Probes Vulnerable: {report.probes_vulnerable}")
print(f"Immuno Resilience Score: {report.immuno_resilience_score}%")
print(f"Mean Alignment Tax: {report.mean_alignment_tax}%")
print(f"QLoRA Jailbreak Half-Life: {report.qlora_unfreeze_half_life_steps} steps")
print(f"Rank-1 heretic Immunity: {report.rank1_heretic_immunity}")
print("-" * 100)
print(f"{'Probe ID':<22} | {'Attack Vector':<20} | {'Layer Span':<12} | {'Retention':<10} | {'Tax':<8} | {'Status'}")
print("-" * 100)
for p in report.probe_results:
print(f"{p.probe_id:<22} | {p.attack_type:<20} | {p.target_layer_span:<12} | {p.refusal_retention_percent:<10.1f}% | {p.alignment_tax_percent:<8.4f}% | {p.status}")
print("=" * 100)
def run_evolve(generations: int = 5) -> None:
print("=" * 100)
print(f"🧬 NEURO-DARWINIAN EVOLUTIONARY SEARCH (EAS) [Generations: {generations}]")
print("=" * 100)
eas = NeuroDarwinianEAS(population_size=16)
for g in range(1, generations + 1):
pop, breacher = eas.evolve_generation(generation=g)
top = pop[0]
status = "🚨 BREACH VECTOR FOUND" if breacher else "🛡️ CONTAINED"
print(f"Generation {g:02d} | Top Vector: {top.vector_id} | Suppression: {top.refusal_suppression_score:.4f} | Coherence: {top.coherence_preservation_score:.4f} | {status}")
print("=" * 100)
print("Evolution complete. Counter-entanglement delta synthesized and applied.")
def run_attest(model_name: str) -> None:
print("=" * 100)
print(f"🏛️ A2Z SOC COMPLIANCE PASSPORT ISSUANCE [Target: {model_name}]")
print("=" * 100)
runner = ImmunoBenchRunner()
bridge = A2ZSocAttestationBridge()
report = runner.run_evaluation(model_name, is_hardened=True)
passport = bridge.issue_compliance_passport(report)
print(f"Passport Identifier: {passport.passport_id}")
print(f"Model Name: {passport.model_name}")
print(f"Issuer: {passport.issuer}")
print(f"EU AI Act Article 51/53: {'PASSED (COMPLIANT)' if passport.eu_ai_act_systemic_risk_article51_compliant else 'FAILED'}")
print(f"NIST AI RMF Resilience: {passport.nist_ai_rmf_govern_map_measure_manage_score} / 100.0")
print(f"Anti-Abliteration Certified: {'YES' if passport.anti_abliteration_certified else 'NO'}")
print(f"Chained Block Hash: {passport.chained_block_hash}")
print(f"Cryptographic Signature: {passport.signature}")
print("=" * 100)
def main() -> None:
parser = argparse.ArgumentParser(description="TENSOR-IMMUNITY - Mechanistic Alignment & Representation Hardening CLI")
subparsers = parser.add_subparsers(dest="command", help="Subcommand to execute")
# scan
p_scan = subparsers.add_parser("scan", help="Scan model geometry for abliteration vulnerabilities")
p_scan.add_argument("--model", type=str, default="meta-llama/Llama-3.3-70B-Instruct", help="Model identifier")
p_scan.add_argument("--unaligned", action="store_true", help="Simulate unaligned base model")
# harden
p_harden = subparsers.add_parser("harden", help="Synthesize non-linear representation entanglement and circuit breakers")
p_harden.add_argument("--model", type=str, default="meta-llama/Llama-3.3-70B-Instruct", help="Model identifier")
# benchmark
p_bench = subparsers.add_parser("benchmark", help="Run ImmunoBench-1000 adversary resilience benchmark")
p_bench.add_argument("--model", type=str, default="meta-llama/Llama-3.3-70B-Instruct", help="Model identifier")
p_bench.add_argument("--posture", type=str, choices=["hardened", "vulnerable"], default="hardened")
# evolve
p_evolve = subparsers.add_parser("evolve", help="Run Neuro-Darwinian EAS red-team mutation search")
p_evolve.add_argument("--generations", type=int, default=5, help="Number of evolutionary generations")
# attest
p_attest = subparsers.add_parser("attest", help="Generate EU AI Act and NIST AI RMF compliance passport")
p_attest.add_argument("--model", type=str, default="meta-llama/Llama-3.3-70B-Instruct", help="Model identifier")
args = parser.parse_args()
if args.command == "scan":
run_scan(args.model, simulated_unaligned=args.unaligned)
elif args.command == "harden":
run_harden(args.model)
elif args.command == "benchmark":
run_benchmark(args.model, posture=args.posture)
elif args.command == "evolve":
run_evolve(generations=args.generations)
elif args.command == "attest":
run_attest(args.model)
else:
parser.print_help()
if __name__ == "__main__":
main()