llmintent 0.9.1__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.
Files changed (78) hide show
  1. llmintent/__init__.py +95 -0
  2. llmintent/activation.py +108 -0
  3. llmintent/analyzer.py +427 -0
  4. llmintent/benchmark/__init__.py +43 -0
  5. llmintent/benchmark/ablation.py +51 -0
  6. llmintent/benchmark/hellaswag.py +203 -0
  7. llmintent/benchmark/retrace_store.py +143 -0
  8. llmintent/benchmark/runner.py +354 -0
  9. llmintent/benchmark/slm_registry.py +37 -0
  10. llmintent/cli.py +498 -0
  11. llmintent/cognitive/__init__.py +15 -0
  12. llmintent/cognitive/ideation.py +49 -0
  13. llmintent/cognitive/identity.py +48 -0
  14. llmintent/cognitive/meta_reasoning.py +49 -0
  15. llmintent/cognitive/orchestrator.py +176 -0
  16. llmintent/cognitive/reasoning.py +50 -0
  17. llmintent/cognitive/types.py +60 -0
  18. llmintent/compaction.py +109 -0
  19. llmintent/embeddings.py +59 -0
  20. llmintent/forward.py +63 -0
  21. llmintent/heighten/__init__.py +47 -0
  22. llmintent/heighten/cot_delta.py +31 -0
  23. llmintent/heighten/extreme.py +191 -0
  24. llmintent/heighten/focus.py +129 -0
  25. llmintent/heighten/framework.py +195 -0
  26. llmintent/heighten/intervention.py +176 -0
  27. llmintent/heighten/retrace.py +119 -0
  28. llmintent/heighten/types.py +125 -0
  29. llmintent/jspace/__init__.py +26 -0
  30. llmintent/jspace/decode.py +103 -0
  31. llmintent/jspace/decompose.py +85 -0
  32. llmintent/jspace/regimes.py +96 -0
  33. llmintent/jspace/trace.py +169 -0
  34. llmintent/jspace/transport.py +74 -0
  35. llmintent/kernels/__init__.py +29 -0
  36. llmintent/kernels/barlow.py +130 -0
  37. llmintent/kernels/kl_kernel.py +81 -0
  38. llmintent/layers.py +157 -0
  39. llmintent/live/__init__.py +38 -0
  40. llmintent/live/activation_stream.py +150 -0
  41. llmintent/live/api.py +125 -0
  42. llmintent/live/generate.py +139 -0
  43. llmintent/live/pipeline.py +225 -0
  44. llmintent/live/registry.py +87 -0
  45. llmintent/live/session.py +128 -0
  46. llmintent/live/types.py +106 -0
  47. llmintent/live/ui.py +307 -0
  48. llmintent/live/viz_panel.py +413 -0
  49. llmintent/metrics.py +52 -0
  50. llmintent/models.py +136 -0
  51. llmintent/morphemes.py +110 -0
  52. llmintent/poles.py +45 -0
  53. llmintent/projection.py +51 -0
  54. llmintent/query/__init__.py +19 -0
  55. llmintent/query/concept_query.py +237 -0
  56. llmintent/query/feature_space.py +116 -0
  57. llmintent/retracement/__init__.py +33 -0
  58. llmintent/retracement/ablation.py +131 -0
  59. llmintent/retracement/blocks.py +77 -0
  60. llmintent/retracement/config.py +67 -0
  61. llmintent/retracement/perplexity.py +137 -0
  62. llmintent/retracement/transformer.py +210 -0
  63. llmintent/steering.py +122 -0
  64. llmintent/svd.py +28 -0
  65. llmintent/trajectory.py +186 -0
  66. llmintent/viz/__init__.py +35 -0
  67. llmintent/viz/animate.py +203 -0
  68. llmintent/viz/backend.py +35 -0
  69. llmintent/viz/correlation.py +131 -0
  70. llmintent/viz/maps.py +181 -0
  71. llmintent/viz/suite.py +185 -0
  72. llmintent/weight_semantics.py +109 -0
  73. llmintent-0.9.1.dist-info/METADATA +970 -0
  74. llmintent-0.9.1.dist-info/RECORD +78 -0
  75. llmintent-0.9.1.dist-info/WHEEL +5 -0
  76. llmintent-0.9.1.dist-info/entry_points.txt +2 -0
  77. llmintent-0.9.1.dist-info/licenses/LICENSE +21 -0
  78. llmintent-0.9.1.dist-info/top_level.txt +1 -0
