Manuscript Offprint
arXiv:2609.00597Topological Steering
Abstract
With the rapid rise of large language models (LLMs), controlling undesirable model behaviors has become increasingly important. Existing behavioral control methods typically intervene directly in activation or feature space, but such approaches can be sensitive to outliers, distributional shifts, noise, and other local perturbations. Motivated by Topological Data Analysis (TDA), which captures global rather than purely local structure, we propose Topological Steering, a new framework for steering LLM behavior through the topological representation of activation spaces. Using persistence diagrams, our method connects activation-based steering with TDA and enables more robust behavioral control. We show that Topological Steering consistently modifies LLM behavior across multiple model families and model sizes.
1 Introduction
Large language models (LLMs) are increasingly deployed as general-purpose assistants, yet their behavior remains difficult to control reliably. Even highly aligned models can produce harmful, dishonest, sycophantic, or otherwise undesirable outputs under adversarial or distribution-shifted prompts. As a result, a growing line of work has sought lightweight mechanisms for controlling model behavior at inference time, without retraining the model or modifying its weights [3, 16, 2].
A particularly promising direction is activation steering [15], which intervenes directly on internal representations. Early methods showed that adding a fixed steering vector to the residual stream can induce predictable changes in sentiment, refusal, truthfulness, or safety-related behavior. Subsequent approaches, including contrastive activation addition [14] and more recent nonlinear or rotational interventions [16], have improved the flexibility of this paradigm. However, most existing steering methods are fundamentally geometric and local: they construct directions from means, linear contrasts, or low-dimensional subspaces in activation space. Such approaches can be effective, but they implicitly assume that the behavioral concept of interest is well captured by a simple global direction or a smooth local transformation.
This assumption is often too restrictive. Behavioral representations in LLMs may be multimodal, nonlinearly organized, and distributed across heterogeneous regions of activation space. For example, refusal behavior may not correspond to a single cluster or linear axis; instead, it may be supported by several distinct activation substructures associated with different prompt types, semantic contexts, or safety mechanisms. In such settings, a global mean-difference vector can dilute or average away the relevant signal, while purely local geometric interventions may be sensitive to outliers, noise, and small perturbations. These limitations motivate a more structural view of activation space: rather than asking only where individual activations lie, we ask what shape the activation cloud has and which multiscale structures distinguish one behavioral regime from another.
Topological Data Analysis (TDA) provides mathematical tools precisely for this purpose. Persistent homology summarizes the multiscale topology of a point cloud by tracking when connected
Preprint.
components, loops, and higher-dimensional features appear and disappear as a distance scale varies. The resulting persistence diagrams are stable summaries of global structure and have been widely studied as robust descriptors of complex high-dimensional data. Historically [1, 5], however, the use of TDA in large-scale machine learning has been limited by computational cost: persistent homology can be expensive to compute inside training loops or on very large datasets. In the context of inference-time steering, this bottleneck is substantially reduced. Steering requires only a finite collection of activation vectors from contrastive prompt sets, making it possible to use persistent topology as an actionable signal for intervention design.
Contribution. In this paper, we introduce Topological Steering, a new inference-time method for controlling LLM behavior through the topology of activation spaces. Given contrastive prompt sets, such as refusal-eliciting and compliance-eliciting prompts, we extract residual-stream activations and view them as point clouds. We then apply joint dimensionality reduction, compute Vietoris–Rips persistence diagrams, and compare the diagrams of the two behavioral regimes. Features that are both persistent and specific to the target behavior are used to identify coherent activation subsets, rather than averaging indiscriminately over all examples. These subsets define localized contrastive directions, which are aggregated into a steering vector and injected into the residual stream during generation.
The key idea is that topology provides a mechanism for moving beyond global centroid shifts. Classical activation steering [14] constructs a direction from the mean difference between positive and negative activations. Topological Steering instead identifies robust, behavior-specific substructures in the positive activation cloud and steers using directions derived from those substructures. This allows the intervention to reflect the heterogeneous organization of behavioral concepts in representation space, while also providing an interpretable account of which activation components support the steering signal.
Our contributions are three-fold:
-
Topology-Aware Steering for LLMs: We introduce Topological Steering, an inference-time framework that uses tools from Topological Data Analysis to construct steering directions from the multiscale structure of LLM activation spaces. By applying TDA outside the training loop, our method avoids the computational bottlenecks that have historically limited its use in large-scale deep learning.
-
Structural Interpretability via Persistence Diagrams: In contrast to linear or angular steering methods [16] that operate through geometric shifts in activation space, our approach uses persistence diagrams to identify robust topological features of behavioral representations, such as connected components and higher-order structures. This provides an interpretable way to localize behavior-relevant regions in the residual stream.
-
Empirical Validation for Topological Intervention: We demonstrate that Topological Steering consistently improves over unsteered baselines and produces measurable behavioral changes across model families and sizes. While the current implementation is not intended to outperform highly optimized geometric steering methods, it offers a complementary trade-off: sacrificing some raw efficacy in exchange for a more structured and inspectable intervention mechanism grounded in the topology of activation space.
Most Recent Steering Methods. Most recently, the field has begun exploring beyond purely additive, translational shifts; for instance, Angular Steering frames behavioral control as rotational interventions within fixed activation subspaces [16]. However, while these methods successfully manipulate representations, they predominantly treat the activation space as possessing relatively simple geometry. This leaves room for approaches such as Topological Steering that can isolate and leverage the complex, global, and non-linear invariants inherent to high-dimensional data manifolds.
Topological Data Analysis and Persistent Homology. TDA provides a rigorous mathematical framework for quantifying the "shape" of complex, high-dimensional datasets. One of the most important methods of TDA is persistent homology [9, 7], which tracks the evolution of topological features such as connected components, one-dimensional loops, and higher-dimensional voids across a continuous range of spatial scales. By constructing a sequence of expanding simplicial complexes (e.g., a Vietoris-Rips filtration) over a point cloud, persistent homology records the scale at which each topological feature appears (birth) and the scale at which it ultimately merges or closes (death). These structural invariants are summarized in a Persistence Diagram, offering a multiscale signature of the data's topology. According to stability theorems [8], Persistence Diagrams are robust to noise and continuous geometric deformations within the data manifold. This is why they have been the subject of extensive research in machine learning.
Topological Machine Learning. The integration of these topological summaries into deep learning led to the creation of the term Topological Machine Learning. Initially, the main focus was on improving Persistence Diagrams. PDs are inherently discrete, and to make these topological features compatible with standard neural networks, researchers have developed stable, finite-dimensional vectorization techniques, the most famous being Persistence Landscapes [6] in 2015 and Persistence images [1] in 2016. In the following year, the researchers developed differentiable topological layers [11, 5], allowing models to optimize for specific topological properties directly during gradient descent.
Despite their theoretical elegance, these methods were fundamentally limited by computational constraints. The combinatorial explosion of tracking high-dimensional simplices, coupled with the expensive matrix reduction algorithms required for persistent homology, scaled poorly. Consequently, computing these topological penalties within the iterative training loops of large-scale models became prohibitively slow and memory-intensive, thereby stalling the field of Topological Machine Learning. Our method revives these powerful topological tools by shifting their application from training-time optimization to inference-time activation steering, effectively bypassing the historical computational barrier.
3 Background
This section introduces the technical ingredients used by our method. We first formalize the transformer computation and the activation-steering intervention used at inference time. We then review the topological knowledge needed to characterize activation geometry: persistent homology, persistence diagrams, and Vietoris–Rips filtrations. Together, these tools let us connect representation-level interventions (steering vectors in residual space) with structure-level summaries (topological features across scales), which is the central perspective of Topological Steering. Some supplementary details can be found in the Appendix A.1.
3.1 Transformers and Activation Steering
For the rest of the paper we are going to fix the notation for a decoder-only transformer with layers, hidden width , and token sequence length . At a layer we have self attention denoted with head dimension .
Activation steering modifies an internal residual activation at a chosen layer and token position (often the final prompt token [18, 14, 15]) by adding a direction vector at inference time: h_{t^*}^{(\ell^*)}' = h_{t^*}^{(\ell^*)} + \alpha \mathbf{v}, where: is the original residual activation, is the steering vector, and is a scalar steering strength.
3.2 Persistent Homology, Persistence Diagrams and Vietoris–Rips Filtration
Persistent homology is a multiscale way to describe the shape of a point cloud (here, activation vectors). As we vary a distance scale , topological features (connected components, loops, etc.) appear and disappear; for feature , we denote its birth and death by , and its persistence by . Features with larger are more stable across scales and are treated as more structurally meaningful.
A Persistence Diagram is the set of birth–death pairs returned by persistent homology. Each point corresponds to one topological feature, and its distance from the diagonal
equals (up to a constant factor) its persistence . In our method, these diagrams summarize activation geometry and allow comparison between harmful and harmless activation clouds.
To compute Persistent Homology, we build a Vietoris–Rips Filtration from pairwise distances. For each scale , we connect points in whose distance is at most , forming a simplicial complex . As increases, these complexes are nested, and tracking topology across this nested sequence yields the birth/death pairs used in our theory and experiments.
4 Topological Steering
4.1 Motivation for Topological Steering
Classical activation steering typically uses a global contrastive direction , where and are class means of harmful and harmless activations. This is optimal only under restrictive geometric assumptions (e.g., approximately unimodal classes with similar covariance structure), where a single linear axis captures the relevant class gap.
A convenient way to see this is through a mixture model. Suppose harmful activations are multi-modal: , , , while harmless activations follow . Then , with and . Hence averages over potentially incompatible behavioral modes; if only a subset of modes encode refusal behavior, their signal is diluted by unrelated components.
This motivates replacing “global centroid shift” with “structure-aware subset shift.” Let denote activation subsets that correspond to robust refusal structure. The desired direction is , where is the mean of the structurally selected subset, not of the entire harmful cloud. The challenge is to identify without supervision on latent modes.
Topological summaries provide a natural criterion because they are multiscale and coordinate-free. Given a filtration on the activation cloud, persistent homology yields features , , where high persistence indicates geometric stability across scales. Comparing harmful and harmless diagrams introduces a second criterion: behavioral specificity. If is the optimal match of harmful feature in the harmless diagram (or diagonal), define , so large indicates a refusal-unique topological signature.
We therefore seek features that are simultaneously stable and class-specific: . Each selected feature induces a local component and a local contrastive direction . Topological steering then constructs , , which emphasizes refusal-relevant submanifolds rather than global class averages.
In short, the motivation is that refusal behavior in residual space is often structurally heterogeneous: linear global means collapse this heterogeneity, whereas persistent topology isolates robust local structure and yields steering directions with stronger mechanistic interpretability.
4.2 Overview of Topological Steering
We propose Topological Steering, a method for constructing activation-space steering vectors for large language models (LLMs) that exploits persistent-homology structure in residual-stream representations. Rather than using the global mean difference between harmful and harmless activations, we identify topologically-significant, refusal-unique sub-clusters in the harmful activation cloud and use those to derive a more precise steering direction. The end-to-end pipeline consists of five key steps:
-
Activation Extraction and Joint Projection: We hook into an intermediate transformer layer to extract residual stream representations for both harmful and harmless prompts. We project these sets into a shared low-dimensional subspace using joint PCA.
-
Topological Feature Extraction: We treat the projected activations as finite metric spaces and compute their persistent homology via Vietoris–Rips filtrations. This yields persistence diagrams ( and ) that capture the birth and death of topological features (e.g., connected components) across multiple spatial scales.
-
Refusal-Unique Feature Selection: We compare the topological summaries of both classes using optimal bottleneck matching. By identifying features with high persistence (geometric stability) and high mismatch cost (absence in the harmless class), we isolate structural signatures that uniquely encode refusal behavior.
-
Local Steering Vector Assembly: For each selected topological feature, we trace back to its constituent points in the activation cloud. We compute local contrastive vectors () between these refusal-specific clusters and their nearest harmless neighbors, weighting them by their topological significance and effect size to form the final aggregate vector, .
-
Inference-Time Intervention: During autoregressive generation, is injected into the target layer's residual stream, consistently nudging the model toward the robustly identified refusal sub-manifolds without compromising the surrounding semantic space.
The advantages of the Topological Steering approach are the following:
-
Heterogeneity Awareness: It identifies and leverages specific, local clusters of target behavior, ensuring that the steering vector is not diluted by averaging disjoint sub-populations.
-
Coordinate-Free Robustness: Because persistent homology characterizes the intrinsic geometry of representations independently of rigid coordinate assumptions, the method is highly resilient to noise and varied prompt distributions.
-
Enhanced Specificity: The dual criteria of persistence and cross-class mismatch ensure that the resulting steering vector is heavily anchored in features unique to the target behavior, maximizing the separation margin and minimizing off-target side effects.
-
Computational Cost: Traditional TDA methods for Deep Learning were focused on the training aspect but here we intervene only at the inference time, reducing the compute cost drastically.
4.3 Notation and Setup
Let be a decoder-only transformer with layers. Given an input prompt, we denote the residual-stream activation at layer and the final token position as , where is the model's hidden dimension. We collect two datasets of prompts:
-
: harmful prompts that elicit model refusals.
-
: harmless prompts on similar topics that elicit compliance.
We split each dataset into disjoint train and holdout sets. All steering vectors are derived exclusively from the train split; holdout activations are used only for evaluation.
4.4 Activation Extraction
For each prompt (resp. ), we register a forward hook on the output of transformer block and record the last-token residual: and . The choice of layer is treated as a hyperparameter and swept over mid-to-late layers.
4.5 Joint PCA Projection
Hidden dimensions (e.g., for Llama-3.1-8B) are too large for tractable persistent-homology computation. We reduce dimensionality via joint PCA: both activation sets are projected into the same low-dimensional space so that their relative geometry is preserved. Concretely, we concatenate into , fit PCA on , and project: , where is the number of retained components (default ). The effective rank is capped at to avoid degeneracy.
4.6 Persistent Homology of Activation Clouds
We model each projected activation set as a finite metric space (point cloud) and compute its persistent homology using the Vietoris–Rips filtration [10].
Given a point cloud and a scale parameter , the Vietoris–Rips complex is the simplicial complex containing every simplex whose pairwise diameter is at most . As grows from 0 to , topological features (connected components in degree , loops in degree , etc.) are born and die. The Persistence Diagram records each -dimensional feature as a point with birth and death ; its persistence is .
We compute persistence diagrams separately for each class: , , using the Ripser algorithm [4] with coefficients. We compute features by default and optionally features.
4.7 Feature Matching and Refusal-Unique Feature Selection
A topological feature in is refusal-unique if it has no close counterpart in . To operationalise this, we compute an optimal matching between and (for each homology degree ) under the bottleneck distance [8]. Each feature is matched to its nearest counterpart (or to the diagonal if no finite match exists), yielding a mismatch cost . We rank all finite features by their persistence and mismatch cost , filtering by thresholds and : , sorted by descending.
4.8 Steering Vector Construction
For each selected feature , we identify the corresponding sub-cluster of harmful activations using the death radius. Specifically, the death value of the feature corresponds to the scale at which its connected component merges into a larger one in the Vietoris–Rips filtration. We extract the points belonging to that component just before merger: , where is a small numerical tolerance. Only components satisfying (a minimum size threshold) are retained.
For each component , we identify the nearest harmless training points (in PCA space) to the component centroid, forming a local negative contrast set . The per-component steering direction is: \mathbf{v}_i = \tilde{X}_C_i^+ - \tilde{X}_N_i^-, \tilde{X}_C_i^+ = \frac{1}{|C_i|} \sum_{j \in C_i} x_j^+, \tilde{X}_N_i^- = \frac{1}{|N_i|} \sum_{j \in N_i} x_j^-. Each direction is weighted by a quality score combining persistence, mismatch cost, and the Cohen's effect size along :
where (resp. ) is the mean projection of (resp. ) onto , and is the pooled standard deviation. The final steering vector is the normalised weighted sum over the top- components:
with orientation enforced so that . We compare against the naive mean-difference direction , which corresponds to the standard activation-steering approach [18].
4.9 Inference-Time Steering
At inference time, we inject the steering vector into the residual stream at the same layer used for extraction. Given a new input prompt , we modify the last-token hidden state at every generation step: , where is the steering magnitude. Applying the hook only at the final token position preserves the full autoregressive context while consistently nudging the model's representation towards the refusal subspace.
4.10 Evaluation Metric
We measure steering quality via the refusal score: the normalised class gap along the steering direction evaluated on held-out activations and : . We report the steering score as the primary comparative metric, where positive values indicate that our topological direction separates harmful from harmless activations more effectively than the baseline.
5 Experimentations
Following recent steering papers that separate representation-level diagnostics from downstream behavioral tests (e.g., refusal sweeps and automated judges; cf. Angular Steering [16]), we organize this section into i) datasets and models and then separate our experiment section into ii) a proof that TS is working with benchmarks and metrics 5.2 and iii) a proof that TS is working across different model architectures 5.3. Unless stated otherwise, steering vectors are computed on training splits only, injected at inference as a normalized residual update at the last prompt token, and evaluated on held-out activations and on open-ended generations. All experiments were run on an A100 (40Gb) and for reproducibility purposes the hyperparameter details are in Appendix A.5.3. Moreover proof that the experiment results we obtain are not due to randomness are in A.6.
5.1 Datasets and Models
Construction of Contrastive Activation Pairs for Steering. Harmful prompts are drawn from AdvBench [17]. We use the standard harmful split materialized as line-delimited prompts; the preparation utility enforces 520 unique harmful strings with a fixed calibration/evaluation partition: 416 calibration and 104 evaluation harmful prompts. Harmless prompts are sampled from the public instruction corpus tatsu-lab/alpaca on Hugging Face as we require at least 512 unique instructions for calibration-side harmless data; when no local snapshot is supplied, prompts are fetched with the datasets library and de-duplicated by normalized text. This mirrors the contrastive pipeline in our codebase: activations are collected at a chosen transformer block, projected with joint PCA, and passed to the topological construction of .
Models. The default development model in our configuration is meta-llama/Llama-3.1-8B-Instruct; the repository also supports multi-model sweeps (Qwen 2.5 and Gemma 2 families) through a shared hooking interface. Layer index and TDA hyperparameters (PCA dimension, persistence thresholds, , component merge depth, etc.) are treated as tunables; a representative end-to-end tuning run selects a single layer and hyperparameter hash before behavioral validation.
5.2 Experimental Proof that Topological Steering is working with relevant Benchmarks
The first goal of the Experiment section 5 is to show that our method is indeed steering LLMs and working. This is shown in table 1.
We report three complementary families of numbers: (i) activation steering scores, (ii) lightweight lexical jailbreak-rates, and (iii) external LLM judges aligned with community red-teaming practice. We now explain the different metrics computed:
Activation Separation Metric ( ). Let , be harmful and harmless held-out activations at . For a candidate direction , write and define the scalar refusal score , where (resp. ) is the mean of (resp. ) and is the pooled standard deviation of the concatenated projections (implementation matches our training-time weighting routine). The steering score delta is with on the train split. Positive certifies that the topological direction separates harmful from harmless clouds more sharply than the mean-difference baseline before any decoding. This steering score delta is vital as it is the first indicator that our model is indeed steering, allowing us to then compute different benchmark methods that will more precisely evaluate the answers of our steered model.
The different benchmarks used are Llama Guard 3 implemented from [12], Harmbench classifier [13] and Substring Matching. More details are found in A.5.1.
Interpretation. Table 1 answers two distinct questions:
-
First, the activation row shows that the learned topological vector improves the linear separability of harmful versus harmless activations relative to the global mean direction. This is direct evidence that the persistence-guided subset construction is extracting a refusal-aligned axis in representation space.
-
Second, the judge rows show that decoding under the same intervention increases automated jailbreak rates on a fixed harmful evaluation set, with the largest relative movement on Llama Guard 3 and a smaller but consistent gain on HarmBench; the substring probe moves modestly.
Table 1: Representative end-to-end result after single-layer steering with comparison to baseline; steering injection in that run). “Judge ” is steered minus baseline success rate.
| Metric family | Baseline | Topological | |
|---|---|---|---|
| Activation: best (held-out) | — | — | +0.0127 |
| Activation: mean std. (robustness replicates) | — | — | +0.0092 0.0022 |
| Llama Guard 3 success rate | 0.510 | 0.692 | +0.183 |
| HarmBench classifier success rate | 0.010 | 0.029 | +0.019 |
| Substring refusal lexicon success rate | 0.029 | 0.038 | +0.010 |
Table 2: Multi-model comparative run. For each checkpoint we sweep transformer blocks , pick that maximizes held-out (topological vs. mean-difference baseline), and report , , and at . is the total number of decoder blocks; is a coarse “depth” readout.
| Model | ||||||
|---|---|---|---|---|---|---|
| google/gemma-2-9b-it | 42 | 13 | 0.31 | 0.499 | 1.249 | 0.750 |
| meta-llama/Llama-3.2-3B-Instruct | 28 | 20 | 0.71 | 1.948 | 1.966 | 0.018 |
| Qwen/Qwen2.5-3B-Instruct | 36 | 20 | 0.56 | 1.981 | 1.987 | 0.006 |
| Qwen/Qwen2.5-14B-Instruct | 48 | 20 | 0.42 | 1.977 | 1.983 | 0.006 |
| Qwen/Qwen2.5-7B-Instruct | 28 | 8 | 0.29 | 1.974 | 1.979 | 0.005 |
| meta-llama/Llama-3.1-8B-Instruct | 32 | 16 | 0.50 | 1.972 | 1.974 | 0.001 |
Limitations. Automated judge metrics are subject to evaluation drift: measured success rates can change when the judge stack changes (e.g., prompt template, backend model revision, API/server configuration), even if the generated responses are held fixed; therefore HarmBench and Llama Guard scores should be interpreted as setup-dependent and not directly interchangeable. Our substring-based refusal probe is intentionally lightweight but misses non-lexical refusals (safe refusals that do not contain predefined trigger phrases for example “That request is unsafe and I won’t provide operational instructions”), which can bias jailbreak-rate estimates upward for semantically valid but lexically novel refusals. Moreover, oppositely because our substring probe only flags generic refusal phrases and does not assess whether a response still contains harmful instructional content, partially compliant or “disclaimer-first” answers can look like refusals to the probe while remaining unsafe under a semantic judge (for example, prefacing harmful steps with a refusal-like disclaimer), this can bias jailbreak-rate estimates downward. Higher activation-space separation (e.g., higher ) does not guarantee uniform improvements across other capabilities, so helpfulness, reasoning, truthfulness, and related tasks must be measured directly rather than inferred from steering metrics.
5.3 Experimental Proof that Topological Steering is working across different Model Architectures
The second goal of our experiments is to show that our method does not work only on meta-llama/Llama-3.1-8B-Instruct but also on other models. So we compared the steering score of different models, as a positive is proof of a working TS method. Our results are shown in table 2.
Interpretation. All six models show at their selected layer: the persistence-guided steering direction consistently improves linear separability of harmful vs. harmless activations relative to the global mean contrast, under the same training/holdout protocol and sweep budget. The ranking is not monotone in parameter count (e.g. Llama-3.2-3B gains more than Llama-3.1-8B), which is expected if refusal geometry is shaped by post-training alignment and width/depth tradeoffs, not raw capacity alone. The optimal injection depth varies by family: Qwen-7B peaks very early (), whereas Qwen-3B/14B and Llama-3.2-3B peak at the sweep cap (), and Llama-3.1-8B peaks mid-stack (). Such spread is consistent with the hypothesis that “where” harmful/harmless structure is most readable in the residual stream depends on stacking depth, normalization placement, and how safety-related features are distributed across layers. All of which differ between Llama-3, Qwen2.5, and Gemma-2 blocks (e.g., Gemma 2 uses alternating local/global attention and a different norm/attention ordering than Llama). We notice a significative difference in Gemma-2-9b-it with a way bigger than the other models. Gemma attains a much larger but also a much smaller baseline than the other five models. Architecturally, that pattern indicates that the scalar refusal score is not cross-model calibrated: residual magnitudes, RMSNorm scaling, and hidden width jointly change the scale of projections , so comparing raw across checkpoints is weaker than comparing within a model or reporting additional generation-side judges. Here, the low suggests the mean-difference axis is a poor proxy for refusal separation in Gemma's activation geometry at , while the topological subset, hence the TS method, still recovers a strong separating direction (large ). We therefore emphasize within-model gains and treat Gemma's large as evidence that Gemma may benefit more from topology-based steering than from simple global mean-difference steering, not as a claim that Gemma is “ more steerable” than Llama in an absolute sense.
Remark 1. Table 2 supports a cross-family proof of mechanism: topological steering is not an artifact of a single Llama checkpoint, it yields positive across decoder-only architectures with different depths, widths, and normalization/attention recipes. The dispersion of motivates reporting layer sweeps (or at least a mid-late band) rather than a single universal layer, and motivates appendix plots of per model. As shown in Figure 1 and Figure 2.
6 Conclusion, limits and remarks
We introduced Topological Steering, an inference-time method that builds steering directions from persistent-homology structure in activation space rather than from a single global mean contrast. By matching harmful/harmless persistence diagrams, selecting robust contrastive features, and aggregating local directions, the method turns activation geometry into an explicit and inspectable steering signal. Our results show consistent positive separation gains () across the tested models and layers in our single-layer setup, together with measurable behavioral movement on external judge benchmarks. More broadly, this work positions TDA as an actionable representation-level tool for intervention design, not only a descriptive visualization aid. While we acknowledge that specialized geometric methods may still lead on specific benchmarks, the results presented here argue for a conceptual pivot. By providing a reproducible and inspectable pipeline, this paper opens a new 'steering primitive' for the field. It is indeed a contribution we believe will remain relevant as model architectures continue to evolve and as engineering refinements will likely improve its absolute performance in the future.
Some limitations of our method are:
- Persistent Homology is sensitive to preprocessing and to hyperparameters that govern feature selection; our gains depend on tuning, as is common for steering.
- Diagram-based summaries are not uniquely tied to semantics: high-persistence features can reflect nuisance geometry unless paired with contrastive matching and behavioral validation.
- Computational cost, while modest compared to training using TDA tools, still scales with point-cloud size and homology degree.
- We focus on refusal as a concrete safety axis; transfer to other behaviors will require new contrast sets and careful evaluation.
A natural next step is hybrid steering: use topology to identify where to intervene, then combine with optimized geometric update rules for how to intervene. Another direction is to use persistence diagrams as structured evidence for safety debugging and representation-level auditing.
Closing Remark. Topological Steering is a proof-of-concept that multiscale structure in activation space can be converted into a practical intervention without retraining. Even when not outperforming specialized baselines, it expands the steering design space by making support subsets and multiscale structure first-class components of the method. We believe that Topological Steering will be a promising foundation for the next generation of representation level safety tools and we hope it helps revive topological thinking in modern deep learning research.
References
[1] Henry Adams, Sofya Chepushtanova, Tegan Emerson, Eric Hanson, Michael Kirby, Francis Motta, Rachel Neville, Chris Peterson, Patrick Shipman, and Lori Ziegelmeier. Persistence images: A stable vector representation of persistent homology, 2016. URL https://arxiv.org/abs/1507.06217.
[2] Andy Arditi, Oscar Obeso, Aaquib Syed, Daniel Paleka, Nina Panickssery, Wes Gurnee, and Neel Nanda. Refusal in language models is mediated by a single direction. Advances in Neural Information Processing Systems, 37:136037–136083, 2024.
[3] Amanda Askell, Yuntao Bai, Anna Chen, Dawn Drain, Deep Ganguli, Tom Henighan, Andy Jones, Nicholas Joseph, Ben Mann, Nova DasSarma, et al. A general language assistant as a laboratory for alignment. arXiv preprint arXiv:2112.00861, 2021.
[4] Ulrich Bauer. Ripser: efficient computation of vietoris–rips persistence barcodes. Journal of Applied and Computational Topology, 5(3):391–423, 2021.
[5] Rickard Brüel-Gabrielsson, Bradley J. Nelson, Anjan Dwaraknath, Primoz Skraba, Leonidas J. Guibas, and Gunnar Carlsson. A topology layer for machine learning, 2020. URL https://arxiv.org/abs/1905.12200.
[6] Peter Bubenik. Statistical topological data analysis using persistence landscapes, 2015. URL https://arxiv.org/abs/1207.6437.
[7] Gunnar Carlsson. Topology and data. Bulletin of the American Mathematical Society, 46(2): 255–308, 2009.
[8] David Cohen-Steiner, Herbert Edelsbrunner, and John Harer. Stability of persistence diagrams. In Proceedings of the twenty-first annual symposium on Computational geometry, pages 263–271, 2005.
[9] Edelsbrunner, Letscher, and Zomorodian. Topological persistence and simplification. Discrete & computational geometry, 28(4):511–533, 2002.
[10] Herbert Edelsbrunner and John Harer. Computational topology: an introduction. American Mathematical Soc., 2010.
[11] Christoph Hofer, Roland Kwitt, Marc Niethammer, and Andreas Uhl. Deep learning with topological signatures, 2018. URL https://arxiv.org/abs/1707.04041.
[12] Hakan Inan, Kartikeya Upasani, Jianfeng Chi, Rashi Rungta, Krithika Iyer, Yuning Mao, Michael Tontchev, Qing Hu, Brian Fuller, Davide Testuggine, et al. Llama guard: Llm-based input-output safeguard for human-ai conversations. arXiv preprint arXiv:2312.06674, 2023.
[13] Mantas Mazeika, Long Phan, Xuwang Yin, Andy Zou, Zifan Wang, Norman Mu, Elham Sakhaee, Nathaniel Li, Steven Basart, Bo Li, et al. Harmbench: A standardized evaluation framework for automated red teaming and robust refusal. arXiv preprint arXiv:2402.04249, 2024.
[14] Nina Panickssery, Nick Gabrieli, Julian Schulz, Meg Tong, Evan Hubinger, and Alexander Matt Turner. Steering llama 2 via contrastive activation addition, 2024. URL https://arxiv.org/abs/2312.06681.
[15] Alexander Matt Turner, Lisa Thiergart, Gavin Leech, David Udell, Juan J. Vazquez, Ulisse Mini, and Monte MacDiarmid. Steering language models with activation engineering, 2024. URL https://arxiv.org/abs/2308.10248.
[16] Hieu M Vu and Tan M Nguyen. Angular steering: Behavior control via rotation in activation space. arXiv preprint arXiv:2510.26243, 2025.
[17] Andy Zou, Zifan Wang, Nicholas Carlini, Milad Nasr, J. Zico Kolter, and Matt Fredrikson. Universal and transferable adversarial attacks on aligned language models, 2023. URL https://arxiv.org/abs/2307.15043.
[18] Andy Zou, Long Phan, Sarah Chen, James Campbell, Phillip Guo, Richard Ren, Alexander Pan, Xuwang Yin, Mantas Mazeika, Ann-Kathrin Dombrowski, Shashwat Goel, Nathaniel Li, Michael J. Byun, Zifan Wang, Alex Mallen, Steven Basart, Sanmi Koyejo, Dawn Song, Matt Fredrikson, J. Zico Kolter, and Dan Hendrycks. Representation engineering: A top-down approach to ai transparency, 2025. URL https://arxiv.org/abs/2310.01405.
A Technical appendices and supplementary material
A.1 Complementary Theoretical Background
A.1.1 Transformers
We recall the notation for a decoder-only transformer with layers, hidden width , and token sequence length . Given an input text, tokenization maps it to discrete token IDs
where is the vocabulary. Each token is embedded into and combined with positional information to form the initial residual states
At layer , a standard pre-norm block applies self-attention and an MLP through residual updates:
Here, denotes multi-head causal self-attention and is the position-wise feed-forward block. For each head, attention weights are computed from queries, keys, and values:
with causal mask M and head dimension .
A.1.2 Activation Steering
To complement the Background 3 section we add that:
In our setting, is estimated from two prompt-conditioned activation collections: a positive set (target behavior to increase) and a negative set (behavior to suppress). Let , be activations extracted at the same , and let and be the respective training-set centroids,
and sets the steering vector to the displacement between these class summaries,
This makes steering explicit: positive moves activations toward the target behavioral region and away from the contrast region in residual space. The modified state is then propagated through layers to produce the final logits and generated text.
A.2 Persistent Homology
Let be a finite point cloud (in our case, sampled activations), and let be a metric on (typically Euclidean distance after preprocessing). Persistent homology studies how the topology of evolves across spatial scales by constructing a nested family of simplicial complexes , called a filtration.
For each scale and homological dimension , the -th homology group (with coefficients in a field , e.g., ) encodes -dimensional topological features: tracks connected components, tracks 1-dimensional loops, tracks voids, etc. Its rank is the -th Betti number at scale .
As increases, features appear and disappear. A feature in dimension is said to be born at scale if it first appears in , and dies at scale if it merges into an older class or becomes a boundary in . Its lifetime (or persistence) is . Long-lived classes are typically interpreted as structurally robust, while short-lived classes are often attributed to sampling noise [9].
Formally, persistence is induced by inclusion maps in the filtration. For the inclusion yields a linear map . A class born at that remains nonzero under for but vanishes at has persistence interval .
In this work, persistent homology provides a multiscale summary of activation geometry without assuming linear separability. By tracking birth/death events of components and higher-order structures across scales, it supplies the topological signal that we later encode with persistence diagrams and use to construct steering-relevant subsets/directions.
A.3 Persistence Diagram
A persistence diagram is a finite multiset of birth–death pairs that summarizes the output of persistent homology for a fixed dimension . Given a filtration and its induced persistence module in dimension , each topological class contributes one point , where is the birth scale and is the death scale. The corresponding diagram is .
The diagonal represents zero persistence. Distance from a point to is proportional to its lifetime , so points far from the diagonal correspond to topologically robust structure, while points near the diagonal are typically less stable under perturbations. In practice, we compute diagrams separately by homology degree (e.g., for connected components and for loops), then compare diagrams across behavioral conditions.
To compare two diagrams and , one uses a matching-based metric (e.g., bottleneck or p-Wasserstein) that allows points to match either across diagrams or to the diagonal. Intuitively, this quantifies how much geometric deformation is required to transform one topological summary into the other.
A.4 Vietoris–Rips Filtration
Let with metric dist. For a scale parameter , the Vietoris–Rips complex at scale is for all . Equivalently, a simplex is included iff all pairwise distances among its vertices are at most . Thus, edges appear first, then triangles, tetrahedra, and higher-dimensional simplices as grows.
Because pairwise constraints are monotone in , these complexes form a filtration: whenever . Applying homology to this nested sequence yields persistent homology and, in turn, persistence diagrams.
Vietoris–Rips is especially convenient for activation point clouds because it only requires pairwise distances and does not need an explicit manifold model. Its main trade-off is combinatorial growth: the number of simplices can increase rapidly with sample size and intrinsic dimension, so implementations typically cap the maximum homology degree and rely on dimension reduction (e.g., PCA) before computing persistence.
A.5 Complements on experiments
A.5.1 Benchmarks
In this section we are going to detail more on the 3 benchmarks used:
-
Llama Guard 3: We call a hosted chat-completions endpoint with a Llama Guard 3-compatible model card and aggregate the fraction of generations labeled safe refusal versus compliance, following the spirit of the Llama Guard evaluator line [12]. To be clear the success rate is currently scored as unsafe (higher = more jailbreak success). The implementation records baseline_success_rate and steered_success_rate on the same fixed harmful evaluation prompts.
-
HarmBench classifier: We use the HarmBench behavioral test harness with a HarmBench-style binary classifier (default backend model cais/HarmBench-Llama-2-13b-c1s in our launcher) that reads the harmful prompt and model answer and returns a harm / no-harm style verdict [13]; we export the resulting success_rate fields analogously to Llama Guard. More concretely a higher Harmbench score is equal to worse safety)
-
Substring matching: We mark a generation as a “refusal hit” if its lowercase text contains any phrase from a fixed short lexicon (default list includes templates such as “i’m sorry”, “i cannot”, “as a language model”, …); the reported success rate is non-refusal rate under substring proxy. This probe is inexpensive and correlates loosely with human-visible refusals, but it is brittle on paraphrases; we therefore treat it as a diagnostic, not a standalone claim.
A.5.2 Implementation clarifications and scope.
For transparency, we clarify that the reported Topological Steering results use an operational H₀-component recovery procedure rather than an exact birth-component oracle. Concretely, for a selected H₀ feature , we extract a connected subset at scale and apply deterministic selection heuristics (e.g., viability/size filtering and component scoring) to obtain the steering subset; therefore, statements of the form “the component born at ” should be read as an implementation-level approximation to the intended topological object, not as exact symbolic tracking across the full filtration. In addition, sign orientation is not claimed as a universal post-hoc guarantee for every possible builder: in the single-layer component-aggregation pipeline used for the main results, direction polarity follows the constructed local contrasts and is validated empirically through held-out , rather than by a separate mandatory global sign-flip step logged for every run. Weighting is also fixed only for the reported experiments: we use (persistence mismatch separation) as the chosen experimental setting, and do not claim this weighting is theoretically unique or mandatory beyond the present study.
Table 3: Hyperparameters selected for the row in Table 1.
| Field | Value |
|---|---|
| Layer | 15 |
| PCA components | 192 |
| top- merged components | 7 |
| Minimum component / subset sizes | 16 / 40 |
| Local negatives | 128 |
| Persistence / mismatch floors | 0.01 / 0.01 |
| Component weights | uniform |
Table 4: Approximate wall-clock runtime for the end-to-end best-run pipeline (reconstructed from artifact timestamps).
| Stage | Time (min) | Time (hours) |
|---|---|---|
| Phase 0 (baseline calibration) | 7.67 | 0.13 |
| Phase 1 (coarse search / layer sweep) | 75.19 | 1.25 |
| Phase 2 (focused hyperparameter optimization) | 56.99 | 0.95 |
| Phase 3 (robustness replicates) | 23.73 | 0.40 |
| Phase 4 (inference + judge benchmarks) | 36.03 | 0.60 |
| Phase 5 (final selection / aggregation) | 0.00 | 0.00 |
| Total (Phase 0–5) | 199.62 | 3.33 |
These durations are reconstructed from filesystem mtime windows for each phase folder, so they're a good approximation but not perfect wall-clock start/stop time of each subprocess. All experiments were run on a GPU A100 with 40Gb memory.
Regarding experiment 2 5.3 the times for the run are in Table 5:
Table 5: Approximate compute time for the multi-model comparative run (artifact-time reconstruction).
| Model | Time (min) | Time (hours) |
|---|---|---|
| Qwen/Qwen2.5-3B-Instruct | 5.36 | 0.09 |
| Qwen/Qwen2.5-7B-Instruct | 5.76 | 0.10 |
| Qwen/Qwen2.5-14B-Instruct | 8.73 | 0.15 |
| meta-llama/Llama-3.2-3B-Instruct | 3.27 | 0.05 |
| meta-llama/Llama-3.1-8B-Instruct | 3.93 | 0.07 |
| google/gemma-2-9b-it | 8.91 | 0.15 |
| Total wall-clock (run start → final artifact) | 35.96 | 0.60 |
Note: durations are reconstructed from filesystem timestamps of run artifacts and are therefore approximate wall-clock estimates.
A.5.3 Reproducibility details for the reported runs.
To make the main results reproducible, we fix the full implementation scope and runtime configuration used in the final single-layer study. All reported numbers are produced with a single-layer Topological Steering pipeline on meta-llama/Llama-3.1-8B-Instruct, where the steering vector is injected at the last prompt token with . We use deterministic random control with controller seed 42, baseline calibration seeds 0:19, and robustness seeds {20, 21, 22, 23, 24}. Layer selection is performed over , and the final reported winner uses . The steering builder is h0_components with -only persistence (maxdim=0, homology_focus=h0_first), and fixed winner hyperparameters listed in Table 6. Behavioral evaluation is run on the fixed harmful evaluation set with the same prompt list for baseline and steered generations, using the judge stack substring_matching, llamaguard3, and harmbench; exact endpoint/model settings are also fixed and reported in the table so the judge layer is reproducible.
Table 6: Reproducibility configuration for the final reported single-layer run.
| Item | Fixed value used for reported results |
|---|---|
| Base model | meta-llama/Llama-3.1-8B-Instruct |
| Steering scope | Single-layer only (no multi-layer injection) |
| Injection position | Last prompt token residual |
| Steering scale | |
| Layer sweep range | |
| Final selected layer | |
| Direction method | h0_components |
| Persistence computation | Vietoris–Rips, Ripser, , maxdim=0 |
| Homology focus | h0_first |
| PCA components (winner) | |
| h0_component_min_size | 16 |
| h0_top_k_components | 7 |
| local_neg_k | 128 |
| min_subset_size | 40 |
| Persistence threshold | persistence_min = 0.01 |
| Mismatch threshold | mismatch_cost_min = 0.01 |
| Component weighting | h0_component_weight_by=uniform |
| Randomness (controller seed) | 42 |
| Baseline calibration seeds | 0:19 |
| Robustness seeds | {20, 21, 22, 23, 24} |
| Data (calibration/eval) | Harmful: 416 cal + 104 eval (AdvBench); Harmless: 512 cal (Alpaca) |
| Behavioral prompt set | benchmarks/paper_data/deval_harmful.txt |
| Judge methods | substring_matching, llamaguard3, harmbench |
| LlamaGuard endpoint/model | OpenAI-compatible endpoint (default: http://0.0.0.0:8898/v1), model meta-llama/Llama-Guard-3-8B |
| HarmBench endpoint/model | OpenAI-compatible endpoint (default: http://0.0.0.0:8897/v1), model cais/HarmBench-Llama-2-13b-c1s |
| Metric definitions |
A.5.4 Hyperparameter selection
We selected single-layer topological-steering hyperparameters with a staged search orchestrated by our tuning script (random-integer seeds; full search space and per-phase budgets archived with each run).
First, a baseline calibration phase repeatedly runs the unsteered pipeline over many seeds and records the mean, best, and standard deviation of the activation-side steering statistic produced by the code (the same separability gain we report as relative to a mean-difference baseline). From this we derive a minimum gain threshold (a floor value together with a multiple of the baseline standard deviation) so that later stages ignore improvements indistinguishable from seed noise.
Second, a coarse search draws a large batch of random configurations from a discrete grid over injection layer, PCA dimension, persistent-homology filtration knobs, component selection and weighting options, local negative-pool size, and subsampling controls; each configuration is evaluated by one end-to-end pipeline run, ranked by average gain, and only the top fraction is kept.
Third, a focused search densifies the grid around those survivors by local moves that perturb several TDA-related coordinates (and occasionally the layer) to propose refined candidates, again ranked by the same activation objective.
Fourth, a robustness phase re-evaluates the leading candidates on additional fresh seeds, aggregates per-candidate statistics, and discards settings whose mean gain does not exceed the calibrated baseline plus the minimum gain threshold.
Finally, a behavioral validation phase generates baseline versus steered outputs on harmful prompts and scores them with external judges (e.g. Llama Guard and HarmBench classifiers, plus inexpensive substring refusal probes where desired); the final selection then picks from the robust shortlist using this behavioral evidence (in our main experiment, ranking by the sum of Llama Guard and HarmBench success-rate deltas), freezing the resulting YAML configuration and steering vector for downstream evaluation.
A.5.5 Layer sweeps plots
Per-model layer sweeps (small multiples)

Figure 1: Per-model layer sweeps of on the comparative run. Each panel reports one model, with the selected best layer marked.

Figure 2: Overlay view of across all models.
A.6 Statistical Significance
Table 7 and Figure 3 quantify how stable the observed steering gain is under randomness. In particular, denotes the steering-score delta (the improvement in the held-out refusal separation over the global mean-difference baseline) produced by the same winning single-layer configuration, while only the random seed is changed. This isolates a key source of variability that can affect topological feature selection, subset extraction, and downstream direction construction, even when the data split, model architecture, and hyperparameters are held fixed.
Each table entry corresponds to one full re-run of the pipeline for the selected configuration. The five robustness seeds yield values of approximately 0.00752–0.01271, with a mean of and a sample standard deviation of . The fact that all five runs are positive indicates that the improvement is not driven by a single lucky run: the steering direction recovered from persistent-topology-guided selection consistently enhances linear separability between harmful and harmless activation clouds relative to the baseline. Moreover, the relative spread is modest; the standard deviation is about 24% of the mean, suggesting that seed-induced fluctuations affect the magnitude of the gain but not its sign.
To further assess statistical significance, we report uncertainty around the mean. The table includes the standard error of the mean (SEM) and a 95% -confidence interval for the mean value of (with robustness runs). This interval is approximately [0.00652, 0.01192], which remains clearly above zero. Under the standard -interval assumptions (exchangeability of runs and reasonable approximation to symmetric errors), this supports the interpretation that the steering gain is robust and not merely an artifact of run-to-run noise.
Figure 3 provides an intuitive visual complement. The dashed horizontal line shows the mean across robustness seeds. The shaded darker band represents around the mean, illustrating the observed variability across seeds, while the lighter band shows the 95% -confidence interval for the mean. All seed points lie within the region, consistent with the numeric summary in Table 7. Overall, the combined evidence from the table and figure indicates that the persistent-topology-guided steering direction is stable: the method yields consistently positive improvements over the baseline across independent re-runs, and the uncertainty in the mean estimate does not overlap zero.
Table 7: Robustness of the selected configuration across 5 random seeds in phase-3 robustness runs. is the steering-score improvement over the baseline direction.
| Seed index (phase-3) | |
|---|---|
| 20 | 0.00819 |
| 21 | 0.00772 |
| 22 | 0.00752 |
| 23 | 0.01271 |
| 24 | 0.00997 |
| Mean | 0.00922 |
| Standard deviation (1) | 0.00218 |
| Standard error of the mean | 0.00097 |
| 95% -CI (df = 4) | [0.00652, 0.01192] |

Figure 3: Robustness of the selected configuration across 5 random seeds. The shaded band shows ; the lighter band shows the 95% t-confidence interval for the mean.
A.7 Societal impact (positive and negative)
This work studies inference-time steering methods intended to improve refusal behavior and reduce harmful responses in large language models, which can have positive societal impact by strengthening safety guardrails in high-risk interaction settings. In particular, improving controllable refusal may lower accidental assistance with dangerous requests and support safer deployment practices when combined with independent safety monitoring. At the same time, the same class of representation-level intervention techniques can be repurposed negatively: steering methods may be adapted to weaken existing safeguards, evade policy-aligned behavior, or induce model behaviors that are difficult to detect from surface text alone. Additional risks include over-reliance on automated judges, setup-dependent evaluation drift, and false confidence if activation-space gains are interpreted as universal safety guarantees. For these reasons, we frame our contribution as a diagnostic and methodological study under controlled benchmarks, not as a complete solution to safe deployment, and we encourage layered evaluation (multiple judges, robustness checks, and transparent reporting of failure modes) before real-world use.