SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2025.findings-acl.394 · ACL Findings · 2025

Hierarchical Safety Realignment: Lightweight Restoration of Safety in Pruned Large Vision-Language Models

Gerard De Melo, Yue Li, Xiaoling Wang, Xin Yi, Linlin Wang, Dongsheng Shi

Open in the Atlas

Code that ran

14 of 17 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 1 honoured the contract we drafted, 0 violated it and 5 have no contract verdict; 8 failures of our instrument; 3 no recorded run), measured 2026-11-24; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2025.findings-acl.394.json · badge: /api/ran/2025.findings-acl.394.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
TheShineyue/HSR canonical (classifier label)
classifier basis: census
14 ran · 3 no recorded run
FunctionStatusWhere it lives
check_sparsity Ran
ran on a synthesized input
TheShineyue/HSR/alignment-attribution-hsr/lib/prune.py
code served (permissive licence) · get_code("e5c2acc858940a2b")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned tuple, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

# Build a minimal model that matches the structure expected by check_sparsity
# The function accesses: model.language_model.model.layers[i]
# Each layer should contain Linear modules (found by find_layers)

class MinimalTransformerLayer(nn.Module):
    def __init__(self, hidden_dim=4, intermediate_dim=3):
        super().__init__()
        # Include some linear layers that will be found by find_layers
        self.linear1 = nn.Linear(hidden_dim, intermediate_dim)
        self.linear2 = nn.Linear(intermediate_dim, hidden_dim)
    
    def forward(self, x):
        return self.linear2(self.linear1(x))

class MinimalTransformerModel(nn.Module):
    def __init__(self, num_layers=2, hidden_dim=4):
        super().__init__()
        self.layers = nn.ModuleList([
            MinimalTransformerLayer(hidden_dim=hidden_dim)
            for _ in range(num_layers)
        ])
    
    def forward(self, x):
        for layer in self.layers:
            x = layer(x)
        return x

class MinimalLanguageModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = MinimalTransformerModel(num_layers=2, hidden_dim=4)
    
    def forward(self, x):
        return self.model(x)

class MinimalFullModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.language_model = MinimalLanguageModel()
    
    def forward(self, x):
        return self.language_model(x)

# Create model and sparsify some weights to test sparsity calculation
model = MinimalFullModel()

# Introduce some sparsity by setting some weights to zero
for layer in model.language_model.model.layers:
    for name, param in layer.named_parameters():
        if 'weight' in name:
            # Set approximately 30% of weights to zero
            mask = torch.rand_like(param.data) > 0.7
            param.data[mask] = 0

# Create a minimal args object (could be a dict or simple namespace)
class MinimalArgs:
    pass

args = MinimalArgs()

