Neural Features and Hallucinations in LLMs: An Engineering Perspective on Interpretability

    This article examines neural features in large language models from an engineering perspective. It explains what neural features are and where their applicability ends, discusses activation paths and the risks of intervention, and analyzes how hallucinations are defined, caused, and evaluated. It then provides PyTorch code for extracting hidden-layer activations and an engineering checklist covering reproducible experiments, evaluation, and cost tracking.

    Research on neural features inside large language models is shifting from observing phenomena to locating and intervening in them. For developers, this means some model behavior can be inspected directly in hidden layers rather than inferred only from outputs. This article first explains what neural features are and where their applicability ends, then discusses activation paths and hallucination, and finally provides feature extraction code and an engineering checklist.

    1. What Are Neural Features, and What Are Their Limits?

    Early research found that individual neurons in a model often respond to multiple unrelated concepts at once, making them difficult to interpret. In recent years, researchers have used methods such as sparse autoencoders to decompose hidden-layer representations into a larger number of more singular directions. Some of these directions correspond to identifiable semantics, such as a grammatical structure, a specific entity, or a tone. Bricken et al. (2023) systematically discussed methods for extracting such “monosemantic features.”

    These conclusions have clear limits of applicability. Whether a feature exists and how clear it is depends on the model structure, the chosen layer, the probing method, and the training data. Switching to another model or layer can lead to completely different conclusions. Therefore, when a team cites a feature, it should also record the model version, layer number, and decomposition method; otherwise, the conclusion cannot be reproduced.

    2. Activation Paths: Useful Intuition, but Not a Substitute for Experiments

    In linear models, the relationship between input and output is relatively direct. In deep networks, information passes through multiple nonlinear transformations, and different inputs may traverse similar but not identical internal paths. Comparing this phenomenon to a “line of steepest descent” can help build intuition, but it is only an analogy, not a mathematical description of the model.

    From an engineering standpoint, the practical risk of this nonlinearity is that deleting seemingly unimportant connections or neurons may change downstream task performance, and the change may not be smooth. Therefore, any pruning or weight adjustment should first be validated experimentally. Here is an actionable checklist:

    1. Fix a set of representative inputs and cache the target layer’s activations as a baseline.
    2. Use probing or decomposition methods to locate features associated with the target behavior, and record their indices and layer numbers.
    3. Before and after the change, compare metrics on general and target tasks, such as accuracy, refusal rate, and output consistency.
    4. Set a rollback threshold in advance—for example, roll back if the target-task metric drops by more than a predetermined percentage of the baseline. The team should determine the threshold based on its own business context.
    5. Record the input, activations, and output for every failure case as the basis for the next round of analysis.

    3. Hallucinations: Definition, Causes, and Evaluation

    In model research, hallucination usually refers to content generated by the model that does not match facts or the input evidence, yet is stated with high confidence. This differs from a “visual illusion.” A visual illusion is an inherent bias of the perceptual system, whereas model hallucination mainly comes from statistical patterns in training data and the model’s tendency to complete text even when evidence is insufficient.

    Research shows that certain certainty-related features may exhibit abnormally strong activation when facing inputs outside the training distribution. This indicates that hallucination is related to internal representations, but it does not mean there is a “hallucination neuron” that can simply be switched off. Commonly used mitigation methods include retrieval-augmented generation, alignment training based on human feedback, and targeted adjustments to specific features.

    Evaluation is key to whether these methods can be deployed. Teams should use a fixed evaluation set to measure the factual error rate, whether refusals are reasonable, and consistency of responses across turns, and compare these against a baseline. An adjustment should be considered effective only if it improves performance on the target evaluation set without significantly degrading general capabilities. Evaluation conclusions should also specify the scope of the evaluation set and should not be directly extrapolated to all scenarios.

    4. Engineering Practice: Extracting Features and Tracking Costs

    Extracting hidden-layer features produces a large amount of data, so resources need to be estimated in advance. For storage at fp16 precision, the storage volume for a single collection is approximately: samples × sequence length × hidden dimension × 2 bytes. For example, 10,000 samples with an average length of 128 and a hidden dimension of 768 require about 2 GB. If multiple layers are saved at the same time, storage grows proportionally with the number of layers.

    On the compute side, teams can use general-purpose container platforms to schedule inference tasks, run forward passes on GPUs, and archive feature files in object storage. Logs and monitoring should cover each task’s start time, duration, GPU memory usage, failure count, and retry records. Cost estimates should be broken down by GPU hours, storage capacity, and network traffic, and mapped to the experimental conclusions produced by each task so teams can judge whether the investment is worthwhile.

    The following code shows how to extract the output of a specified layer using a PyTorch-style forward hook. Dependencies are torch 2.0 or later and transformers 4.30 or later.

    1. import torch
    2. import torch.nn as nn
    3. class FeatureExtractor:
    4. def __init__(self, model: nn.Module, target_layer: nn.Module):
    5. self.model = model
    6. self.features = None
    7. # Register a forward hook on the target layer without modifying model weights
    8. self.handle = target_layer.register_forward_hook(self._hook)
    9. def _hook(self, module, inputs, output):
    10. # Some layers output a tuple; in that case, take the first tensor
    11. if isinstance(output, tuple):
    12. output = output[0]
    13. self.features = output.detach().cpu()
    14. @torch.no_grad()
    15. def get_features(self, input_ids: torch.Tensor) -> torch.Tensor:
    16. self.model.eval()
    17. # input_ids shape is [batch, seq_len]
    18. self.model(input_ids)
    19. return self.features
    20. def close(self):
    21. # Remove the hook after use to avoid duplicate registration
    22. self.handle.remove()
    23. # Usage example (GPT-2 shown; replace with another causal language model)
    24. from transformers import AutoTokenizer, AutoModelForCausalLM
    25. name = "gpt2"
    26. tokenizer = AutoTokenizer.from_pretrained(name)
    27. model = AutoModelForCausalLM.from_pretrained(name)
    28. # The 6th Transformer block of GPT-2; confirm the layer number based on the model structure
    29. extractor = FeatureExtractor(model, model.transformer.h[6])
    30. ids = tokenizer("The capital of France is", return_tensors="pt").input_ids
    31. feats = extractor.get_features(ids)
    32. print(feats.shape) # Shape is [1, seq_len, 768], where 768 is the hidden dimension
    33. extractor.close()

    If the model runs on a GPU, move input_ids to the same device as the model. When choosing target_layer, print the model structure first, confirm the layer names and indices, and compare across multiple layers rather than inspecting only one layer.

    Conclusion and Engineering Takeaways

    Research on neural features inside large language models provides a new entry point for understanding model behavior. For engineering teams, three practices are most valuable. First, make feature localization and activation caching part of the standard workflow, and keep reproducible records. Second, evaluate hallucination before intervention, using a fixed evaluation set to measure the benefits and costs of each adjustment. Third, estimate storage and compute costs in advance, and map the investment in each experiment to its output. These practices will not solve every problem at once, but they make every change traceable.