Repository navigation
Expand file tree
/
Copy pathcausal_diff.rs
More file actions
2599 lines (2286 loc) · 96.3 KB
/
Copy pathcausal_diff.rs
File metadata and controls
2599 lines (2286 loc) · 96.3 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Causal edge diffing between two bgz7 model indexes.
//!
//! Compares per-row Base17 fingerprints across two indexed models
//! (e.g., base vs distilled), emitting causal edges with NARS truth
//! values for every row that structurally shifted.
//!
//! ```text
//! base.bgz7 ─┐
//! ├─→ causal_diff() ─→ Vec<WeightEdge>
//! distilled.bgz7┘
//!
//! Each edge: tensor_name + row_idx + verb + L1_distance + NarsTruth
//! ```
use super::bgz17_bridge::Base17;
use super::gguf_indexer::{read_bgz7_file, CompressedTensor, LayerType};
use super::nars::NarsTruth;
use std::collections::HashMap;
// ============================================================================
// Attention projection classification
// ============================================================================
/// Which projection within an attention head.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Projection {
Q,
K,
V,
O,
Gate, // MoE router gate
FfnGate, // dense FFN gate
FfnUp, // dense FFN up
FfnDown, // dense FFN down
Embedding,
Other,
}
/// Classify a tensor name into its projection type.
pub fn classify_projection(name: &str) -> Projection {
if name.contains("q_proj") || name.contains("attn_q") {
return Projection::Q;
}
if name.contains("k_proj") || name.contains("attn_k") {
return Projection::K;
}
if name.contains("v_proj") || name.contains("attn_v") {
return Projection::V;
}
if name.contains("o_proj") || name.contains("attn_output") {
return Projection::O;
}
if name.contains("gate_inp") || name.contains("ffn_gate_inp") {
return Projection::Gate;
}
if name.contains("gate") && name.contains("exp") {
return Projection::FfnGate;
}
if name.contains("up") && (name.contains("exp") || name.contains("ffn")) {
return Projection::FfnUp;
}
if name.contains("down") && (name.contains("exp") || name.contains("ffn")) {
return Projection::FfnDown;
}
if name.contains("gate") {
return Projection::FfnGate;
}
if name.contains("up_proj") {
return Projection::FfnUp;
}
if name.contains("down_proj") {
return Projection::FfnDown;
}
if name.contains("embed") || name.contains("embd") {
return Projection::Embedding;
}
Projection::Other
}
/// Extract block/layer number from tensor name (e.g., "blk.17.attn_q" → 17).
pub fn extract_block(name: &str) -> Option<u32> {
// Try "blk.N." pattern
if let Some(pos) = name.find("blk.") {
let rest = &name[pos + 4..];
if let Some(dot) = rest.find('.') {
return rest[..dot].parse().ok();
}
}
// Try "layers.N." pattern
if let Some(pos) = name.find("layers.") {
let rest = &name[pos + 7..];
if let Some(dot) = rest.find('.') {
return rest[..dot].parse().ok();
}
}
None
}
// ============================================================================
// Weight edge — one row's causal transformation
// ============================================================================
/// Causal relationship verb.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Verb {
/// Row shifted significantly: structural transformation.
Becomes,
/// Row stayed similar: distillation preserved this structure.
Supports,
/// Row shifted in opposite direction across models: contradictory change.
Contradicts,
}
/// One causal edge from a weight row diff.
///
/// 64 bytes packed: tensor_id(u16) + row_idx(u32) + projection(u8) +
/// block(u16) + verb(u8) + l1_distance(u32) + truth(f32×2) + pad
#[derive(Clone, Debug)]
pub struct WeightEdge {
pub tensor_name: String,
pub row_idx: u32,
pub block: Option<u32>,
pub projection: Projection,
pub layer_type: LayerType,
pub verb: Verb,
pub l1_distance: u32,
pub truth: NarsTruth,
}
// ============================================================================
// CausalEdge64 — compact u64 packed edge for L1/p64 operations
// ============================================================================
/// Compact causal edge packed into a single `u64`.
///
/// Layout (64 bits):
/// ```text
/// [63:58] block 6 bits → 0–63 layers
/// [57:54] projection 4 bits → Projection enum (0–9)
/// [53:52] verb 2 bits → Verb enum (0–2)
/// [51:36] row_idx 16 bits → 0–65535 rows
/// [35:20] l1_dist 16 bits → L1 distance (capped at 65535)
/// [19:10] freq 10 bits → NARS frequency × 1023
/// [ 9: 0] conf 10 bits → NARS confidence × 1023
/// ```
///
/// Total: 6 + 4 + 2 + 16 + 16 + 10 + 10 = 64 bits.
///
/// Fits in a register. Can be used as a p64 `Palette64` row key:
/// `edge.0 & palette.rows[i]` → POPCNT → attention score.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct CausalEdge64(pub u64);
impl CausalEdge64 {
/// Pack a WeightEdge into a compact u64.
#[inline]
pub fn pack(edge: &WeightEdge) -> Self {
let block = (edge.block.unwrap_or(0) & 0x3F) as u64;
let proj = projection_to_u4(&edge.projection) as u64;
let verb = match edge.verb {
Verb::Becomes => 0u64,
Verb::Supports => 1,
Verb::Contradicts => 2,
};
let row = (edge.row_idx as u64) & 0xFFFF;
let l1 = (edge.l1_distance.min(65535) as u64) & 0xFFFF;
let freq = ((edge.truth.frequency * 1023.0).round() as u64) & 0x3FF;
let conf = ((edge.truth.confidence * 1023.0).round() as u64) & 0x3FF;
Self((block << 58) | (proj << 54) | (verb << 52) | (row << 36) | (l1 << 20) | (freq << 10) | conf)
}
/// Unpack block number.
#[inline]
pub fn block(self) -> u32 {
((self.0 >> 58) & 0x3F) as u32
}
/// Unpack projection type.
#[inline]
pub fn projection(self) -> Projection {
u4_to_projection(((self.0 >> 54) & 0xF) as u8)
}
/// Unpack verb.
#[inline]
pub fn verb(self) -> Verb {
match (self.0 >> 52) & 0x3 {
0 => Verb::Becomes,
1 => Verb::Supports,
_ => Verb::Contradicts,
}
}
/// Unpack row index.
#[inline]
pub fn row_idx(self) -> u32 {
((self.0 >> 36) & 0xFFFF) as u32
}
/// Unpack L1 distance.
#[inline]
pub fn l1_distance(self) -> u32 {
((self.0 >> 20) & 0xFFFF) as u32
}
/// Unpack NARS frequency.
#[inline]
pub fn frequency(self) -> f32 {
((self.0 >> 10) & 0x3FF) as f32 / 1023.0
}
/// Unpack NARS confidence.
#[inline]
pub fn confidence(self) -> f32 {
(self.0 & 0x3FF) as f32 / 1023.0
}
/// Reconstruct NarsTruth.
#[inline]
pub fn truth(self) -> NarsTruth {
NarsTruth::new(self.frequency(), self.confidence())
}
}
fn projection_to_u4(p: &Projection) -> u8 {
match p {
Projection::Q => 0,
Projection::K => 1,
Projection::V => 2,
Projection::O => 3,
Projection::Gate => 4,
Projection::FfnGate => 5,
Projection::FfnUp => 6,
Projection::FfnDown => 7,
Projection::Embedding => 8,
Projection::Other => 9,
}
}
fn u4_to_projection(v: u8) -> Projection {
match v {
0 => Projection::Q,
1 => Projection::K,
2 => Projection::V,
3 => Projection::O,
4 => Projection::Gate,
5 => Projection::FfnGate,
6 => Projection::FfnUp,
7 => Projection::FfnDown,
8 => Projection::Embedding,
_ => Projection::Other,
}
}
// ============================================================================
// p64 bridge: scaffold edges → Palette64 attention matrix
// ============================================================================
/// Build a p64 `Palette64` from scaffold edges.
///
/// Each unique (block, projection) pair becomes a row in the palette.
/// The row value is the OR-combination of all CausalEdge64 values for that pair.
/// Result: a 64×64 binary attention matrix where `attend(query, gamma)`
/// finds which scaffold blocks match a structural query.
///
/// Synergy with p64:
/// - `palette.attend(query, gamma)` → which reasoning scaffold blocks fire
/// - `palette.nearest_k(query, 8)` → top-8 similar scaffold heads
/// - `HeelPlanes::from_clam_seed` → Base17 fingerprint → p64 → scaffold query
pub fn scaffold_to_palette64(edges: &[WeightEdge]) -> ([u64; 64], Vec<(u32, Projection)>) {
let mut row_map: HashMap<(u32, u8), u64> = HashMap::new();
let mut keys: Vec<(u32, u8)> = Vec::new();
for edge in edges {
let block = edge.block.unwrap_or(0);
let proj = projection_to_u4(&edge.projection);
let key = (block, proj);
let packed = CausalEdge64::pack(edge).0;
let entry = row_map.entry(key).or_insert_with(|| {
keys.push(key);
0u64
});
*entry |= packed;
}
// Sort by block then projection for deterministic layout
keys.sort();
keys.truncate(64);
let mut rows = [0u64; 64];
let mut labels = Vec::with_capacity(keys.len());
for (i, &(block, proj)) in keys.iter().enumerate() {
rows[i] = row_map[&(block, proj)];
labels.push((block, u4_to_projection(proj)));
}
(rows, labels)
}
// ============================================================================
// p64 Palette3D bridge: scaffold → 8-layer reasoning circuit
// ============================================================================
/// Map projection shifts to p64 predicate layers via SPO = QKV.
///
/// ```text
/// CausalEdge64 SPO mapping: S = Q, P = K, O = O
/// Pearl CausalMask: Q+O active, K inactive = CausalMask::SO (0b101)
///
/// Projection → HEEL plane SPO role Rationale
/// ────────── ────────── ──────── ─────────
/// Q shift → CAUSES (0) Subject queries changed → causation
/// O shift → ENABLES (1) Object synthesis changed → enabling
/// K stable → SUPPORTS (2) Predicate keys preserved → supporting
/// V shift → REFINES (4) — retrieval shifted → refinement
/// Gate → CONTRADICTS(3)— router change → tension
/// FfnUp/Down → ABSTRACTS (5) — FFN capacity → abstraction
/// FfnGate → GROUNDS (6) — FFN rewiring → grounding
/// Embedding → BECOMES (7) — vocabulary → identity
/// ```
///
/// The 4 measured layers (CAUSES, ENABLES, REFINES, ABSTRACTS) come from
/// the 4 diffs. The 4 deduced layers (SUPPORTS, CONTRADICTS, GROUNDS,
/// BECOMES) emerge from intersection/negation in `scaffold_to_palette3d_layers`.
pub fn projection_to_predicate(proj: &Projection) -> usize {
match proj {
Projection::Q => 0, // CAUSES (Subject in SPO)
Projection::O => 1, // ENABLES (Object in SPO)
Projection::K => 2, // SUPPORTS (Predicate in SPO — stable = supporting)
Projection::V => 4, // REFINES
Projection::Gate => 3, // CONTRADICTS
Projection::FfnUp => 5, // ABSTRACTS
Projection::FfnDown => 5, // ABSTRACTS (same layer)
Projection::FfnGate => 6, // GROUNDS
Projection::Embedding => 7, // BECOMES
Projection::Other => 7, // BECOMES
}
}
/// Build 8 HEEL planes from scaffold edges — one plane per predicate/projection.
///
/// Each HEEL plane is a 64-bit pattern where bit `b` = 1 means block `b`
/// had significant shift in that projection type. The 8 HEELs expand
/// via golden rotation to a full 64×64 Palette64, which then stacks
/// into a Palette3D for multi-predicate reasoning.
///
/// ```text
/// WeightEdge[]
/// → group by projection → 8 × u64 bitmasks (block shifted?)
/// → HeelPlanes::new(planes)
/// → .expand() → Palette64 (64×64)
/// → Palette3D::new([8 layers], ThinkingStyle::ANALYTICAL)
/// → .infer(block) → which scaffold blocks fire
/// → HHTL cascade → 256×256 fine-grain distances
/// ```
pub fn scaffold_to_heel_planes(edges: &[WeightEdge], shift_threshold: f64) -> [u64; 8] {
// Count shifts per (block, projection)
let mut block_proj_shifts: HashMap<(u32, u8), (usize, usize)> = HashMap::new();
for edge in edges {
let block = edge.block.unwrap_or(0);
if block >= 64 {
continue;
} // p64 only has 64 rows
let proj = projection_to_u4(&edge.projection);
let entry = block_proj_shifts.entry((block, proj)).or_insert((0, 0));
entry.0 += 1; // shifted
entry.1 += 1; // total (all edges here are shifted by definition)
}
// Also count stable rows (rows NOT in edges) — we need total per (block, proj)
// Since edges only contain shifted rows, we approximate: if a block has ANY
// edges for a projection, mark that bit in the corresponding HEEL plane.
let mut planes = [0u64; 8];
for (&(block, proj), &(shifted, _total)) in &block_proj_shifts {
if block >= 64 {
continue;
}
// Map projection to predicate layer
let predicate = projection_to_predicate(&u4_to_projection(proj));
if predicate < 8 {
// Set this block's bit in the corresponding HEEL plane
planes[predicate] |= 1u64 << block;
}
}
planes
}
/// Build a full Palette3D reasoning circuit from four diff runs.
///
/// The 4 diffs ARE the 4 deduction rules — each measures one predicate:
///
/// ```text
/// MEASURED (from data):
/// base→v1: CAUSES "What does Claude distillation cause?"
/// base→v2: ENABLES "What does the second iteration enable?"
/// v1→v2: REFINES "Which heads converged (refined)?"
/// 9B diff: ABSTRACTS "Is the pattern scale-invariant (abstract)?"
///
/// DEDUCED (from intersection/negation of measured):
/// SUPPORTS = CAUSES ∩ ENABLES (both distillations agree)
/// CONTRADICTS = v1→v2 sign flips (head was overcorrected)
/// GROUNDS = SUPPORTS ∩ ABSTRACTS (consistent AND scale-invariant)
/// BECOMES = ENABLES \ CAUSES (novel heads, not in first distillation)
/// ```
///
/// SPO mapping in CausalEdge64: S=Q, P=K, O=O.
/// Q+O shifted, K stable = CausalMask::SO (0b101) = the reasoning scaffold.
///
/// Returns 8 `[u64; 64]` palettes (one per predicate layer) ready for Palette3D.
pub fn scaffold_to_palette3d_layers(
edges_v1: &[WeightEdge], edges_v2: &[WeightEdge], edges_v1v2: &[WeightEdge], edges_9b: &[WeightEdge],
) -> [[u64; 64]; 8] {
// scaffold_to_heel_planes maps projections → predicate layers:
// plane[0] = CAUSES (from Q projections)
// plane[1] = ENABLES (from O projections)
// plane[2] = SUPPORTS (from K projections — will be inverted)
// plane[3] = CONTRADICTS (from Gate projections)
// plane[4] = REFINES (from V projections)
// plane[5] = ABSTRACTS (from FFN projections)
// plane[6] = GROUNDS (from FfnGate)
// plane[7] = BECOMES (from Embedding/Other)
let heels_v1 = scaffold_to_heel_planes(edges_v1, 0.3);
let heels_v2 = scaffold_to_heel_planes(edges_v2, 0.3);
let heels_v1v2 = scaffold_to_heel_planes(edges_v1v2, 0.3);
let heels_9b = scaffold_to_heel_planes(edges_9b, 0.3);
let mut layers = [[0u64; 64]; 8];
// ── 4 MEASURED layers (directly from diffs) ──
//
// Layer 0 CAUSES: base→v1 Q+O topology (what distillation changed)
let causes = heels_v1[0] | heels_v1[1]; // Q shifted OR O shifted
//
// Layer 1 ENABLES: base→v2 Q+O topology (what second iteration changed)
let enables = heels_v2[0] | heels_v2[1];
//
// Layer 4 REFINES: v1→v2 convergence (which heads stabilized)
// Heads in v1→v2 with LOW shift = converged = refined
// Heads in v1→v2 with HIGH shift = still moving = not refined
// Invert: bits NOT set in v1v2 means the head converged
let still_moving = heels_v1v2[0] | heels_v1v2[1];
let refines = causes & !still_moving; // caused in v1, converged by v2
//
// Layer 5 ABSTRACTS: 9B diff topology (scale-invariant = abstract)
let abstracts_9b = heels_9b[0] | heels_9b[1]; // Q+O from 9B
// ── 4 DEDUCED layers (from intersection/negation) ──
//
// Layer 2 SUPPORTS: CAUSES ∩ ENABLES (both distillations agree)
let supports = causes & enables;
//
// Layer 3 CONTRADICTS: v1→v2 heads that CAUSES but v2 reversed
// = blocks in CAUSES that are NOT in ENABLES but ARE still moving
let contradicts = causes & !enables & still_moving;
//
// Layer 6 GROUNDS: SUPPORTS ∩ ABSTRACTS (consistent AND scale-invariant)
let grounds = supports & abstracts_9b;
//
// Layer 7 BECOMES: ENABLES \ CAUSES (novel heads, emerged in second iteration)
let becomes = enables & !causes;
let heel_bits = [
causes, // 0 CAUSES
enables, // 1 ENABLES
supports, // 2 SUPPORTS
contradicts, // 3 CONTRADICTS
refines, // 4 REFINES
abstracts_9b, // 5 ABSTRACTS
grounds, // 6 GROUNDS
becomes, // 7 BECOMES
];
// Expand each HEEL to 64 rows via golden rotation
for (layer_idx, &bits) in heel_bits.iter().enumerate() {
for row in 0..64 {
let octave = row / 8;
let rotation = (octave as u32) * 39; // GOLDEN_SHIFT_64
layers[layer_idx][row] = bits.rotate_left(rotation);
}
}
layers
}
/// Build Palette3D from 2 diffs only: base→v2 (27B) + base→dist (9B).
///
/// v2 supercedes v1 (14K samples vs 3K). Two diffs suffice:
///
/// ```text
/// MEASURED:
/// CAUSES = base→v2 Q|O shifts (what did distillation change?)
/// ABSTRACTS = 9B Q|O shifts (which of those survive at 9B?)
///
/// DEDUCED:
/// ENABLES = CAUSES (single distillation: causes=enables)
/// SUPPORTS = CAUSES ∩ ABSTRACTS (both scales agree)
/// CONTRADICTS = CAUSES \ ABSTRACTS (27B-only = capacity-dependent)
/// REFINES = 0 (no v1→v2 available)
/// GROUNDS = SUPPORTS (= SUPPORTS with 2 diffs)
/// BECOMES = ABSTRACTS \ CAUSES (9B-only, not in 27B)
/// ```
pub fn scaffold_to_palette3d_from_2_diffs(edges_27b: &[WeightEdge], edges_9b: &[WeightEdge]) -> [[u64; 64]; 8] {
let heels_27b = scaffold_to_heel_planes(edges_27b, 0.3);
let heels_9b = scaffold_to_heel_planes(edges_9b, 0.3);
// MEASURED
let causes = heels_27b[0] | heels_27b[1]; // Q|O from base→v2
let abstracts = heels_9b[0] | heels_9b[1]; // Q|O from 9B
// DEDUCED
let enables = causes; // single distillation
let supports = causes & abstracts; // both scales agree
let contradicts = causes & !abstracts; // 27B-only (capacity-dependent)
let refines = 0u64; // no v1→v2
let grounds = supports; // = supports with 2 diffs
let becomes = abstracts & !causes; // 9B-only novel heads
let heel_bits = [
causes, // 0 CAUSES
enables, // 1 ENABLES
supports, // 2 SUPPORTS
contradicts, // 3 CONTRADICTS
refines, // 4 REFINES
abstracts, // 5 ABSTRACTS
grounds, // 6 GROUNDS
becomes, // 7 BECOMES
];
let mut layers = [[0u64; 64]; 8];
for (layer_idx, &bits) in heel_bits.iter().enumerate() {
for row in 0..64 {
let octave = row / 8;
let rotation = (octave as u32) * 39;
layers[layer_idx][row] = bits.rotate_left(rotation);
}
}
layers
}
// ============================================================================
// Quality scoring: GOOD / BAD / UNCERTAIN per attention head
// ============================================================================
/// Quality classification of a shifted attention head.
///
/// Determined by cross-validating 4 diffs: v1 is the control experiment.
/// v1 vs v2 separates intentional refinement from overfitting.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HeadQuality {
/// v1 ∩ v2 ∩ 9B: all three agree. Scale-invariant, consistent across
/// both distillation rounds. This IS the reasoning scaffold.
Good,
/// v2 \ v1: only in the aggressive second round, not in the conservative first.
/// v2 lost 7.2% MMLU-Pro → these are the knowledge-destruction heads.
Bad,
/// v1 ∩ v2 \ 9B: consistent across rounds but not scale-invariant.
/// Could be 27B-specific reasoning OR capacity-dependent overfitting.
Uncertain,
/// v1 \ v2: present in first round but reverted in second.
/// v2 corrected an overcorrection. Good sign for v2.
Reverted,
}
/// Per-head quality scores from 4-diff cross-validation.
#[derive(Clone, Debug)]
pub struct QualityMap {
/// (block, projection_name) → quality classification + NARS truth.
pub heads: HashMap<(u32, String), (HeadQuality, NarsTruth)>,
/// Summary counts.
pub good: usize,
pub bad: usize,
pub uncertain: usize,
pub reverted: usize,
}
/// Score every shifted head as GOOD/BAD/UNCERTAIN using 4-diff cross-validation.
///
/// ```text
/// v1 = conservative (3K samples), v2 = aggressive (14K samples), 9B = scale test
///
/// GOOD: v1 ∩ v2 ∩ 9B (all agree → reasoning scaffold)
/// BAD: v2 \ v1 (only aggressive round → overfit/knowledge-loss)
/// UNCERTAIN: v1 ∩ v2 \ 9B (consistent but not scale-invariant)
/// REVERTED: v1 \ v2 (first round overcorrected, second fixed it)
/// ```
///
/// The NARS truth per head is the cross-validated frequency from all diffs
/// where the head appeared, giving confidence in the classification.
pub fn score_head_quality(edges_v1: &[WeightEdge], edges_v2: &[WeightEdge], edges_9b: &[WeightEdge]) -> QualityMap {
// Collect which (block, proj) pairs appear in each diff
let heads_v1 = head_set(edges_v1);
let heads_v2 = head_set(edges_v2);
let heads_9b = head_set(edges_9b);
let mut heads = HashMap::new();
let mut good = 0;
let mut bad = 0;
let mut uncertain = 0;
let mut reverted = 0;
// All heads from any diff
let all_heads: std::collections::BTreeSet<(u32, String)> = heads_v1
.keys()
.chain(heads_v2.keys())
.chain(heads_9b.keys())
.cloned()
.collect();
for key in &all_heads {
let in_v1 = heads_v1.contains_key(key);
let in_v2 = heads_v2.contains_key(key);
let in_9b = heads_9b.contains_key(key);
let quality = if in_v1 && in_v2 && in_9b {
good += 1;
HeadQuality::Good
} else if in_v2 && !in_v1 {
bad += 1;
HeadQuality::Bad
} else if in_v1 && !in_v2 {
reverted += 1;
HeadQuality::Reverted
} else {
// v1 ∩ v2 but not 9B, or 9B-only, or other combinations
uncertain += 1;
HeadQuality::Uncertain
};
// NARS truth: aggregate evidence from all diffs where this head appeared
let mut truth = NarsTruth::new(0.5, 0.0);
for (src, map) in [("v1", &heads_v1), ("v2", &heads_v2), ("9b", &heads_9b)] {
if let Some(&(f, c)) = map.get(key) {
truth = nars_revision(truth, NarsTruth::new(f, c));
}
}
heads.insert(key.clone(), (quality, truth));
}
QualityMap {
heads,
good,
bad,
uncertain,
reverted,
}
}
/// Extract (block, proj) → (frequency, confidence) from edges via cluster_by_head.
fn head_set(edges: &[WeightEdge]) -> HashMap<(u32, String), (f32, f32)> {
let clusters = cluster_by_head(edges);
clusters
.into_iter()
.map(|((block, proj), (count, total, _mean_l1))| {
let f = if total > 0 { count as f32 / total as f32 } else { 0.0 };
let c = (1.0 - 1.0 / (1.0 + total as f32)).min(0.99);
((block, proj), (f, c))
})
.collect()
}
/// Build Palette3D with quality-aware bit setting.
///
/// Only GOOD heads get full palette bits. BAD heads get zero.
/// UNCERTAIN heads get bits only in non-critical layers (REFINES, ABSTRACTS).
/// This filters the Palette3D to be a QUALITY prior, not just a topology map.
///
/// The result can drive NARS self-reinforcement LoRA:
/// 1. Static: Palette3D as prior (which heads to reinforce)
/// 2. Dynamic: run inference → NARS score outputs → update truth per head
/// 3. LoRA: train δW guided by Palette3D mask × NARS confidence
/// - GOOD heads with high NARS conf → reinforce (increase LoRA rank)
/// - BAD heads with high conf → suppress (LoRA rank → 0)
/// - UNCERTAIN heads → let NARS feedback decide over iterations
pub fn scaffold_to_palette3d_quality_filtered(
edges_v1: &[WeightEdge], edges_v2: &[WeightEdge], edges_v1v2: &[WeightEdge], edges_9b: &[WeightEdge],
) -> ([[u64; 64]; 8], QualityMap) {
let quality = score_head_quality(edges_v1, edges_v2, edges_9b);
let heels_v1 = scaffold_to_heel_planes(edges_v1, 0.3);
let heels_v2 = scaffold_to_heel_planes(edges_v2, 0.3);
let heels_v1v2 = scaffold_to_heel_planes(edges_v1v2, 0.3);
let heels_9b = scaffold_to_heel_planes(edges_9b, 0.3);
// Build quality masks: which blocks are GOOD vs BAD
let mut good_mask = 0u64;
let mut bad_mask = 0u64;
for ((block, _proj), (q, _truth)) in &quality.heads {
if *block >= 64 {
continue;
}
match q {
HeadQuality::Good => good_mask |= 1u64 << block,
HeadQuality::Bad => bad_mask |= 1u64 << block,
_ => {}
}
}
// Uncertain blocks: not explicitly good or bad
let uncertain_mask = !(good_mask | bad_mask);
// MEASURED (same as 4-diff version)
let causes = heels_v1[0] | heels_v1[1];
let enables = heels_v2[0] | heels_v2[1];
let still_moving = heels_v1v2[0] | heels_v1v2[1];
let abstracts_9b = heels_9b[0] | heels_9b[1];
// DEDUCED (same algebra)
let refines = causes & !still_moving;
let supports = causes & enables;
let contradicts = causes & !enables & still_moving;
let grounds = supports & abstracts_9b;
let becomes = enables & !causes;
// QUALITY FILTER: mask layers by head quality
// Critical layers (CAUSES, ENABLES, SUPPORTS, GROUNDS): only GOOD bits
// Informational layers (REFINES, ABSTRACTS): GOOD + UNCERTAIN
// Tension layers (CONTRADICTS, BECOMES): unfiltered (they ARE the signal)
let heel_bits = [
causes & good_mask, // 0 CAUSES: only good
enables & good_mask, // 1 ENABLES: only good
supports & good_mask, // 2 SUPPORTS: only good
contradicts, // 3 CONTRADICTS: unfiltered
refines & (good_mask | uncertain_mask), // 4 REFINES: good + uncertain
abstracts_9b & (good_mask | uncertain_mask), // 5 ABSTRACTS: good + uncertain
grounds & good_mask, // 6 GROUNDS: only good
becomes, // 7 BECOMES: unfiltered
];
let mut layers = [[0u64; 64]; 8];
for (layer_idx, &bits) in heel_bits.iter().enumerate() {
for row in 0..64 {
let octave = row / 8;
let rotation = (octave as u32) * 39;
layers[layer_idx][row] = bits.rotate_left(rotation);
}
}
(layers, quality)
}
// ============================================================================
// NARS self-reinforcement LoRA — feedback loop framework
// ============================================================================
/// Per-head NARS belief updated by inference feedback.
///
/// Static analysis gives the prior (from weight diffs).
/// Each inference run updates the belief: did this head's contribution
/// improve or degrade output quality?
///
/// After N inference rounds, heads with high frequency + high confidence
/// → reinforce via LoRA. Heads with low frequency + high confidence
/// → suppress. Uncertain heads → keep exploring.
#[derive(Clone, Debug)]
pub struct NarsHeadBelief {
/// (block, projection) → quality prior + dynamic truth.
pub beliefs: HashMap<(u32, String), HeadBelief>,
}
/// One head's belief state in the NARS learning loop.
#[derive(Clone, Debug)]
pub struct HeadBelief {
/// Static prior from weight-diff quality scoring.
pub prior: HeadQuality,
/// Dynamic truth from inference feedback. Starts at prior, updated each round.
pub truth: NarsTruth,
/// Number of inference rounds that updated this belief.
pub rounds: u32,
/// Recommended LoRA action based on current truth.
pub action: LoraAction,
}
/// What the NARS loop recommends for a head's LoRA rank.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LoraAction {
/// High freq + high conf → increase LoRA rank for this head.
Reinforce,
/// Low freq + high conf → set LoRA rank to 0 (suppress).
Suppress,
/// Low conf → keep exploring, don't commit yet.
Explore,
}
impl NarsHeadBelief {
/// Initialize from static quality map (the prior).
pub fn from_quality_map(qm: &QualityMap) -> Self {
let mut beliefs = HashMap::new();
for (key, (quality, truth)) in &qm.heads {
let action = match quality {
HeadQuality::Good => LoraAction::Reinforce,
HeadQuality::Bad => LoraAction::Suppress,
_ => LoraAction::Explore,
};
beliefs.insert(
key.clone(),
HeadBelief {
prior: *quality,
truth: *truth,
rounds: 0,
action,
},
);
}
Self { beliefs }
}
/// Update beliefs after one inference round.
///
/// `feedback`: (block, projection) → did this head help? (frequency 0..1)
/// High frequency = head contributed to correct output.
/// Low frequency = head degraded output.
///
/// This is where static analysis meets dynamic validation:
/// a GOOD-prior head that consistently helps → Reinforce with high conf.
/// a GOOD-prior head that hurts → truth drops → eventually Explore/Suppress.
/// a BAD-prior head that actually helps → truth rises → eventually Reinforce.
pub fn update(&mut self, feedback: &HashMap<(u32, String), f32>) {
for (key, belief) in &mut self.beliefs {
if let Some(&quality_score) = feedback.get(key) {
let evidence = NarsTruth::new(quality_score, 0.8);
belief.truth = nars_revision(belief.truth, evidence);
belief.rounds += 1;
// Update action based on revised truth
belief.action = if belief.truth.confidence > 0.7 {
if belief.truth.frequency > 0.6 {
LoraAction::Reinforce
} else if belief.truth.frequency < 0.3 {
LoraAction::Suppress
} else {
LoraAction::Explore
}
} else {
LoraAction::Explore // not enough confidence yet
};
}
}
}
/// Generate LoRA rank recommendations per head.
///
/// Returns (block, projection, rank) where rank is 0 (suppress),
/// 4/8/16 (explore), or 32/64 (reinforce).
pub fn lora_ranks(&self, max_rank: u32) -> Vec<(u32, String, u32)> {
let mut ranks = Vec::new();
for ((block, proj), belief) in &self.beliefs {
let rank = match belief.action {
LoraAction::Suppress => 0,
LoraAction::Explore => max_rank / 4,
LoraAction::Reinforce => {
// Scale rank by NARS confidence: higher conf → higher rank
let scale = belief.truth.confidence.min(0.99);
((max_rank as f32) * scale) as u32
}
};
ranks.push((*block, proj.clone(), rank));
}
ranks.sort_by(|a, b| b.2.cmp(&a.2)); // highest rank first
ranks
}
}
// ============================================================================
// Palette3D attention overlay — structural restoration at inference time
// ============================================================================
/// Volatility score per (block, projection) from cross-validated diffs.
///
/// A weight is volatile if it shifted in multiple independent diffs.
/// The score is the NARS-revised frequency across all diffs for that
/// (block, projection) combination.
#[derive(Clone, Debug)]
pub struct VolatilityMap {
/// (block, projection) → NARS truth from cross-validated diffs.
pub scores: HashMap<(u32, String), NarsTruth>,
/// Blocks classified as scaffold (Q+O shifted, K stable).
pub scaffold_blocks: Vec<u32>,
/// Blocks classified as scale-invariant (present in both 27B and 9B).
pub scale_invariant: Vec<u32>,
}
/// Build a volatility map from 4 diff runs.
///
/// Cross-validates: a head is volatile only if it shifted in multiple diffs.
/// Single-diff noise is suppressed by NARS revision across all 4 evidence sources.
pub fn build_volatility_map(
edges_v1: &[WeightEdge], edges_v2: &[WeightEdge], edges_v1v2: &[WeightEdge], edges_9b: &[WeightEdge],
stats: &[(&str, &DiffStats)],
) -> VolatilityMap {
// NARS revision across all diffs per projection
let revised = revise_across_diffs(stats);
// Per-head volatility: count how many diffs this (block, proj) appears in
let mut head_evidence: HashMap<(u32, String), Vec<NarsTruth>> = HashMap::new();
for (label, diff_edges) in [("v1", edges_v1), ("v2", edges_v2), ("v1v2", edges_v1v2), ("9b", edges_9b)] {
let clusters = cluster_by_head(diff_edges);
for ((block, proj), (count, total, mean_l1)) in &clusters {
let f = if *total > 0 { *count as f32 / *total as f32 } else { 0.0 };
let c = (1.0 - 1.0 / (1.0 + *total as f32)).min(0.99);
head_evidence
.entry((*block, proj.clone()))
.or_default()
.push(NarsTruth::new(f, c));
}
}
// Revise per-head evidence across all diffs
let mut scores = HashMap::new();
for (key, truths) in &head_evidence {
let mut revised = NarsTruth::new(0.5, 0.0);
for &t in truths {
revised = nars_revision(revised, t);
}
scores.insert(key.clone(), revised);
}
// Scaffold detection
let scaffold_v1 = find_reasoning_scaffold(edges_v1, 0.3);
let scaffold_v2 = find_reasoning_scaffold(edges_v2, 0.3);
let scaffold_9b = find_reasoning_scaffold(edges_9b, 0.3);
let scale_invariant: Vec<u32> = scaffold_v1
.iter()
.filter(|b| scaffold_9b.contains(b))
.cloned()
.collect();
VolatilityMap {
scores,
scaffold_blocks: scaffold_v1,
scale_invariant,
}
}
/// Apply Palette3D as attention overlay.
///
/// Given a block's attention scores (Q×K^T), modulate them based on
/// the palette's structural prior. Volatile heads keep full strength.
/// Ballast heads are dampened.
///
/// ```text
/// scores[i] *= if palette_bit(block, i) { 1.0 } else { decay }
/// ```
///
/// `decay`: 0.0 = hard mask (zero ballast), 0.8 = soft dampen.
/// For structural restoration, 0.85-0.95 works well — the Q8_0 weights
/// still carry approximate information, the palette just sharpens contrast.
#[inline]
pub fn apply_palette_overlay(scores: &mut [f32], palette_row: u64, decay: f32) {
// Map score positions to 64 palette bins
let n = scores.len();
let bin_size = (n + 63) / 64;
for (i, score) in scores.iter_mut().enumerate() {
let bin = (i / bin_size).min(63);
if palette_row & (1u64 << bin) == 0 {
// Ballast: dampen
*score *= decay;
}
// Volatile: keep full strength (×1.0, no-op)
}
}
/// ThinkingStyle ordinal for PAL8 serialization.
///
/// Maps to p64::ThinkingStyle constants and lance-graph-contract ThinkingStyles.
/// The ordinal travels with the palette over the Cognitive Highway so the
/// consumer (Blumenstrauss) knows which combine/contra mode to use.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum PaletteStyle {
Analytical = 0, // tight intersection, contradiction kills
Creative = 1, // wide union, contradiction ignored
Focused = 2, // single causal chain
Integrative = 3, // majority vote, contradiction as tension
Divergent = 4, // contradiction inverts (fuel)
Meta = 5, // observes the observation
}
impl PaletteStyle {
fn from_u8(v: u8) -> Self {
match v {
0 => Self::Analytical,
1 => Self::Creative,
2 => Self::Focused,
3 => Self::Integrative,
4 => Self::Divergent,
5 => Self::Meta,
_ => Self::Analytical,
}
}
}
/// Serialize 8 palette layers + style to compact binary.
///
/// Format: "PAL8" magic + style(u8) + 8 × 64 × u64 LE = 4101 bytes.
/// This is the Cognitive Highway payload: ndarray extracts → PAL8 → lance-graph