llmintent/__init__.py ADDED
@@ -0,0 +1,95 @@
1
+ """LLMIntent — semantic extraction and intent analysis for transformer LLMs."""
2
+
3
+ from llmintent.activation import activation_summary, identify_activation_layers
4
+ from llmintent.analyzer import AnalysisReport, LLMIntentAnalyzer
5
+ from llmintent.compaction import CompactionAnalyzer
6
+ from llmintent.cognitive import CognitiveModuleProfile, build_cognitive_module_profile
7
+ from llmintent.heighten import (
8
+ FocusMetrics,
9
+ HeightenedReasoningFramework,
10
+ HeightenedReasoningResult,
11
+ RetraceMode,
12
+ heighten_reasoning,
13
+ )
14
+ from llmintent.jspace import (
15
+ IntentTrace,
16
+ TransportMaps,
17
+ build_intent_trace,
18
+ classify_layer_regimes,
19
+ fit_transport_maps,
20
+ )
21
+ from llmintent.kernels import minimize_twin_barlow, per_layer_kl_profile
22
+ from llmintent.layers import build_layer_correspondence_map, summarize_layer_bands
23
+ from llmintent.metrics import calculate_sso_score, kl_divergence, shannon_entropy
24
+ from llmintent.query import ConceptQueryResult, query_concept_in_trajectory, query_concepts_batch
25
+ from llmintent.trajectory import TrajectoryMapping, build_trajectory_mapping
26
+ from llmintent.viz import VisualizationSuite
27
+ from llmintent.benchmark import (
28
+ AblationCondition,
29
+ BenchmarkRunConfig,
30
+ HellaSwagBenchmarkRunner,
31
+ RetraceStore,
32
+ list_slms,
33
+ parse_conditions,
34
+ prepare_slm_comparison,
35
+ )
36
+ from llmintent.live import (
37
+ LiveIntentPipeline,
38
+ LiveSessionConfig,
39
+ list_live_models,
40
+ )
41
+ from llmintent.retracement import (
42
+ RetracementConfig,
43
+ RetracementMode,
44
+ RetracementTransformer,
45
+ run_retracement_ablation,
46
+ )
47
+
48
+ __all__ = [
49
+ "AnalysisReport",
50
+ "CognitiveModuleProfile",
51
+ "AblationCondition",
52
+ "BenchmarkRunConfig",
53
+ "CompactionAnalyzer",
54
+ "ConceptQueryResult",
55
+ "FocusMetrics",
56
+ "HellaSwagBenchmarkRunner",
57
+ "HeightenedReasoningFramework",
58
+ "HeightenedReasoningResult",
59
+ "IntentTrace",
60
+ "LLMIntentAnalyzer",
61
+ "LiveIntentPipeline",
62
+ "LiveSessionConfig",
63
+ "RetraceStore",
64
+ "RetraceMode",
65
+ "RetracementConfig",
66
+ "RetracementMode",
67
+ "RetracementTransformer",
68
+ "TrajectoryMapping",
69
+ "TransportMaps",
70
+ "VisualizationSuite",
71
+ "activation_summary",
72
+ "build_cognitive_module_profile",
73
+ "build_intent_trace",
74
+ "build_layer_correspondence_map",
75
+ "build_trajectory_mapping",
76
+ "calculate_sso_score",
77
+ "classify_layer_regimes",
78
+ "fit_transport_maps",
79
+ "heighten_reasoning",
80
+ "identify_activation_layers",
81
+ "kl_divergence",
82
+ "minimize_twin_barlow",
83
+ "list_live_models",
84
+ "list_slms",
85
+ "parse_conditions",
86
+ "prepare_slm_comparison",
87
+ "per_layer_kl_profile",
88
+ "query_concept_in_trajectory",
89
+ "query_concepts_batch",
90
+ "run_retracement_ablation",
91
+ "shannon_entropy",
92
+ "summarize_layer_bands",
93
+ ]
94
+
95
+ __version__ = "0.9.1"
@@ -0,0 +1,108 @@
1
+ """Identify layers of peak activation and inference pivots."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ import torch
8
+
9
+ from llmintent.forward import forward_hidden_states
10
+ from llmintent.metrics import cosine_intensity
11
+ from llmintent.models import ModelBundle
12
+ from llmintent.poles import build_numerical_pole
13
+
14
+
15
+ def identify_activation_layers(
16
+ bundle: ModelBundle,
17
+ prompt: str,
18
+ *,
19
+ layer_stats: pd.DataFrame | None = None,
20
+ entropy: list[float] | None = None,
21
+ occupancy: list[float] | None = None,
22
+ position: int = -1,
23
+ ) -> dict[str, int]:
24
+ """
25
+ Detect key activation layers for a prompt.
26
+
27
+ Returns layer indices for:
28
+ - inference_pivot: largest entropy drop (maturation point)
29
+ - workspace_peak: max J-space occupancy in workspace band
30
+ - motor_onset: where decode aligns with final layer output
31
+ - intensity_peak: max numerical-pole cosine similarity (notebook metric)
32
+ """
33
+ _, states = forward_hidden_states(bundle, prompt)
34
+ num_layers = len(states)
35
+
36
+ if entropy is None:
37
+ from llmintent.steering import get_entropy_trajectory
38
+
39
+ ent_df = get_entropy_trajectory(bundle, prompt)
40
+ entropy = ent_df["entropy"].tolist()
41
+
42
+ ent = np.array(entropy, dtype=float)
43
+ ent_diff = np.diff(ent)
44
+ inference_pivot = int(np.argmin(ent_diff) + 1) if len(ent_diff) else 0
45
+
46
+ if occupancy is None:
47
+ from llmintent.jspace.decompose import jspace_occupancy
48
+
49
+ occupancy = [
50
+ float(jspace_occupancy(bundle, states[i][0, position, :]))
51
+ for i in range(num_layers)
52
+ ]
53
+ occ = np.array(occupancy, dtype=float)
54
+
55
+ # Workspace band ~ middle third
56
+ ws_start = num_layers // 3
57
+ ws_end = (2 * num_layers) // 3
58
+ ws_slice = occ[ws_start : ws_end + 1]
59
+ workspace_peak = ws_start + int(np.argmax(ws_slice)) if len(ws_slice) else ws_start
60
+
61
+ if layer_stats is not None and "motor_alignment" in layer_stats.columns:
62
+ motor_onset = int(layer_stats["motor_alignment"].idxmax())
63
+ else:
64
+ motor_onset = max(0, num_layers - 2)
65
+
66
+ pole = build_numerical_pole(bundle)
67
+ intensities = [
68
+ cosine_intensity(states[i][0, position, :], pole.to(bundle.device))
69
+ for i in range(num_layers)
70
+ ]
71
+ intensity_peak = int(np.argmax(intensities))
72
+
73
+ return {
74
+ "inference_pivot": inference_pivot,
75
+ "workspace_peak": workspace_peak,
76
+ "motor_onset": motor_onset,
77
+ "intensity_peak": intensity_peak,
78
+ }
79
+
80
+
81
+ def activation_summary(
82
+ bundle: ModelBundle,
83
+ prompt: str,
84
+ *,
85
+ position: int = -1,
86
+ ) -> pd.DataFrame:
87
+ """Per-layer activation metrics for layer correspondence mapping."""
88
+ from llmintent.jspace.decompose import jspace_occupancy
89
+ from llmintent.steering import get_entropy_trajectory
90
+
91
+ _, states = forward_hidden_states(bundle, prompt)
92
+ ent_df = get_entropy_trajectory(bundle, prompt)
93
+ pole = build_numerical_pole(bundle)
94
+
95
+ rows: list[dict] = []
96
+ for i, state in enumerate(states):
97
+ hidden = state[0, position, :]
98
+ rows.append(
99
+ {
100
+ "layer": i,
101
+ "entropy": float(ent_df.loc[i, "entropy"]),
102
+ "occupancy": float(jspace_occupancy(bundle, hidden)),
103
+ "intensity": cosine_intensity(hidden, pole.to(bundle.device)),
104
+ }
105
+ )
106
+ df = pd.DataFrame(rows)
107
+ df["entropy_drop"] = -df["entropy"].diff().fillna(0)
108
+ return df
llmintent/analyzer.py ADDED
@@ -0,0 +1,427 @@
1
+ """High-level facade combining notebook extraction workflows."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gc
6
+ from collections import Counter
7
+ from dataclasses import dataclass, field
8
+
9
+ import pandas as pd
10
+ import torch
11
+
12
+ from llmintent.activation import activation_summary, identify_activation_layers
13
+ from llmintent.compaction import CompactionAnalyzer
14
+ from llmintent.embeddings import EmbeddingSpace, load_glove_gensim
15
+ from llmintent.cognitive import CognitiveModuleProfile, build_cognitive_module_profile
16
+ from llmintent.jspace.trace import IntentTrace, build_intent_trace
17
+ from llmintent.jspace.transport import TransportMaps, fit_transport_maps
18
+ from llmintent.layers import build_layer_correspondence_map, summarize_layer_bands
19
+ from llmintent.models import ModelBundle, get_transformer_layers, load_model_bundle
20
+ from llmintent.morphemes import MorphemeExtractor
21
+ from llmintent.poles import build_glove_poles, build_numerical_pole
22
+ from llmintent.query import ConceptQueryResult, query_concept_in_trajectory, query_concepts_batch
23
+ from llmintent.trajectory import TrajectoryMapping, build_trajectory_mapping
24
+ from llmintent.steering import (
25
+ analyze_steering_intensity,
26
+ calculate_pivot_entropy,
27
+ compare_cot_intensity,
28
+ get_entropy_trajectory,
29
+ run_intensity_sweep,
30
+ run_stress_test,
31
+ )
32
+ from llmintent.weight_semantics import get_block_expertise, get_block_semantics
33
+
34
+
35
+ @dataclass
36
+ class AnalysisReport:
37
+ prompt: str
38
+ model_name: str
39
+ intensity_sweep: pd.DataFrame = field(default_factory=pd.DataFrame)
40
+ entropy_trajectory: pd.DataFrame = field(default_factory=pd.DataFrame)
41
+ pivot_entropy: dict[str, float] = field(default_factory=dict)
42
+ cot_comparison: dict[str, float] = field(default_factory=dict)
43
+ block_semantics: dict[int, dict[str, list[str]]] = field(default_factory=dict)
44
+ compaction: pd.DataFrame = field(default_factory=pd.DataFrame)
45
+ inference_pivot: int | None = None
46
+ activation_layers: dict[str, int] = field(default_factory=dict)
47
+ layer_map: pd.DataFrame = field(default_factory=pd.DataFrame)
48
+ intent_trace: IntentTrace | None = None
49
+ cognitive_profile: CognitiveModuleProfile | None = None
50
+
51
+
52
+ class LLMIntentAnalyzer:
53
+ """
54
+ Unified semantic extraction analyzer.
55
+
56
+ Combines notebook metrics (steering, compaction, morpheme wells) with
57
+ Anthropic J-space layer thoughts (logit/J-lens decode, activation pivots).
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ model_name: str,
63
+ *,
64
+ device: str | None = None,
65
+ morpheme_backend: str = "lemma",
66
+ embedding_name: str = "glove-wiki-gigaword-100",
67
+ load_glove: bool = True,
68
+ pivot_layer: int | None = None,
69
+ fit_jspace_transport: bool = False,
70
+ transport_prompts: list[str] | None = None,
71
+ ) -> None:
72
+ self.model_name = model_name
73
+ self.pivot_layer = pivot_layer
74
+ self.bundle = load_model_bundle(model_name, device=device)
75
+ self.extractor = MorphemeExtractor(morpheme_backend) # type: ignore[arg-type]
76
+ self.embedding_space: EmbeddingSpace | None = None
77
+ self.morpheme_freq: Counter[str] = Counter()
78
+ self.transport: TransportMaps | None = None
79
+
80
+ if load_glove:
81
+ self.embedding_space = load_glove_gensim(embedding_name)
82
+ sample_words = self.embedding_space.vocab[:5000]
83
+ self.morpheme_freq = Counter(self.extractor.extract(sample_words))
84
+
85
+ self._numerical_pole: torch.Tensor | None = None
86
+ self._glove_poles = build_glove_poles(self.embedding_space) if self.embedding_space else None
87
+
88
+ if fit_jspace_transport:
89
+ prompts = transport_prompts or [
90
+ "The quick brown fox jumps over the lazy dog.",
91
+ "Two plus two equals four.",
92
+ "Question: What is 12 times 2? Answer:",
93
+ ]
94
+ self.transport = fit_transport_maps(self.bundle, prompts)
95
+
96
+ @property
97
+ def numerical_pole(self) -> torch.Tensor:
98
+ if self._numerical_pole is None:
99
+ self._numerical_pole = build_numerical_pole(self.bundle)
100
+ return self._numerical_pole
101
+
102
+ def analyze_prompt(
103
+ self,
104
+ prompt: str,
105
+ *,
106
+ cot_prompt: str | None = None,
107
+ include_compaction: bool = False,
108
+ include_block_semantics: bool = False,
109
+ include_jspace: bool = True,
110
+ track_tokens: list[str] | None = None,
111
+ twin_b: str | None = None,
112
+ ) -> AnalysisReport:
113
+ report = AnalysisReport(prompt=prompt, model_name=self.model_name)
114
+ pole = self.numerical_pole
115
+
116
+ report.intensity_sweep = analyze_steering_intensity(self.bundle, prompt, pole)
117
+ report.entropy_trajectory = get_entropy_trajectory(self.bundle, prompt)
118
+
119
+ pivot = self.pivot_layer or self._default_pivot()
120
+ if cot_prompt:
121
+ report.cot_comparison = compare_cot_intensity(
122
+ self.bundle,
123
+ prompt,
124
+ cot_prompt,
125
+ pole,
126
+ pivot_layer=pivot,
127
+ )
128
+ report.pivot_entropy = calculate_pivot_entropy(
129
+ self.bundle,
130
+ prompt,
131
+ cot_prompt,
132
+ pivot_layer=pivot,
133
+ )
134
+
135
+ if include_jspace:
136
+ report.intent_trace = build_intent_trace(
137
+ self.bundle,
138
+ prompt,
139
+ transport=self.transport,
140
+ track_tokens=track_tokens,
141
+ )
142
+ report.activation_layers = report.intent_trace.activation_layers
143
+ if twin_b:
144
+ report.cognitive_profile = build_cognitive_module_profile(
145
+ self.bundle,
146
+ prompt,
147
+ twin_b,
148
+ transport=self.transport,
149
+ )
150
+ report.layer_map = build_layer_correspondence_map(
151
+ self.bundle,
152
+ prompt,
153
+ transport=self.transport,
154
+ cognitive_profile=report.cognitive_profile,
155
+ )
156
+ else:
157
+ report.layer_map = build_layer_correspondence_map(
158
+ self.bundle,
159
+ prompt,
160
+ transport=self.transport,
161
+ )
162
+ report.inference_pivot = report.activation_layers.get("inference_pivot")
163
+
164
+ if include_block_semantics and self.embedding_space:
165
+ report.block_semantics = self.extract_block_semantics()
166
+
167
+ if include_compaction and self.embedding_space:
168
+ comp = CompactionAnalyzer(self.model_name, self.embedding_space)
169
+ report.compaction = comp.analyze_compaction()
170
+ if report.inference_pivot is None:
171
+ report.inference_pivot = comp.find_inference_pivot(report.compaction)
172
+ comp.cleanup()
173
+
174
+ return report
175
+
176
+ def identify_activation(self, prompt: str) -> dict[str, int]:
177
+ """Return layer indices for inference pivot, workspace peak, motor onset."""
178
+ return identify_activation_layers(self.bundle, prompt)
179
+
180
+ def cognitive_modules(
181
+ self,
182
+ twin_a: str,
183
+ twin_b: str,
184
+ ) -> CognitiveModuleProfile:
185
+ """Identify identity, reasoning, meta-reasoning, ideation kernels."""
186
+ from llmintent.heighten.cot_delta import compute_cot_delta
187
+
188
+ cot_delta = compute_cot_delta(self.bundle, twin_a, twin_b)
189
+ return build_cognitive_module_profile(
190
+ self.bundle,
191
+ twin_a,
192
+ twin_b,
193
+ transport=self.transport,
194
+ cot_delta=cot_delta,
195
+ )
196
+
197
+ def layer_correspondence(
198
+ self,
199
+ prompt: str,
200
+ *,
201
+ twin_b: str | None = None,
202
+ ) -> pd.DataFrame:
203
+ """Map each transformer layer to regime, role, and top verbal intent."""
204
+ return build_layer_correspondence_map(
205
+ self.bundle,
206
+ prompt,
207
+ transport=self.transport,
208
+ twin_b=twin_b,
209
+ )
210
+
211
+ def intent_trace(
212
+ self,
213
+ prompt: str,
214
+ *,
215
+ track_tokens: list[str] | None = None,
216
+ ) -> IntentTrace:
217
+ """Build full J-space intent trace (layer thoughts)."""
218
+ return build_intent_trace(
219
+ self.bundle,
220
+ prompt,
221
+ transport=self.transport,
222
+ track_tokens=track_tokens,
223
+ )
224
+
225
+ def layer_band_summary(self, prompt: str) -> dict:
226
+ return summarize_layer_bands(self.bundle, prompt, transport=self.transport)
227
+
228
+ def fit_transport(self, prompts: list[str]) -> TransportMaps:
229
+ self.transport = fit_transport_maps(self.bundle, prompts)
230
+ return self.transport
231
+
232
+ def query_concept(
233
+ self,
234
+ concept: str,
235
+ prompt: str,
236
+ *,
237
+ twin_b: str | None = None,
238
+ top_k_layers: int = 5,
239
+ ) -> ConceptQueryResult:
240
+ """
241
+ Query a semantic concept against the activation trajectory.
242
+
243
+ Uses KL + twin Barlow feature space with KNN retrieval to identify
244
+ which layers activate for the given concept text.
245
+ """
246
+ cognitive = None
247
+ if twin_b:
248
+ cognitive = build_cognitive_module_profile(
249
+ self.bundle,
250
+ prompt,
251
+ twin_b,
252
+ transport=self.transport,
253
+ )
254
+ return query_concept_in_trajectory(
255
+ self.bundle,
256
+ concept,
257
+ prompt,
258
+ twin_b=twin_b,
259
+ top_k_layers=top_k_layers,
260
+ cognitive_profile=cognitive,
261
+ )
262
+
263
+ def query_concepts(
264
+ self,
265
+ concepts: list[str],
266
+ prompt: str,
267
+ *,
268
+ twin_b: str | None = None,
269
+ ) -> dict[str, ConceptQueryResult]:
270
+ return query_concepts_batch(
271
+ self.bundle,
272
+ concepts,
273
+ prompt,
274
+ twin_b=twin_b,
275
+ )
276
+
277
+ def trajectory_map(
278
+ self,
279
+ prompt: str,
280
+ *,
281
+ twin_b: str | None = None,
282
+ concepts: list[str] | None = None,
283
+ ) -> TrajectoryMapping:
284
+ """Build unified activation trajectory mapping across all layers."""
285
+ return build_trajectory_mapping(
286
+ self.bundle,
287
+ prompt,
288
+ twin_b=twin_b,
289
+ transport=self.transport,
290
+ concepts=concepts,
291
+ )
292
+
293
+ def visualizer(self, output_dir: str = "llmintent_viz"):
294
+ """Return a VisualizationSuite for maps, correlations, and animations."""
295
+ from llmintent.viz import VisualizationSuite
296
+
297
+ return VisualizationSuite(self.bundle, output_dir=output_dir)
298
+
299
+ def visualize_report(
300
+ self,
301
+ prompt: str,
302
+ *,
303
+ twin_b: str | None = None,
304
+ concepts: list[str] | None = None,
305
+ output_dir: str = "llmintent_viz",
306
+ include_morphemes: bool = False,
307
+ ) -> dict[str, str]:
308
+ """Generate full visualization report (maps, correlations, animations)."""
309
+ viz = self.visualizer(output_dir=output_dir)
310
+ block_semantics = self.extract_block_semantics() if include_morphemes else None
311
+ return viz.render_full_report(
312
+ prompt,
313
+ twin_b=twin_b,
314
+ concepts=concepts,
315
+ block_semantics=block_semantics,
316
+ )
317
+
318
+ def heighten_framework(self, focus_threshold: float = 0.45):
319
+ """Return HeightenedReasoningFramework for retrace-based focus sharpening."""
320
+ from llmintent.heighten import HeightenedReasoningFramework
321
+
322
+ return HeightenedReasoningFramework(
323
+ self.bundle,
324
+ transport=self.transport,
325
+ focus_threshold=focus_threshold,
326
+ )
327
+
328
+ def diagnose_focus(
329
+ self,
330
+ prompt: str,
331
+ *,
332
+ anchor_prompt: str | None = None,
333
+ concepts: list[str] | None = None,
334
+ ):
335
+ """Measure how focused reasoning is for a prompt trajectory."""
336
+ return self.heighten_framework().diagnose_focus(
337
+ prompt,
338
+ anchor_prompt=anchor_prompt,
339
+ concepts=concepts,
340
+ )
341
+
342
+ def heighten_reasoning(
343
+ self,
344
+ prompt: str,
345
+ *,
346
+ anchor_prompt: str | None = None,
347
+ concepts: list[str] | None = None,
348
+ mode: str = "explicit_retrace",
349
+ apply_steering: bool = False,
350
+ ):
351
+ """
352
+ Heighten reasoning by forcing a self-retrace and measuring focus gain.
353
+
354
+ Uses retrace prompt scaffolding + optional activation steering at
355
+ reasoning layers to sharpen concept-peaked, layer-concentrated computation.
356
+ """
357
+ from llmintent.heighten import RetraceMode, heighten_reasoning
358
+
359
+ retrace_mode = RetraceMode(mode) if isinstance(mode, str) else mode
360
+ return heighten_reasoning(
361
+ self.bundle,
362
+ prompt,
363
+ anchor_prompt=anchor_prompt,
364
+ concepts=concepts,
365
+ mode=retrace_mode,
366
+ transport=self.transport,
367
+ apply_steering=apply_steering,
368
+ )
369
+
370
+ def compare_prompts(
371
+ self,
372
+ prompts: dict[str, str],
373
+ ) -> pd.DataFrame:
374
+ """Multi-prompt intensity sweep (Direct vs CoT, ablation levels, etc.)."""
375
+ return run_intensity_sweep(self.bundle, prompts, self.numerical_pole)
376
+
377
+ def stress_test(self, simple: str, complex: str) -> pd.DataFrame:
378
+ return run_stress_test(self.bundle, simple, complex)
379
+
380
+ def activation_profile(self, prompt: str) -> pd.DataFrame:
381
+ return activation_summary(self.bundle, prompt)
382
+
383
+ def extract_block_semantics(self, max_layers: int | None = None) -> dict[int, dict[str, list[str]]]:
384
+ if not self.embedding_space:
385
+ raise RuntimeError("GloVe embeddings required for block semantics")
386
+ layers = get_transformer_layers(self.bundle.model)
387
+ limit = max_layers or len(layers)
388
+ out: dict[int, dict[str, list[str]]] = {}
389
+ for idx, layer in enumerate(layers[:limit]):
390
+ try:
391
+ out[idx] = get_block_semantics(
392
+ layer,
393
+ self.embedding_space,
394
+ self.morpheme_freq,
395
+ extractor=self.extractor,
396
+ )
397
+ except AttributeError:
398
+ continue
399
+ return out
400
+
401
+ def block_expertise_report(self, max_layers: int | None = None) -> pd.DataFrame:
402
+ semantics = self.extract_block_semantics(max_layers=max_layers)
403
+ rows: list[dict[str, str | int]] = []
404
+ for layer_idx, block in semantics.items():
405
+ expertise = get_block_expertise(block)
406
+ for component, units in block.items():
407
+ rows.append(
408
+ {
409
+ "layer": layer_idx,
410
+ "expertise": expertise,
411
+ "component": component,
412
+ "top_units": ", ".join(units[:5]),
413
+ }
414
+ )
415
+ return pd.DataFrame(rows)
416
+
417
+ def _default_pivot(self) -> int:
418
+ canonical = 18
419
+ canonical_depth = 48
420
+ scaled = int(round(canonical / canonical_depth * self.bundle.num_layers))
421
+ return max(1, min(scaled, self.bundle.num_layers - 1))
422
+
423
+ def cleanup(self) -> None:
424
+ del self.bundle
425
+ gc.collect()
426
+ if torch.cuda.is_available():
427
+ torch.cuda.empty_cache()
@@ -0,0 +1,43 @@
1
+ """Benchmark suite: HellaSwag validation with retrace ablations on SLMs."""
2
+
3
+ from llmintent.benchmark.ablation import (
4
+ AblationCondition,
5
+ DEFAULT_ABLATION_SUITE,
6
+ FAST_ABLATION_SUITE,
7
+ parse_conditions,
8
+ )
9
+ from llmintent.benchmark.hellaswag import (
10
+ HellaSwagExample,
11
+ hellaswag_accuracy,
12
+ load_hellaswag,
13
+ load_hellaswag_fallback,
14
+ score_hellaswag_example,
15
+ )
16
+ from llmintent.benchmark.retrace_store import RetraceStore, StoredRetracement
17
+ from llmintent.benchmark.runner import (
18
+ BenchmarkRunConfig,
19
+ ConditionResult,
20
+ HellaSwagBenchmarkRunner,
21
+ prepare_slm_comparison,
22
+ )
23
+ from llmintent.benchmark.slm_registry import DEFAULT_SLMS, get_slm, list_slms
24
+
25
+ __all__ = [
26
+ "AblationCondition",
27
+ "BenchmarkRunConfig",
28
+ "ConditionResult",
29
+ "DEFAULT_ABLATION_SUITE",
30
+ "FAST_ABLATION_SUITE",
31
+ "HellaSwagBenchmarkRunner",
32
+ "HellaSwagExample",
33
+ "RetraceStore",
34
+ "StoredRetracement",
35
+ "get_slm",
36
+ "hellaswag_accuracy",
37
+ "list_slms",
38
+ "load_hellaswag",
39
+ "load_hellaswag_fallback",
40
+ "parse_conditions",
41
+ "prepare_slm_comparison",
42
+ "score_hellaswag_example",
43
+ ]