SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2504.02508 · CVPR · 2025

APHQ-ViT: Post-Training Quantization with Average Perturbation Hessian Based Reconstruction for Vision Transformers

Jiayi Zhang, Di Huang, Jiaxin Chen, Yunhong Wang, Jinyang Guo, Zhuguanyu Wu

arXiv · PDF · Open in the Atlas

Code that ran

4 of 9 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; 0 honoured the contract we drafted, 0 violated it and 1 has no contract verdict; 3 failures of our instrument; 5 no recorded run), measured 2026-11-22; 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/2504.02508.json · badge: /api/ran/2504.02508.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
GoatWu/APHQ-ViT community
Papers with Code archive
4 ran · 5 no recorded run
FunctionStatusWhere it lives
LossFunction Ran
ran on a synthesized input
GoatWu/APHQ-ViT/utils/block_recon.py
code served (permissive licence) · get_code("fa84db46289995ad")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 0, 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 torch_nn

class MockQuantizer:
    def __init__(self):
        self.soft_targets = torch.tensor([0.3, 0.7, 0.4, 0.6])
    
    def get_soft_targets(self):
        return self.soft_targets

class MockModule(torch_nn.Module):
    def __init__(self):
        super().__init__()
        self.w_quantizer = MockQuantizer()

class MockBlock(torch_nn.Module):
    def __init__(self):
        super().__init__()
        self.layer1 = MockModule()
        self.layer2 = MockModule()

INIT_ARGS = {
    'block': MockBlock(),
    'round_loss': 'relaxation',
    'weight': 1.0,
    'rec_loss': 'mse',
    'max_count': 2000,
    'b_range': (10, 2),
    'decay_start': 0.0,
    'warmup': 0.0,
    'p': 2.0,
}

ARGS = {
    'pred': torch.randn(2, 4),
    'tgt': torch.randn(2, 4),
    'grad': None,
    'count': True,
}

from torch.nn.functional import kl_div, log_softmax, softmax

class LinearTempDecay:

    def __init__(self, t_max: int, rel_start_decay: float=0.2, start_b: int=10, end_b: int=2):
        self.t_max = t_max
        self.start_decay = rel_start_decay * t_max
        self.start_b = start_b
        self.end_b = end_b

    def __call__(self, t):
        """
        Cosine annealing scheduler for temperature b.
        :param t: the current time step
        :return: scheduled temperature
        """
        if t < self.start_decay:
            return self.start_b
        else:
            rel_t = (t - self.start_decay) / (self.t_max - self.start_decay)
            return self.end_b + (self.start_b - self.end_b) * max(0.0, 1 - rel_t)

class LossFunction:

    def __init__(self, block, round_loss: str='relaxation', weight: float=1.0, rec_loss: str='mse', max_count: int=2000, b_range: tuple=(10, 2), decay_start: float=0.0, warmup: float=0.0, p: float=2.0):
        self.block = block
        self.round_loss = round_loss
        self.weight = weight
        self.rec_loss = rec_loss
        self.loss_start = max_count * warmup
        self.p = p
        self.temp_decay = LinearTempDecay(max_count, rel_start_decay=warmup + (1 - warmup) * decay_start, start_b=b_range[0], end_b=b_range[1])
        self.init_loss = 0
        self.count = 0

    @staticmethod
    def lp_loss(pred, tgt, p=2.0, reduction='none'):
        """
        loss function measured in L_p Norm
        """
        if reduction == 'none':
            return (pred - tgt).abs().pow(p).sum(1).mean()
        else:
            return (pred - tgt).abs().pow(p).mean()

    def __call__(self, pred, tgt, grad=None, count=True):
        """
        Compute the total loss for adaptive rounding:
        rec_loss is the quadratic output reconstruction loss, round_loss is
        a regularization term to optimize the rounding policy

        :param pred: output from quantized model
        :param tgt: output from FP model
        :param grad: gradients to compute Hessian
        :return: total loss function
        """
        if count:
            self.count += 1
        if self.rec_loss == 'mse':
            rec_loss = self.lp_loss(pred, tgt, p=self.p)
        elif self.rec_loss == 'mae':
            rec_loss = self.lp_loss(pred, tgt, p=1.0)
        elif self.rec_loss in ['hessian_brecq', 'hessian_perturb']:
            rec_loss = ((pred - tgt).pow(2) * grad.abs()).mean()
        elif self.rec_loss == 'kl_div':
            rec_loss = kl_div(log_softmax(pred, dim=-1), softmax(tgt, dim=-1).detach(), reduction='batchmean')
        else:
            raise ValueError('Not supported reconstruction loss function: {}'.format(self.rec_loss))
        b = self.temp_decay(self.count)
        if self.count < self.loss_start or self.round_loss == 'none':
            b = round_loss = 0
        elif self.round_loss == 'relaxation':
            round_loss = 0
            for name, module in self.block.named_modules():
                if hasattr(module, 'w_quantizer'):
                    round_vals = module.w_quantizer.get_soft_targets()
                    round_loss += self.weight * (1 - ((round_vals - 0.5).abs() * 2).pow(b)).sum()
        else:
            raise NotImplementedError
        if self.count == 1:
            self.init_loss = rec_loss.item()
        rec_loss = rec_loss * 2 / self.init_loss
        total_loss = rec_loss + round_loss
        if self.count == 1 or self.count % 500 == 0:
            print('Total loss:\t{:.3f} (rec:{:.3f}, round:{:.3f})\tb={:.2f}\tcount={}'.format(float(total_loss), float(rec_loss), float(round_loss), b, self.count))
        return total_loss

