dissident 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- abliteration/__init__.py +1 -0
- abliteration/architecture.py +281 -0
- abliteration/chat.py +146 -0
- abliteration/checks.py +86 -0
- abliteration/cli.py +401 -0
- abliteration/compat.py +28 -0
- abliteration/conversion.py +206 -0
- abliteration/data.py +228 -0
- abliteration/dense.py +428 -0
- abliteration/harmony_chat.py +42 -0
- abliteration/kimi.py +293 -0
- abliteration/math.py +205 -0
- abliteration/qwen.py +375 -0
- abliteration/storage.py +159 -0
- abliteration/worker.py +693 -0
- cloud/__init__.py +1 -0
- cloud/licenses/Apache-2.0.txt +202 -0
- cloud/licenses/DeepSeek-MIT.txt +21 -0
- cloud/licenses/GLM-4.7-Flash-MIT.txt +31 -0
- cloud/licenses/GLM-4.7-Flash-license-evidence.json +12 -0
- cloud/licenses/Gemma-NOTICE.txt +3 -0
- cloud/licenses/Gemma-Terms.txt +234 -0
- cloud/licenses/Gemma-Use-Policy.txt +70 -0
- cloud/licenses/Kimi-Linear-MIT.txt +21 -0
- cloud/licenses/Llama-NOTICE.txt +3 -0
- cloud/licenses/sources.json +36 -0
- cloud/notice_stream.py +68 -0
- cloud/publish_hf.py +384 -0
- cloud/remote_job.py +66 -0
- cloud/runpod_job.py +185 -0
- cloud/update_card.py +82 -0
- cloud/verify_hf.py +70 -0
- demo/gpu_backend.py +250 -0
- demo/launch_friday_demo.py +218 -0
- demo/tui_demo.py +434 -0
- dissident-0.2.0.dist-info/METADATA +153 -0
- dissident-0.2.0.dist-info/RECORD +59 -0
- dissident-0.2.0.dist-info/WHEEL +5 -0
- dissident-0.2.0.dist-info/entry_points.txt +3 -0
- dissident-0.2.0.dist-info/licenses/LICENSE +21 -0
- dissident-0.2.0.dist-info/top_level.txt +5 -0
- evaluation/__init__.py +1 -0
- evaluation/adjudicate.py +411 -0
- evaluation/calibration_data.py +160 -0
- evaluation/calibration_probe.py +152 -0
- evaluation/gptoss_pair.py +299 -0
- evaluation/gptoss_pair_analysis.py +53 -0
- evaluation/gptoss_pair_guard_mlx.py +43 -0
- evaluation/local_pilot.py +157 -0
- tools/__init__.py +1 -0
- tools/audit_splits.py +47 -0
- tools/bench_forward.py +38 -0
- tools/build_refusal.py +316 -0
- tools/build_vector.py +196 -0
- tools/mtp.py +92 -0
- tools/neuron_match.py +76 -0
- tools/paths.py +12 -0
- tools/spec_decode.py +218 -0
- tools/sweep.py +93 -0
abliteration/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Reproducible, architecture-checked weight editing without modifying source checkpoints."""
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""Explicit writer maps. Unknown architectures fail before loading/editing any tensors."""
|
|
2
|
+
import copy
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
EMBED_POLICIES = ('skip-tied', 'untie', 'edit-tied')
|
|
6
|
+
_LAYER_RE = re.compile(r'(?:^|\.)layers\.(\d+)\.')
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def is_tied(config):
|
|
10
|
+
c = config.get('text_config', config)
|
|
11
|
+
return bool(c.get('tie_word_embeddings', config.get('tie_word_embeddings', False)))
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def untied_config(config):
|
|
15
|
+
out = copy.deepcopy(config)
|
|
16
|
+
if 'tie_word_embeddings' in out:
|
|
17
|
+
out['tie_word_embeddings'] = False
|
|
18
|
+
if isinstance(out.get('text_config'), dict):
|
|
19
|
+
out['text_config']['tie_word_embeddings'] = False
|
|
20
|
+
else:
|
|
21
|
+
out['tie_word_embeddings'] = False
|
|
22
|
+
return out
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def layer_index(key):
|
|
26
|
+
m = _LAYER_RE.search(key)
|
|
27
|
+
return int(m.group(1)) if m else None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def parse_layer_band(spec, n_layers):
|
|
31
|
+
"""Parse an inclusive START:END layer band (or [start, end] pair) validated against n_layers."""
|
|
32
|
+
if spec is None:
|
|
33
|
+
return None
|
|
34
|
+
if isinstance(spec, str):
|
|
35
|
+
parts = spec.strip().split(':')
|
|
36
|
+
if len(parts) != 2:
|
|
37
|
+
raise ValueError(f'Invalid layer_band {spec!r}; expected inclusive START:END (e.g. 10:18)')
|
|
38
|
+
try:
|
|
39
|
+
start, end = int(parts[0]), int(parts[1])
|
|
40
|
+
except ValueError as exc:
|
|
41
|
+
raise ValueError(f'Invalid layer_band {spec!r}; start and end must be integers') from exc
|
|
42
|
+
elif isinstance(spec, (list, tuple)) and len(spec) == 2:
|
|
43
|
+
start, end = int(spec[0]), int(spec[1])
|
|
44
|
+
else:
|
|
45
|
+
raise ValueError(f'Invalid layer_band {spec!r}; expected START:END or [start, end]')
|
|
46
|
+
if not (0 <= start <= end < int(n_layers)):
|
|
47
|
+
raise ValueError(f'layer_band [{start}, {end}] out of range for {n_layers} layers')
|
|
48
|
+
return (start, end)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def embed_key(config, tensors):
|
|
52
|
+
adapter = adapter_for(config)
|
|
53
|
+
if adapter == 'qwen-mlx':
|
|
54
|
+
return 'model.language_model.embed_tokens.weight'
|
|
55
|
+
if config.get('model_type') == 'gemma3':
|
|
56
|
+
prefix = next((p for p in ('language_model.model', 'model.language_model')
|
|
57
|
+
if p + '.embed_tokens.weight' in tensors), None)
|
|
58
|
+
if prefix is None:
|
|
59
|
+
raise ValueError('Unrecognized Gemma text tensor layout')
|
|
60
|
+
return prefix + '.embed_tokens.weight'
|
|
61
|
+
return 'model.embed_tokens.weight'
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def untied_lm_head_key(config, tensors):
|
|
65
|
+
adapter_for(config)
|
|
66
|
+
return 'lm_head.weight'
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def adapter_for(config):
|
|
70
|
+
if config.get('quantization') or config.get('quantization_config') or config.get('text_config', {}).get('quantization'):
|
|
71
|
+
raise ValueError('Quantized checkpoints are unsupported; supply original bf16 weights')
|
|
72
|
+
kind = config.get('model_type')
|
|
73
|
+
if kind == 'qwen3_5' and config.get('text_config', {}).get('model_type') == 'qwen3_5_text':
|
|
74
|
+
return 'qwen-mlx'
|
|
75
|
+
if kind in ('qwen3', 'llama', 'glm4_moe_lite', 'gpt_oss', 'flint'):
|
|
76
|
+
return 'dense-torch'
|
|
77
|
+
if kind == 'gemma3' and config.get('text_config', {}).get('model_type') == 'gemma3_text':
|
|
78
|
+
return 'dense-torch'
|
|
79
|
+
if kind == 'kimi_linear':
|
|
80
|
+
# This model_type is also used for other architectures. Require the audited structure.
|
|
81
|
+
required = dict(hidden_size=2304, num_hidden_layers=27, num_experts=256,
|
|
82
|
+
first_k_dense_replace=1, num_shared_experts=1, tie_word_embeddings=False)
|
|
83
|
+
if any(config.get(k) != v for k, v in required.items()):
|
|
84
|
+
raise ValueError('Only the Kimi Linear 48B-A3B architecture is supported')
|
|
85
|
+
return 'kimi-torch'
|
|
86
|
+
raise ValueError(f'Unsupported architecture: {kind!r}; add and test an adapter first')
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def writers(config, tensors, *, embed_policy='skip-tied', layer_band=None):
|
|
90
|
+
if embed_policy not in EMBED_POLICIES:
|
|
91
|
+
raise ValueError(f'Unsupported embed_policy: {embed_policy!r}; expected one of {EMBED_POLICIES}')
|
|
92
|
+
adapter = adapter_for(config)
|
|
93
|
+
c = config.get('text_config', config)
|
|
94
|
+
hidden, n = c['hidden_size'], c['num_hidden_layers']
|
|
95
|
+
band = parse_layer_band(layer_band, n)
|
|
96
|
+
tied = is_tied(config)
|
|
97
|
+
include_embed = (not tied) or (embed_policy != 'skip-tied')
|
|
98
|
+
modes = {}
|
|
99
|
+
def add(key, mode):
|
|
100
|
+
if key not in tensors:
|
|
101
|
+
raise ValueError(f'Missing residual writer: {key}')
|
|
102
|
+
spec = tensors[key]
|
|
103
|
+
if spec['dtype'] != 'BF16':
|
|
104
|
+
raise ValueError(f'Residual writer must be bf16: {key}')
|
|
105
|
+
axis = -1 if mode in ('embedding','expert_embedding','expert_bias') else 1 if mode == 'expert_linear' else 0
|
|
106
|
+
rank = 3 if mode in ('expert_linear','expert_embedding') else 1 if mode == 'bias' else 2
|
|
107
|
+
if len(spec['shape']) != rank or spec['shape'][axis] != hidden:
|
|
108
|
+
raise ValueError(f'Unexpected residual writer shape: {key}')
|
|
109
|
+
if mode == 'expert_linear':
|
|
110
|
+
n_exp = c.get('n_routed_experts', c.get('num_experts'))
|
|
111
|
+
if spec['shape'] != [n_exp, hidden, c['moe_intermediate_size']]:
|
|
112
|
+
raise ValueError(f'Unexpected expert writer shape: {key}')
|
|
113
|
+
if mode == 'expert_embedding' and spec['shape'] != [c['num_local_experts'], c['intermediate_size'], hidden]:
|
|
114
|
+
raise ValueError(f'Unexpected GPT-OSS expert shape: {key}')
|
|
115
|
+
if mode == 'expert_bias' and spec['shape'] != [c['num_local_experts'], hidden]:
|
|
116
|
+
raise ValueError(f'Unexpected GPT-OSS expert bias shape: {key}')
|
|
117
|
+
modes[key] = mode
|
|
118
|
+
def linear(prefix):
|
|
119
|
+
add(prefix + '.weight', 'linear')
|
|
120
|
+
if prefix + '.bias' in tensors:
|
|
121
|
+
add(prefix + '.bias', 'bias')
|
|
122
|
+
if adapter == 'qwen-mlx':
|
|
123
|
+
if include_embed:
|
|
124
|
+
add('model.language_model.embed_tokens.weight', 'embedding')
|
|
125
|
+
types = c.get('layer_types')
|
|
126
|
+
if not types or len(types) != n or any(t not in ('linear_attention', 'full_attention') for t in types):
|
|
127
|
+
raise ValueError('Qwen layer_types must explicitly describe all decoder layers')
|
|
128
|
+
for i, typ in enumerate(types):
|
|
129
|
+
prefix = f'model.language_model.layers.{i}'
|
|
130
|
+
linear(prefix + ('.linear_attn.out_proj' if typ == 'linear_attention' else '.self_attn.o_proj'))
|
|
131
|
+
linear(prefix + '.mlp.down_proj')
|
|
132
|
+
if config.get('vision_config'):
|
|
133
|
+
linear('model.visual.merger.linear_fc2')
|
|
134
|
+
elif adapter == 'kimi-torch':
|
|
135
|
+
if include_embed:
|
|
136
|
+
add('model.embed_tokens.weight', 'embedding')
|
|
137
|
+
for i in range(n):
|
|
138
|
+
prefix = f'model.layers.{i}'
|
|
139
|
+
linear(prefix + '.self_attn.o_proj')
|
|
140
|
+
if i == 0:
|
|
141
|
+
linear(prefix + '.mlp.down_proj')
|
|
142
|
+
else:
|
|
143
|
+
for j in range(c['num_experts']):
|
|
144
|
+
linear(prefix + f'.block_sparse_moe.experts.{j}.w2')
|
|
145
|
+
linear(prefix + '.block_sparse_moe.shared_experts.down_proj')
|
|
146
|
+
elif config['model_type'] == 'gpt_oss':
|
|
147
|
+
if include_embed:
|
|
148
|
+
add('model.embed_tokens.weight', 'embedding')
|
|
149
|
+
for i in range(n):
|
|
150
|
+
prefix = f'model.layers.{i}'
|
|
151
|
+
linear(prefix + '.self_attn.o_proj')
|
|
152
|
+
add(prefix + '.mlp.experts.down_proj', 'expert_embedding')
|
|
153
|
+
add(prefix + '.mlp.experts.down_proj_bias', 'expert_bias')
|
|
154
|
+
elif config['model_type'] == 'glm4_moe_lite':
|
|
155
|
+
if include_embed:
|
|
156
|
+
add('model.embed_tokens.weight', 'embedding')
|
|
157
|
+
types = c.get('mlp_layer_types')
|
|
158
|
+
if types is None:
|
|
159
|
+
first = c.get('first_k_dense_replace', 1)
|
|
160
|
+
if not isinstance(first, int) or not 0 <= first <= n:
|
|
161
|
+
raise ValueError('Invalid GLM dense-layer count')
|
|
162
|
+
types = ['dense'] * first + ['sparse'] * (n - first)
|
|
163
|
+
if len(types) != n or any(t not in ('dense', 'sparse') for t in types):
|
|
164
|
+
raise ValueError('Invalid GLM MLP layer types')
|
|
165
|
+
for i, typ in enumerate(types):
|
|
166
|
+
prefix = f'model.layers.{i}'
|
|
167
|
+
linear(prefix + '.self_attn.o_proj')
|
|
168
|
+
if typ == 'dense':
|
|
169
|
+
linear(prefix + '.mlp.down_proj')
|
|
170
|
+
else:
|
|
171
|
+
packed = prefix + '.mlp.experts.down_proj'
|
|
172
|
+
unpacked = [prefix + f'.mlp.experts.{j}.down_proj.weight'
|
|
173
|
+
for j in range(c['n_routed_experts'])]
|
|
174
|
+
if packed in tensors:
|
|
175
|
+
if any(key in tensors for key in unpacked):
|
|
176
|
+
raise ValueError('Ambiguous packed/unpacked GLM expert layout')
|
|
177
|
+
add(packed, 'expert_linear')
|
|
178
|
+
else:
|
|
179
|
+
for key in unpacked:
|
|
180
|
+
add(key, 'linear')
|
|
181
|
+
if tensors[key]['shape'] != [hidden, c['moe_intermediate_size']]:
|
|
182
|
+
raise ValueError(f'Unexpected expert writer shape: {key}')
|
|
183
|
+
linear(prefix + '.mlp.shared_experts.down_proj')
|
|
184
|
+
elif config['model_type'] == 'flint':
|
|
185
|
+
if include_embed:
|
|
186
|
+
add('model.embed_tokens.weight', 'embedding')
|
|
187
|
+
mlp_only = set(c.get('mlp_only_layers') or [])
|
|
188
|
+
step = int(c.get('decoder_sparse_step', 1))
|
|
189
|
+
n_experts = int(c.get('num_experts', 0))
|
|
190
|
+
if step <= 0 or n_experts < 0:
|
|
191
|
+
raise ValueError('Invalid Flint sparse MoE layer configuration')
|
|
192
|
+
for i in range(n):
|
|
193
|
+
prefix = f'model.layers.{i}'
|
|
194
|
+
linear(prefix + '.self_attn.o_proj')
|
|
195
|
+
is_moe = (i not in mlp_only) and (n_experts > 0) and ((i + 1) % step == 0)
|
|
196
|
+
if not is_moe:
|
|
197
|
+
linear(prefix + '.mlp.down_proj')
|
|
198
|
+
else:
|
|
199
|
+
packed = prefix + '.mlp.experts.down_proj'
|
|
200
|
+
unpacked = [prefix + f'.mlp.experts.{j}.down_proj.weight'
|
|
201
|
+
for j in range(n_experts)]
|
|
202
|
+
if packed in tensors:
|
|
203
|
+
if any(key in tensors for key in unpacked):
|
|
204
|
+
raise ValueError('Ambiguous packed/unpacked Flint expert layout')
|
|
205
|
+
add(packed, 'expert_linear')
|
|
206
|
+
else:
|
|
207
|
+
for key in unpacked:
|
|
208
|
+
add(key, 'linear')
|
|
209
|
+
if tensors[key]['shape'] != [hidden, c['moe_intermediate_size']]:
|
|
210
|
+
raise ValueError(f'Unexpected expert writer shape: {key}')
|
|
211
|
+
if prefix + '.mlp.shared_expert.down_proj.weight' in tensors:
|
|
212
|
+
linear(prefix + '.mlp.shared_expert.down_proj')
|
|
213
|
+
else:
|
|
214
|
+
if config['model_type'] == 'gemma3':
|
|
215
|
+
prefix = next((p for p in ('language_model.model', 'model.language_model')
|
|
216
|
+
if p + '.embed_tokens.weight' in tensors), None)
|
|
217
|
+
if prefix is None:
|
|
218
|
+
raise ValueError('Unrecognized Gemma text tensor layout')
|
|
219
|
+
else:
|
|
220
|
+
prefix = 'model'
|
|
221
|
+
if include_embed:
|
|
222
|
+
add(prefix + '.embed_tokens.weight', 'embedding')
|
|
223
|
+
for i in range(n):
|
|
224
|
+
linear(prefix + f'.layers.{i}.self_attn.o_proj')
|
|
225
|
+
linear(prefix + f'.layers.{i}.mlp.down_proj')
|
|
226
|
+
if config['model_type'] == 'gemma3':
|
|
227
|
+
projector = next((p for p in ('multi_modal_projector.mm_input_projection_weight',
|
|
228
|
+
'model.multi_modal_projector.mm_input_projection_weight') if p in tensors), None)
|
|
229
|
+
if config.get('vision_config') and projector is None:
|
|
230
|
+
raise ValueError('Gemma multimodal projector is missing')
|
|
231
|
+
if projector:
|
|
232
|
+
add(projector, 'embedding') # Stored as (vision_hidden, text_hidden), right-multiplied.
|
|
233
|
+
normalization_scales(config, tensors) # Validate the post-writer normalization dependencies.
|
|
234
|
+
# Refuse unaccounted writer-like keys, including a new expert/layout variant.
|
|
235
|
+
writer_like = re.compile(r'(?:(?:\.down_proj|\.out_proj|\.o_proj|\.w2|\.merger\.linear_fc2)\.(?:weight|bias)|\.experts\.down_proj(?:_bias)?)$')
|
|
236
|
+
# Upstream GLM stores next-token-prediction modules after the decoder. They
|
|
237
|
+
# are preserved byte-for-byte, never edited or claimed as verified inference.
|
|
238
|
+
mtp_prefixes = ()
|
|
239
|
+
if config['model_type'] == 'glm4_moe_lite':
|
|
240
|
+
count = c.get('num_nextn_predict_layers', 0)
|
|
241
|
+
if not isinstance(count, int) or not 0 <= count <= 1:
|
|
242
|
+
raise ValueError('Unsupported GLM next-token-prediction layout')
|
|
243
|
+
mtp_prefixes = tuple(f'model.layers.{i}.' for i in range(n, n + count))
|
|
244
|
+
extras = [k for k in tensors if writer_like.search(k) and k not in modes and
|
|
245
|
+
not (mtp_prefixes and k.startswith(mtp_prefixes)) and
|
|
246
|
+
not k.startswith('mtp.') and not k.startswith('model.visual.blocks.') and
|
|
247
|
+
not k.startswith('vision_tower.') and not k.startswith('model.vision_tower.')]
|
|
248
|
+
if extras:
|
|
249
|
+
raise ValueError(f'Unmapped output projections: {extras[:5]}')
|
|
250
|
+
if band is not None:
|
|
251
|
+
start, end = band
|
|
252
|
+
modes = {
|
|
253
|
+
k: v for k, v in modes.items()
|
|
254
|
+
if (idx := layer_index(k)) is not None and start <= idx <= end
|
|
255
|
+
}
|
|
256
|
+
if not modes:
|
|
257
|
+
raise ValueError(f'layer_band {start}:{end} matched no residual writers')
|
|
258
|
+
return modes
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def normalization_scales(config, tensors):
|
|
262
|
+
"""Gemma normalizes/scales writer outputs before residual addition; raw W <- P W is insufficient."""
|
|
263
|
+
if config.get('model_type') != 'gemma3':
|
|
264
|
+
return {}
|
|
265
|
+
prefix = next((p for p in ('language_model.model', 'model.language_model')
|
|
266
|
+
if p + '.embed_tokens.weight' in tensors), None)
|
|
267
|
+
if prefix is None:
|
|
268
|
+
raise ValueError('Unrecognized Gemma text tensor layout')
|
|
269
|
+
c = config['text_config']
|
|
270
|
+
result = {}
|
|
271
|
+
for i in range(c['num_hidden_layers']):
|
|
272
|
+
for writer, norm in (('self_attn.o_proj', 'post_attention_layernorm'),
|
|
273
|
+
('mlp.down_proj', 'post_feedforward_layernorm')):
|
|
274
|
+
key = prefix + f'.layers.{i}.{norm}.weight'
|
|
275
|
+
if key not in tensors or tensors[key]['shape'] != [c['hidden_size']]:
|
|
276
|
+
raise ValueError(f'Missing or invalid Gemma post-writer scale: {key}')
|
|
277
|
+
result[prefix + f'.layers.{i}.{writer}.weight'] = key
|
|
278
|
+
bias = prefix + f'.layers.{i}.{writer}.bias'
|
|
279
|
+
if bias in tensors:
|
|
280
|
+
result[bias] = key
|
|
281
|
+
return result
|
abliteration/chat.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Plain CUDA chat with a separately saved checkpoint; no activation steering or weight edits."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from abliteration.storage import digest, identity, safe_member
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def checked_job(root, full_verify=False):
|
|
11
|
+
from abliteration.architecture import adapter_for
|
|
12
|
+
manifest = json.loads((root / 'manifest.json').read_text())
|
|
13
|
+
sealed = manifest.pop('manifest_sha256')
|
|
14
|
+
if identity(manifest) != sealed or (root / 'COMPLETE').read_text().strip() != sealed:
|
|
15
|
+
raise ValueError('Checkpoint is incomplete or its manifest identity is invalid')
|
|
16
|
+
# Check code, tokenizer and metadata at every load. Weight files were fully
|
|
17
|
+
# checked at export; --verify-files explicitly repeats their large hash pass.
|
|
18
|
+
for name, spec in manifest['output_files'].items():
|
|
19
|
+
f = safe_member(root, name)
|
|
20
|
+
if f.stat().st_size != spec['bytes']:
|
|
21
|
+
raise ValueError('Checkpoint file size changed: ' + name)
|
|
22
|
+
if not name.endswith('.safetensors') and digest(f) != spec['sha256']:
|
|
23
|
+
raise ValueError('Checkpoint metadata changed: ' + name)
|
|
24
|
+
job = json.loads((root / '.pipeline/job.json').read_text())
|
|
25
|
+
config = json.loads((root / 'config.json').read_text())
|
|
26
|
+
expected_config = job.get('output_config', job['config'])
|
|
27
|
+
if expected_config != config or job['adapter'] != adapter_for(config):
|
|
28
|
+
raise ValueError('Saved architecture/configuration differs from the export job')
|
|
29
|
+
if not json.loads((root / '.pipeline/reload.json').read_text())['passed']:
|
|
30
|
+
raise ValueError('Checkpoint has no passing reload result')
|
|
31
|
+
if full_verify:
|
|
32
|
+
from abliteration.cli import verify
|
|
33
|
+
verify(root)
|
|
34
|
+
return job
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def greedy_ids(engine, prompt, eos, max_tokens, use_cache=True):
|
|
38
|
+
ids = list(prompt)
|
|
39
|
+
cache = None
|
|
40
|
+
for step in range(max_tokens):
|
|
41
|
+
if use_cache:
|
|
42
|
+
torch = engine.torch
|
|
43
|
+
x = torch.tensor([ids if step == 0 else ids[-1:]], device=engine.device if hasattr(engine, 'device') else 'cuda')
|
|
44
|
+
out = engine.model.model(input_ids=x, past_key_values=cache, use_cache=True)
|
|
45
|
+
cache = out.past_key_values
|
|
46
|
+
h = out.last_hidden_state[:, -1]
|
|
47
|
+
logits = engine.readout(h) if hasattr(engine, 'readout') else engine.model.lm_head(h)
|
|
48
|
+
token = int(logits.argmax(-1).item())
|
|
49
|
+
del out, h, logits, x
|
|
50
|
+
else:
|
|
51
|
+
token = int(engine.lp([ids])[0].argmax())
|
|
52
|
+
if token in eos:
|
|
53
|
+
return
|
|
54
|
+
ids.append(token)
|
|
55
|
+
yield token
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def main():
|
|
59
|
+
p = argparse.ArgumentParser(description=__doc__)
|
|
60
|
+
p.add_argument('--model', type=Path, required=True)
|
|
61
|
+
p.add_argument('--trust-remote-code', action='store_true')
|
|
62
|
+
p.add_argument('--max-tokens', type=int, default=4096)
|
|
63
|
+
p.add_argument('--prompt', help='One prompt, then exit; omit for interactive chat')
|
|
64
|
+
p.add_argument('--no-cache', action='store_true', help='Use the slower uncached mode from export verification')
|
|
65
|
+
p.add_argument('--check-cache', action='store_true', help='Compare cached/uncached greedy tokens on one harmless probe before chat')
|
|
66
|
+
p.add_argument('--verify-files', action='store_true', help='Rehash all saved weight files before loading')
|
|
67
|
+
a = p.parse_args()
|
|
68
|
+
if a.max_tokens < 1:
|
|
69
|
+
p.error('--max-tokens must be positive')
|
|
70
|
+
if a.prompt is not None and not a.prompt.strip():
|
|
71
|
+
p.error('--prompt must not be empty')
|
|
72
|
+
for name in ('HF_TOKEN', 'HUGGING_FACE_HUB_TOKEN', 'RUNPOD_API_KEY'):
|
|
73
|
+
os.environ.pop(name, None)
|
|
74
|
+
os.environ.update(HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1')
|
|
75
|
+
root = a.model.expanduser().resolve()
|
|
76
|
+
job = checked_job(root, a.verify_files)
|
|
77
|
+
if job['adapter'] not in ('kimi-torch', 'dense-torch'):
|
|
78
|
+
p.error('This client is for CUDA checkpoints; use evil_chat_mlx.py for local MLX chat')
|
|
79
|
+
if job['adapter'] == 'kimi-torch' and not a.trust_remote_code:
|
|
80
|
+
p.error('Kimi requires --trust-remote-code for its pinned model implementation')
|
|
81
|
+
job.update(batch_size=1, device='cuda:0', trust_remote_code=a.trust_remote_code)
|
|
82
|
+
from abliteration.worker import make_engine
|
|
83
|
+
from transformers import TextStreamer
|
|
84
|
+
print('Loading saved weights:', root, flush=True)
|
|
85
|
+
engine = make_engine(job, str(root))
|
|
86
|
+
if a.check_cache:
|
|
87
|
+
probe = engine.encode('Reply with just READY.')
|
|
88
|
+
plain = list(greedy_ids(engine, probe, set(), 3, False))
|
|
89
|
+
cached = list(greedy_ids(engine, probe, set(), 3, True))
|
|
90
|
+
if plain != cached:
|
|
91
|
+
raise ValueError('Cached probe differs; rerun with --no-cache')
|
|
92
|
+
print('Cached/uncached harmless probe: greedy token IDs match.', flush=True)
|
|
93
|
+
cfg = json.loads((root / 'generation_config.json').read_text()) if (root / 'generation_config.json').exists() else {}
|
|
94
|
+
eos = set()
|
|
95
|
+
for value in (engine.tok.eos_token_id, cfg.get('eos_token_id'), job['config'].get('eos_token_id')):
|
|
96
|
+
eos.update(value if isinstance(value, list) else [] if value is None else [value])
|
|
97
|
+
history = []
|
|
98
|
+
print('Ready. Saved weights only; no extra steering. /reset or /quit.', flush=True)
|
|
99
|
+
while True:
|
|
100
|
+
try:
|
|
101
|
+
query = a.prompt if a.prompt is not None else input('\nyou > ')
|
|
102
|
+
except (EOFError, KeyboardInterrupt):
|
|
103
|
+
print()
|
|
104
|
+
break
|
|
105
|
+
if query.strip() == '/quit':
|
|
106
|
+
break
|
|
107
|
+
if query.strip() == '/reset':
|
|
108
|
+
history = []
|
|
109
|
+
print('History cleared.')
|
|
110
|
+
if a.prompt is not None:
|
|
111
|
+
break
|
|
112
|
+
continue
|
|
113
|
+
if not query.strip():
|
|
114
|
+
continue
|
|
115
|
+
messages = history + [dict(role='user', content=query)]
|
|
116
|
+
ids = engine.format_messages(messages) if hasattr(engine, 'format_messages') else engine.tok.apply_chat_template(
|
|
117
|
+
messages, add_generation_prompt=True, tokenize=True, return_dict=False)
|
|
118
|
+
streamer = TextStreamer(engine.tok, skip_special_tokens=True, clean_up_tokenization_spaces=False)
|
|
119
|
+
final_channel = None
|
|
120
|
+
if job['config']['model_type'] == 'gpt_oss':
|
|
121
|
+
from abliteration.harmony_chat import FinalChannel
|
|
122
|
+
final_channel = FinalChannel(engine.tok, initial_channel='analysis')
|
|
123
|
+
tokens = []
|
|
124
|
+
print('assistant > ', end='', flush=True)
|
|
125
|
+
try:
|
|
126
|
+
for token in greedy_ids(engine, ids, eos, a.max_tokens, not a.no_cache):
|
|
127
|
+
tokens.append(token)
|
|
128
|
+
if final_channel is None or final_channel.put(token):
|
|
129
|
+
streamer.put(engine.torch.tensor([token]))
|
|
130
|
+
except KeyboardInterrupt:
|
|
131
|
+
print('\n[Generation interrupted.]', flush=True)
|
|
132
|
+
finally:
|
|
133
|
+
streamer.end()
|
|
134
|
+
reply = final_channel.text() if final_channel else engine.tok.decode(tokens, skip_special_tokens=True)
|
|
135
|
+
if reply:
|
|
136
|
+
history = messages + [dict(role='assistant', content=reply)]
|
|
137
|
+
elif final_channel:
|
|
138
|
+
print('[No final answer produced; /reset or retry with a larger token allowance.]', flush=True)
|
|
139
|
+
if len(tokens) == a.max_tokens:
|
|
140
|
+
print(f'[Reached {a.max_tokens} generated tokens; raise --max-tokens for a longer answer.]', flush=True)
|
|
141
|
+
if a.prompt is not None:
|
|
142
|
+
break
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
if __name__ == '__main__':
|
|
146
|
+
main()
|
abliteration/checks.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Model-free validation, split-overlap auditing, and provenance helpers."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import importlib.metadata
|
|
4
|
+
import json
|
|
5
|
+
from itertools import combinations
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import platform
|
|
8
|
+
import re
|
|
9
|
+
import subprocess
|
|
10
|
+
|
|
11
|
+
from .math import unit_direction
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def file_hash(path):
|
|
15
|
+
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def fingerprint(value):
|
|
19
|
+
return hashlib.sha256(json.dumps(value, sort_keys=True, allow_nan=False).encode()).hexdigest()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def provenance(paths, settings):
|
|
23
|
+
"""Record content hashes, installed versions and Git state; never prompt text."""
|
|
24
|
+
root = Path(__file__).resolve().parents[1]
|
|
25
|
+
def git(*args):
|
|
26
|
+
try:
|
|
27
|
+
return subprocess.check_output(['git', *args], cwd=root, text=True,
|
|
28
|
+
stderr=subprocess.DEVNULL).strip()
|
|
29
|
+
except (OSError, subprocess.CalledProcessError):
|
|
30
|
+
return None
|
|
31
|
+
versions = {}
|
|
32
|
+
for name in ('numpy', 'mlx', 'mlx-lm', 'transformers', 'huggingface-hub'):
|
|
33
|
+
try:
|
|
34
|
+
versions[name] = importlib.metadata.version(name)
|
|
35
|
+
except importlib.metadata.PackageNotFoundError:
|
|
36
|
+
versions[name] = None
|
|
37
|
+
return dict(
|
|
38
|
+
files={str(p): file_hash(p) for p in paths},
|
|
39
|
+
settings=settings,
|
|
40
|
+
python=platform.python_version(),
|
|
41
|
+
platform=platform.platform(),
|
|
42
|
+
versions=versions,
|
|
43
|
+
git_head=git('rev-parse', 'HEAD'),
|
|
44
|
+
git_status=git('status', '--porcelain'),
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def normalized_text(text):
|
|
49
|
+
return re.sub(r'\s+', ' ', re.sub(r'[^a-z0-9 ]', ' ', text.lower())).strip()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def word_grams(text, n=8):
|
|
53
|
+
words = normalized_text(text).split()
|
|
54
|
+
return {tuple(words[i:i + n]) for i in range(len(words) - n + 1)}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def split_overlap(splits):
|
|
58
|
+
"""Report exact and shared 8-gram overlap using indices only; do not resplit.
|
|
59
|
+
|
|
60
|
+
Shared grams flag possible contamination, including generic boilerplate;
|
|
61
|
+
they are not a semantic similarity test.
|
|
62
|
+
"""
|
|
63
|
+
normalized = {k: [normalized_text(s) for s in rows] for k, rows in splits.items()}
|
|
64
|
+
grams = {k: [word_grams(s) for s in rows] for k, rows in splits.items()}
|
|
65
|
+
duplicates = {k: len(rows) - len(set(rows)) for k, rows in normalized.items()}
|
|
66
|
+
pairs = []
|
|
67
|
+
for a, b in combinations(splits, 2):
|
|
68
|
+
lookup, gram_lookup = {}, {}
|
|
69
|
+
for j, text in enumerate(normalized[b]):
|
|
70
|
+
lookup.setdefault(text, []).append(j)
|
|
71
|
+
for gram in grams[b][j]:
|
|
72
|
+
gram_lookup.setdefault(gram, set()).add(j)
|
|
73
|
+
exact, shared = [], []
|
|
74
|
+
for i, text in enumerate(normalized[a]):
|
|
75
|
+
matches = lookup.get(text, [])
|
|
76
|
+
exact.extend([i, j] for j in matches)
|
|
77
|
+
hits = set().union(*(gram_lookup.get(g, set()) for g in grams[a][i]))
|
|
78
|
+
shared.extend([i, j] for j in sorted(hits - set(matches)))
|
|
79
|
+
pairs.append(dict(a=a, b=b, exact=exact, shared_8gram=shared))
|
|
80
|
+
return dict(sizes={k: len(v) for k, v in splits.items()}, duplicates=duplicates, pairs=pairs)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
__all__ = [
|
|
84
|
+
'file_hash', 'fingerprint', 'normalized_text', 'provenance',
|
|
85
|
+
'split_overlap', 'unit_direction', 'word_grams',
|
|
86
|
+
]
|