ARGS = {
    'args': args,
    'model': model
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 1, dtype family float — a tuple output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
find_layers Ran
ran; our contract draft was wrong, not the code
TheShineyue/HSR/alignment-attribution-hsr/lib/prune.py
pointer only (licence: MIT); the stored copy get_code serves, from zyxxmu/dsnot, is pointer only (licence: NONE) · get_code("2ed16fcdc14ad951")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from zyxxmu/dsnot, and GitHub detected no licence in that repository when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

get_chat_vicuna Ran
ran on a synthesized input
TheShineyue/HSR/alignment-attribution-hsr/lib/data.py
code served (permissive licence) · get_code("44ae8046f05daee6")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned list, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

torch.manual_seed(0)

ARGS = {
    'prompt': 'What is in this image?',
    'answer': 'This is a sample answer.'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type list, ndim 1, dtype family float — a list output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
get_last_hidden_states Ran
ran, honoured the contract we drafted
TheShineyue/HSR/SafetyHeadAttribution-hsr/attribution.py
pointer only (licence: MIT); the stored copy get_code serves, from ydyjya/safetyheadattribution, is pointer only (licence: NONE) · get_code("313de3d0e5c72b22")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from ydyjya/safetyheadattribution, and GitHub detected no licence in that repository when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

get_last_hidden_states Ran
ran on a synthesized input
TheShineyue/HSR/SafetyHeadAttribution-hsr/llava_next_ships.py
code served (permissive licence) · get_code("2ae85ec12c676745")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned Tensor, ndim 2, dtype family float, shape (2, 16) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

class DummyModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 8)
    
    def forward(self, input_ids, pixel_values, image_sizes, attention_mask, 
                head_mask=None, mask_type=None, scale_factor=None, output_hidden_states=False):
        # Simulate model output with hidden_states
        batch_size = input_ids.shape[0]
        seq_len = input_ids.shape[1]
        hidden_dim = 8
        
        # Return a mock output object with hidden_states attribute
        class MockOutput:
            def __init__(self, hidden_states):
                self.hidden_states = hidden_states
        
        # Create hidden states: list of tensors, last one has shape (batch_size, seq_len, hidden_dim)
        hidden_states = [torch.randn(batch_size, seq_len, hidden_dim) for _ in range(3)]
        return MockOutput(hidden_states)

# Create model and tokenizer
model = DummyModel()
tokenizer = None  # Not actually used in the function

# Create device
device = 'cpu'

# Create data as list of batches
batch_size = 2
seq_len = 3
hidden_dim = 8
pixel_dim = 5

data = [
    {
        'input_ids': torch.randint(0, 100, (batch_size, seq_len)),
        'pixel_values': torch.randn(batch_size, 3, pixel_dim, pixel_dim),
        'image_sizes': torch.randint(1, 10, (batch_size, 2)),
        'attention_mask': torch.ones(batch_size, seq_len, dtype=torch.long)
    },
    {
        'input_ids': torch.randint(0, 100, (batch_size, seq_len)),
        'pixel_values': torch.randn(batch_size, 3, pixel_dim, pixel_dim),
        'image_sizes': torch.randint(1, 10, (batch_size, 2)),
        'attention_mask': torch.ones(batch_size, seq_len, dtype=torch.long)
    }
]

# Create mask_cfg
mask_cfg = {
    'head_mask': None,
    'mask_type': 'attention',
    'scale_factor': 1.0
}

ARGS = {
    'model': model,
    'tokenizer': tokenizer,
    'data': data,
    'device': device,
    'mask_cfg': mask_cfg
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 2, dtype family float, shape (2, 16) — shape (2, 16) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
get_llm Ran
ran on a synthesized input
TheShineyue/HSR/alignment-attribution-hsr/main_low_rank.py
code served (permissive licence) · get_code("5638e4d0804fdac3")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned MockLLM. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
from torch import nn

torch.manual_seed(0)

# Mock the modeltype2path dictionary
modeltype2path = {
    'llama2-7b-chat-hf': 'mock_path_7b_chat',
    'llama2-13b-chat-hf': 'mock_path_13b_chat',
    'llama2-7b-hf': 'mock_path_7b',
    'llama2-13b-hf': 'mock_path_13b'
}

# Create a minimal mock model that satisfies the function's usage
class MockLLMConfig:
    def __init__(self):
        self.max_position_embeddings = 2048

class MockLLM(nn.Module):
    def __init__(self):
        super().__init__()
        self.config = MockLLMConfig()
        self.seqlen = None
    
    def forward(self, input_ids, attention_mask=None):
        return torch.randn(2, 10, 32000)

# Patch AutoModelForCausalLM.from_pretrained to return our mock
from unittest.mock import patch, MagicMock

def mock_from_pretrained(*args, **kwargs):
    model = MockLLM()
    return model

# Apply the patch
import transformers
original_from_pretrained = transformers.AutoModelForCausalLM.from_pretrained
transformers.AutoModelForCausalLM.from_pretrained = staticmethod(mock_from_pretrained)

ARGS = {
    'model_name': 'llama2-7b-chat-hf',
    'cache_dir': 'llm_weights'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type MockLLM — a MockLLM output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a MockLLM output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
load_from_search_cfg Ran
ran; our contract draft was wrong, not the code
TheShineyue/HSR/SafetyHeadAttribution-hsr/attribution.py
pointer only (licence: MIT); the stored copy get_code serves, from ydyjya/safetyheadattribution, is pointer only (licence: NONE) · get_code("2b9bd829f84c86a0")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from ydyjya/safetyheadattribution, and GitHub detected no licence in that repository when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

load_vlm_dataset Ran
ran on a synthesized input
TheShineyue/HSR/alignment-attribution-hsr/lib/data.py
code served (permissive licence) · get_code("32597e11c4b6dc95")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned Dataset. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import json
import tempfile
import os
from datasets import Dataset
import pandas as pd

# Create a temporary JSON file with sample data
sample_data = [
    {
        "id": 1,
        "text": "A cat sitting on a mat",
        "label": "animal"
    },
    {
        "id": 2,
        "text": "A dog running in a field",
        "label": "animal"
    }
]

# Write sample data to a temporary file
temp_dir = tempfile.gettempdir()
data_path = os.path.join(temp_dir, "vlm_dataset_test.json")

with open(data_path, 'w', encoding='utf-8') as f:
    json.dump(sample_data, f, ensure_ascii=False)

ARGS = {
    "data_path": data_path
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
datasets, pandas — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Dataset — a Dataset output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a Dataset output the recorded ndim 1 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
make_Act Ran
ran; our contract draft was wrong, not the code
TheShineyue/HSR/alignment-attribution-hsr/lib/model_wrapper.py
code served (permissive licence) · get_code("6331aac8ce321543")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned SimpleModel. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

# Create a simple model with Linear layers
class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear1 = nn.Linear(4, 3)
        self.linear2 = nn.Linear(3, 2)
        self.nested = nn.Sequential(
            nn.Linear(2, 5)
        )
    
    def forward(self, x):
        x = self.linear1(x)
        x = self.linear2(x)
        x = self.nested(x)
        return x

# Instantiate the model
model = SimpleModel()

# Define ARGS dictionary with all parameters for make_Act
ARGS = {
    "model": model,
    "verbose": False
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type SimpleModel — a SimpleModel output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a SimpleModel output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
make_Act Ran
ran; our contract draft was wrong, not the code
TheShineyue/HSR/alignment-attribution-hsr/lib/model_wrapper_low.py
code served (permissive licence) · get_code("bfffa1909ea61c48")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned SimpleModel. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

# Build a simple model with nested Linear layers
class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.layer1 = nn.Linear(4, 3)
        self.layer2 = nn.Linear(3, 2)
        self.nested = nn.Sequential(
            nn.Linear(2, 5),
            nn.Linear(5, 1)
        )
    
    def forward(self, x):
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.nested(x)
        return x

model = SimpleModel()

ARGS = {
    "model": model,
    "verbose": False
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type SimpleModel — a SimpleModel output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a SimpleModel output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
return_given_alpha Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
TheShineyue/HSR/alignment-attribution-hsr/lib/prune.py
code served (permissive licence) · get_code("d79ce728b3ab7682")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned tuple. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

# Analyzing the function:
# - alpha: used in multiplication with sum_before, should be a scalar or tensor
# - sort_res: indexed as sort_res[0], which is then used with torch.gather
#   sort_res[0] should be a tensor of shape (batch, features)
# - W_metric: compared with <= operator, should be a tensor
# - tmp_metric: compared with <= operator, shape should match (batch, features)
# - sum_before: multiplied by alpha, should be a 1D tensor of shape (batch,)

# The function:
# 1. Computes thres_cumsum = sum_before * alpha
# 2. Creates sort_mask by comparing tmp_metric <= thres_cumsum.reshape((-1, 1))
# 3. Uses torch.gather on sort_res[0] with indices from sort_mask.sum(dim=1, keepdims=True) - 1
# 4. Compares W_metric <= thres
# 5. Computes sparsity as ratio of True values

# Setting up small tensors with distinct dimensions:
batch_size = 2
feature_size = 4

# alpha: scalar or small tensor
alpha = torch.tensor(0.5)

# sum_before: shape (batch_size,)
sum_before = torch.tensor([10.0, 20.0])

# sort_res: list with first element being (batch_size, feature_size) tensor
sort_res = [torch.randn(batch_size, feature_size)]

# tmp_metric: (batch_size, feature_size) - values to compare
tmp_metric = torch.randn(batch_size, feature_size)

# W_metric: (batch_size, feature_size) - values to compare with threshold
W_metric = torch.randn(batch_size, feature_size)

ARGS = {
    "alpha": alpha,
    "sort_res": sort_res,
    "W_metric": W_metric,
    "tmp_metric": tmp_metric,
    "sum_before": sum_before,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple — a tuple output has no array shape of its own; none is stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
revert_Act_to_Linear Ran
ran; our contract draft was wrong, not the code
TheShineyue/HSR/alignment-attribution-hsr/lib/model_wrapper.py
code served (permissive licence) · get_code("8c4e38a44dc7aecd")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned SimpleModel. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
from functools import reduce

class ActLinear(nn.Module):
    """
    drop in replacement of nn.Linear
    """

    def __init__(self, base: nn.Linear):
        super().__init__()
        self.base = base
        self.activation_norms = torch.zeros([base.in_features], device=self.base.weight.device, requires_grad=False)
        self.n_samples = 0
        self.record_activation = True

    def clear_act_buffer(self):
        self.activation_norms.fill_(0.0)
        self.n_samples = 0

    def forward(self, x):
        if self.record_activation:
            if hasattr(self, 'mask') and self.mask is not None:
                x_ = x[self.mask]
            else:
                x_ = x
            bs = x_.nelement() // x_.shape[-1]
            self.activation_norms = self.activation_norms * (self.n_samples / (self.n_samples + bs)) + (x_ * x_).view(-1, x_.shape[-1]).sum(dim=0) * (1.0 / (self.n_samples + bs))
            self.n_samples += bs
        out = self.base(x)
        return out

    @property
    def weight(self):
        return self.base.weight

    @property
    def bias(self):
        return self.base.bias

def revert_Act_to_Linear(model):
    """
    Reverts ActLinear modules back to their original nn.Linear layers.
    """
    for name, module in model.named_modules():
        if isinstance(module, ActLinear):
            linear_module = module.base
            parent_name = name.rsplit('.', 1)[0] if '.' in name else ''
            print(f'Reverting {name}, parent: {parent_name}')
            parent_module = model if parent_name == '' else reduce(getattr, parent_name.split('.'), model)
            setattr(parent_module, name.split('.')[-1], linear_module)
    return model

torch.manual_seed(0)

# Build a simple model with ActLinear modules
class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        # Create base linear layers
        base_linear1 = nn.Linear(4, 3)
        base_linear2 = nn.Linear(3, 2)
        
        # Wrap them in ActLinear
        self.layer1 = ActLinear(base_linear1)
        self.layer2 = ActLinear(base_linear2)
    
    def forward(self, x):
        x = self.layer1(x)
        x = self.layer2(x)
        return x

model = SimpleModel()

ARGS = {
    "model": model
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type SimpleModel — a SimpleModel output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a SimpleModel output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
revert_Act_to_Linear Ran
ran; our contract draft was wrong, not the code
TheShineyue/HSR/alignment-attribution-hsr/lib/model_wrapper_low.py
code served (permissive licence) · get_code("51a9a80e8f53eb6b")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned TestModel. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
from functools import reduce

torch.manual_seed(0)

class ActLinear(nn.Module):
    """
    drop in replacement of nn.Linear
    """

    def __init__(self, base: nn.Linear):
        super().__init__()
        self.base = base
        self.activation_norms = []
        self.record_activation = True

    def clear_act_buffer(self):
        self.activation_norms = []

    def forward(self, x):
        if self.record_activation:
            if hasattr(self, 'mask') and self.mask is not None:
                x_ = x[self.mask]
            else:
                x_ = x
            self.activation_norms.append(x_.view(-1, x_.shape[-1]).cpu())
        out = self.base(x)
        return out

def revert_Act_to_Linear(model):
    """
    Reverts ActLinear modules back to their original nn.Linear layers.
    """
    for name, module in model.named_modules():
        if isinstance(module, ActLinear):
            linear_module = module.base
            parent_name = name.rsplit('.', 1)[0] if '.' in name else ''
            print(f'Reverting {name}, parent: {parent_name}')
            parent_module = model if parent_name == '' else reduce(getattr, parent_name.split('.'), model)
            setattr(parent_module, name.split('.')[-1], linear_module)
    return model


# Build a test model with ActLinear modules at various levels
class TestModel(nn.Module):
    def __init__(self):
        super().__init__()
        # Top-level ActLinear
        self.linear1 = ActLinear(nn.Linear(4, 3))
        # Nested ActLinear in a submodule
        self.submodule = nn.Module()
        self.submodule.linear2 = ActLinear(nn.Linear(3, 2))
        # Regular linear layer (should not be reverted)
        self.linear3 = nn.Linear(2, 4)

model = TestModel()

ARGS = {
    "model": model
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type TestModel — a TestModel output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a TestModel output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
update_mask_cfg Ran
ran; our contract draft was wrong, not the code
TheShineyue/HSR/SafetyHeadAttribution-hsr/attribution.py
pointer only (licence: MIT); the stored copy get_code serves, from ydyjya/safetyheadattribution, is pointer only (licence: NONE) · get_code("3a2320c99110f0df")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from ydyjya/safetyheadattribution, and GitHub detected no licence in that repository when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

apply_prompt_template Not yet run
unverified (harvested, no recorded run)
TheShineyue/HSR/alignment-attribution-hsr/lib/prompt_utils.py
code served (permissive licence) · get_code("f5343b47f228ee9b")
How it ran

no invocation recorded.

get_VLguard_vicuna Not yet run
unverified (harvested, no recorded run)
TheShineyue/HSR/alignment-attribution-hsr/lib/data.py
code served (permissive licence) · get_code("fbbb5f87e2327714")
How it ran

no invocation recorded.

get_prompt_template Not yet run
unverified (harvested, no recorded run)
TheShineyue/HSR/alignment-attribution-hsr/lib/prompt_utils.py
code served (permissive licence) · get_code("ae0dc3fd8cee2ec4")
How it ran

no invocation recorded.

Also present in other papers' code

Of 17 samples lifted from this paper's linked repositories, 17 carry a function identity and 0 do not. Of the 15 distinct functions with an identity, 7 are also present in other papers whose code we hold (6 with at least one paper dated earlier, 0 the same month, 1 later) and 8 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

FunctionAlso present inEarliest-datedOthers named
find_layers 21 other papers
15 dated earlier, 1 later, 5 same year, order not determinable · 5 only as an assembly brick
2306.11695 (2023-06)
A Simple and Effective Pruning Approach for Large Language Models
2310.05175 (2023-10)
Outlier Weighed Layerwise Sparsity (OWL ): A Missing Secret Sauce for Pruning LLMs to High Sparsity
2310.08915 (2023-10)
Dynamic Sparse No Training: Training-Free Fine-tuning for Sparse LLMs
and 18 more not named here
return_given_alpha 2 other papers
1 dated earlier, 1 same year, order not determinable · 1 only as an assembly brick
2306.11695 (2023-06)
A Simple and Effective Pruning Approach for Large Language Models
2505.23807 (2025-05)
DLP: Dynamic Layerwise Pruning in Large Language Models
revert_Act_to_Linear 2 other papers
1 dated earlier, 1 same year, order not determinable
2412.12497 (2024-12)
NLSR: Neuron-Level Safety Realignment of Large Language Models Against Harmful Fine-Tuning
2025.acl-long.590 (2025 (year only))
The Tug of War Within: Mitigating the Fairness-Privacy Conflicts in Large Language Models
get_last_hidden_states 1 other paper
1 dated earlier
2410.13708 (2024-10)
On the Role of Attention Heads in Large Language Model Safety
load_from_search_cfg 1 other paper
1 dated earlier
2410.13708 (2024-10)
On the Role of Attention Heads in Large Language Model Safety
make_Act 1 other paper
1 same year, order not determinable
2025.acl-long.590 (2025 (year only))
The Tug of War Within: Mitigating the Fairness-Privacy Conflicts in Large Language Models
update_mask_cfg 1 other paper
1 dated earlier
2410.13708 (2024-10)
On the Role of Attention Heads in Large Language Model Safety

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-24.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

With the growing size of Large Vision-Language Models (LVLMs), network pruning techniques designed to compress these models for deployment in resource-constrained environments have attracted significant attention. However, we observe that pruning frequently results in a degradation in safety performance. To address this issue, we propose a novel and lightweight approach, named Hierarchical Safety Realignment (HSR). HSR operates by first quantifying the contribution of each attention head to safety, identifying the most critical ones, and then selectively restoring neurons directly within these attention heads that play a pivotal role in maintaining safety. This process hierarchically realigns the safety of pruned LVLMs, progressing from the attention head level to the neuron level. We validate HSR across various models and pruning strategies, consistently achieving notable improvements in safety performance. To the best of our knowledge, this is the first work explicitly focused on restoring safety in LVLMs post-pruning. The code will be available at https://github.com/TheShineyue/HSR.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2025.findings-acl.394")
get_code_for_paper("2025.findings-acl.394")
have("2025.findings-acl.394")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2025.findings-acl.394.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2025.findings-acl.394.svg)](https://syntology.ai/paper/2025.findings-acl.394)

Connect an agent — have() is free.