loss_fn = LossFunction(**INIT_ARGS)
result = loss_fn(**ARGS)
print(f"Loss result: {result}")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
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 0, dtype family float — no output shape is stated: observe_signature.py observed this class with its constructor sizes canonicalised where it could, which the node does not record, so its shape is not stated as this setup block's
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: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
patch_embed_forward Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
GoatWu/APHQ-ViT/utils/block_recon.py
code served (permissive licence) · get_code("4c0321fd4f221905")
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) and returned Tensor, ndim 3, dtype family float, shape (2, 16, 4) 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 PatchEmbed(nn.Module):
    def __init__(self, in_channels=3, embed_dim=4, flatten=True, perturb_u=False, perturb_d=False):
        super().__init__()
        self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=2, stride=2)
        self.norm = nn.LayerNorm(embed_dim)
        self.flatten = flatten
        self.perturb_u = perturb_u
        self.perturb_d = perturb_d
    
    def forward(self, x):
        B, C, H, W = x.shape
        x = self.proj(x)
        if self.flatten:
            x = x.flatten(2).transpose(1, 2)
        else:
            x = x.permute(0, 2, 3, 1)
        x = self.norm(x)
        if self.perturb_u:
            x = x + torch.ones_like(x) * 1e-06
        elif self.perturb_d:
            x = x - torch.ones_like(x) * 1e-06
        return x

# Create instance with flatten=True, no perturbation
patch_embed = PatchEmbed(in_channels=3, embed_dim=4, flatten=True, perturb_u=False, perturb_d=False)

# Create input tensor: batch_size=2, channels=3, height=8, width=8
x = torch.randn(2, 3, 8, 8)

ARGS = {
    "self": patch_embed,
    "x": x
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
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 3, dtype family float, shape (2, 16, 4) — shape (2, 16, 4) 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
swin_patchmerging_forward Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
GoatWu/APHQ-ViT/utils/block_recon.py
code served (permissive licence) · get_code("c3aa10aca8e3d4f2")
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) and returned Tensor, ndim 4, dtype family float, shape (2, 2, 3, 8) 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 SwinPatchMerging(nn.Module):
    def __init__(self, in_channels, out_channels, perturb_u=False, perturb_d=False):
        super().__init__()
        self.norm = nn.LayerNorm(in_channels * 4)
        self.reduction = nn.Linear(in_channels * 4, out_channels)
        self.perturb_u = perturb_u
        self.perturb_d = perturb_d
    
    def forward(self, x):
        B, H, W, C = x.shape
        x = x.reshape(B, H // 2, 2, W // 2, 2, C).permute(0, 1, 3, 4, 2, 5).flatten(3)
        x = self.norm(x)
        x = self.reduction(x)
        if self.perturb_u:
            x = x + torch.ones_like(x) * 1e-06
        elif self.perturb_d:
            x = x - torch.ones_like(x) * 1e-06
        return x

# Create a small instance of the module
in_channels = 4
out_channels = 8
module = SwinPatchMerging(in_channels=in_channels, out_channels=out_channels, perturb_u=False, perturb_d=False)

# Create input tensor with shape (B, H, W, C)
# B=2, H=4, W=6, C=4 (H and W must be even for the reshape operation)
x = torch.randn(2, 4, 6, 4)

ARGS = {
    "self": module,
    "x": x
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
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 4, dtype family float, shape (2, 2, 3, 8) — shape (2, 2, 3, 8) 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
vit_block_forward Ran
ran; our contract draft was wrong, not the code
GoatWu/APHQ-ViT/utils/block_recon.py
code served (permissive licence) · get_code("0afb8b4e757385ce")
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) and returned Tensor, ndim 3, dtype family float, shape (2, 3, 4) 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 DropPath(nn.Module):
    def __init__(self, drop_prob=0.0):
        super().__init__()
        self.drop_prob = drop_prob
    
    def forward(self, x):
        return x

class LayerScale(nn.Module):
    def __init__(self, dim, init_value=1e-4):
        super().__init__()
        self.gamma = nn.Parameter(torch.ones(dim) * init_value)
    
    def forward(self, x):
        return x * self.gamma

class Attention(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.qkv = nn.Linear(dim, dim * 3)
        self.proj = nn.Linear(dim, dim)
    
    def forward(self, x):
        return self.proj(x)

class MLP(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.fc1 = nn.Linear(dim, dim * 4)
        self.fc2 = nn.Linear(dim * 4, dim)
    
    def forward(self, x):
        return self.fc2(torch.relu(self.fc1(x)))

class Norm(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.norm = nn.LayerNorm(dim)
    
    def forward(self, x):
        return self.norm(x)

class ViTBlock(nn.Module):
    def __init__(self, dim=4, perturb_u=False, perturb_d=False):
        super().__init__()
        self.norm1 = Norm(dim)
        self.attn = Attention(dim)
        self.ls1 = LayerScale(dim)
        self.drop_path1 = DropPath()
        
        self.norm2 = Norm(dim)
        self.mlp = MLP(dim)
        self.ls2 = LayerScale(dim)
        self.drop_path2 = DropPath()
        
        self.perturb_u = perturb_u
        self.perturb_d = perturb_d
    
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = x + self.drop_path1(self.ls1(self.attn(self.norm1(x))))
        x = x + self.drop_path2(self.ls2(self.mlp(self.norm2(x))))
        if self.perturb_u:
            x = x + torch.ones_like(x) * 1e-06
        elif self.perturb_d:
            x = x - torch.ones_like(x) * 1e-06
        return x

vit_block = ViTBlock(dim=4, perturb_u=False, perturb_d=False)
x = torch.randn(2, 3, 4)

ARGS = {
    "self": vit_block,
    "x": x
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
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 3, dtype family float, shape (2, 3, 4) — shape (2, 3, 4) 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
AdaRoundQuantizer Not yet run
unverified (harvested, no recorded run)
GoatWu/APHQ-ViT/utils/block_recon.py
code served (permissive licence) · get_code("e57b20bac95de843")
How it ran

no invocation recorded.

BlockReconstructor Not yet run
unverified (harvested, no recorded run)
GoatWu/APHQ-ViT/utils/block_recon.py
code served (permissive licence) · get_code("a69a114345a6be8b")
How it ran

no invocation recorded.

QuantCalibrator Not yet run
unverified (harvested, no recorded run)
GoatWu/APHQ-ViT/utils/block_recon.py
code served (permissive licence) · get_code("14974a54218e1889")
How it ran

no invocation recorded.

UniformQuantizer Not yet run
unverified (harvested, no recorded run)
GoatWu/APHQ-ViT/utils/block_recon.py
code served (permissive licence) · get_code("40e2f2d6bcc163d9")
How it ran

no invocation recorded.

swin_block_forward Not yet run
unverified (harvested, no recorded run)
GoatWu/APHQ-ViT/utils/block_recon.py
code served (permissive licence) · get_code("44a6dd7e559c25bb")
How it ran

no invocation recorded.

Also present in other papers' code

Of 9 samples lifted from this paper's linked repositories, 9 carry a function identity and 0 do not. Of the 9 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 9 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.

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-22.

Repositories linked to this paper

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

Abstract

Vision Transformers (ViTs) have become one of the most commonly used backbones for vision tasks. Despite their remarkable performance, they often suffer significant accuracy drops when quantized for practical deployment, particularly by post-training quantization (PTQ) under ultra-low bits. Recently, reconstruction-based PTQ methods have shown promising performance in quantizing Convolutional Neural Networks (CNNs). However, they fail when applied to ViTs, primarily due to the inaccurate estimation of output importance and the substantial accuracy degradation in quantizing post-GELU activations. To address these issues, we propose APHQ-ViT, a novel PTQ approach based on importance estimation with Average Perturbation Hessian (APH). Specifically, we first thoroughly analyze the current approximation approaches with Hessian loss, and propose an improved average perturbation Hessian loss. To deal with the quantization of the post-GELU activations, we design an MLP Reconstruction (MR) method by replacing the GELU function in MLP with ReLU and reconstructing it by the APH loss on a small unlabeled calibration set. Extensive experiments demonstrate that APHQ-ViT using linear quantizers outperforms existing PTQ methods by substantial margins in 3-bit and 4-bit across different vision tasks. The source code is available at https://github.com/GoatWu/APHQ-ViT.

For agents

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

get_harvested_code_for_paper("2504.02508")
get_code_for_paper("2504.02508")
have("2504.02508")

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

curl https://syntology.ai/api/ran/2504.02508.json

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

[![Syntology run record](https://syntology.ai/api/ran/2504.02508.svg)](https://syntology.ai/paper/2504.02508)

Connect an agent — have() is free.