SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2503.15465 · 2025

FP4DiT: Towards Effective Floating Point Quantization for Diffusion Transformers

Keith Mills, Di Niu, Ruichen Chen

arXiv · PDF · Open in the Atlas

Code that ran

3 of 4 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 1 has no contract verdict; 1 failure of our instrument; 1 no recorded run), measured 2026-11-22; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; 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/2503.15465.json · badge: /api/ran/2503.15465.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
cccrrrccc/FP4DiT community
Papers with Code archive
3 ran · 1 no recorded run
FunctionStatusWhere it lives
UniformAffineQuantizer Ran
ran on a synthesized input
cccrrrccc/FP4DiT/qdiff/quant_layer.py
code served (permissive licence) · get_code("461c9e5368bcce0c")
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 2, 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
import numpy as np
import logging

# Setup logging
logging.basicConfig(level=logging.INFO)

# Import the class (assuming it's defined above or in the same file)
from torch.autograd import Function

class RoundStraightThrough(Function):
    @staticmethod
    def forward(ctx, x):
        return torch.round(x)

    @staticmethod
    def backward(ctx, output_grad):
        return output_grad

def round_ste(x: torch.Tensor):
    return (x.round() - x).detach() + x

round_ste_func = RoundStraightThrough.apply

def lp_loss(pred, tgt, p=2.0, reduction='none'):
    if reduction == 'none':
        return (pred - tgt).abs().pow(p).sum(1).mean()
    else:
        return (pred - tgt).abs().pow(p).mean()

def quantize_to_fp8_ste_MM(x_float: torch.Tensor, n_bits: int, maxval: torch.Tensor, num_mantissa_bits: torch.Tensor, sign_bits: int) -> torch.Tensor:
    maxval = maxval.to(x_float.device)
    maxval = torch.clamp(maxval, min=0.0001)
    num_mantissa_bits = num_mantissa_bits.to(x_float.device)
    M = torch.clamp(round_ste_func(num_mantissa_bits), 0, n_bits - sign_bits)
    E = n_bits - sign_bits - M
    if maxval.shape[0] != 1 and len(maxval.shape) != len(x_float.shape):
        maxval = maxval.view([-1] + [1] * (len(x_float.shape) - 1))
    bias = 2 ** E - torch.log2(maxval) + torch.log2(2 - 2 ** (-M)) - 1
    minval = -maxval if sign_bits == 1 else torch.zeros_like(maxval)
    xc = torch.min(torch.max(x_float, minval), maxval)
    log_scales = torch.clamp(torch.floor(torch.log2(torch.abs(xc) + 1e-8) + bias).detach(), 1.0)
    scales = 2.0 ** (log_scales - M - bias)
    result = round_ste_func(xc / scales) * scales
    return result

class UniformAffineQuantizer(nn.Module):
    def __init__(self, n_bits: int=8, symmetric: bool=False, channel_wise: bool=False, scale_method: str='max', leaf_param: bool=False, always_zero: bool=False, fp: bool=False, mantissa_bits: int=None, weight_group_size: int=None, fp_biased_adaround: bool=True, online_act_quant: bool=False, group_quant: bool=False, **kwargs):
        super(UniformAffineQuantizer, self).__init__()
        self.sym = symmetric
        self.n_bits = n_bits
        self.n_levels = 2 ** self.n_bits if not self.sym else 2 ** (self.n_bits - 1) - 1
        self.delta = None
        self.zero_point = None
        self.inited = False
        self.leaf_param = leaf_param
        self.channel_wise = channel_wise
        self.scale_method = scale_method
        self.running_stat = False
        self.always_zero = always_zero
        self.fp_biased_adaround = fp_biased_adaround
        self.sign_bits = 1
        self.fp = fp
        if mantissa_bits is None:
            if n_bits == 8:
                mantissa_bits = 4
            elif n_bits == 6:
                mantissa_bits = 2
            else:
                mantissa_bits = 1
        self.mantissa_bits = torch.Tensor([float(mantissa_bits)])
        if self.leaf_param:
            self.x_min, self.x_max = (None, None)
        if self.scale_method == 'mse':
            self.alpha_dict = {}

    def forward(self, x: torch.Tensor):
        if self.fp:
            if not self.inited:
                self.delta = torch.tensor(1.0)
                self.inited = True
            return quantize_to_fp8_ste_MM(x, self.n_bits, self.delta, self.mantissa_bits, self.sign_bits)
        else:
            if not self.inited:
                self.delta = torch.tensor(1.0)
                self.zero_point = torch.tensor(0.0)
                self.inited = True
            xc = torch.clamp(x, 0, 1)
            return torch.round(xc / self.delta) * self.delta

INIT_ARGS = {
    'n_bits': 8,
    'symmetric': False,
    'channel_wise': False,
    'scale_method': 'max',
    'leaf_param': False,
    'always_zero': False,
    'fp': False,
    'mantissa_bits': 4,
    'weight_group_size': None,
    'fp_biased_adaround': True,
    'online_act_quant': False,
    'group_quant': False,
}

ARGS = {
    'x': torch.randn(2, 4),
}

if __name__ == '__main__':
    quantizer = UniformAffineQuantizer(**INIT_ARGS)
    output = quantizer(**ARGS)
    print("Output shape:", output.shape)
    print("Output:", output)
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
ipdb, numpy, qdiff, sklearn, 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 — 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)
i Ran
ran, honoured the contract we drafted
cccrrrccc/FP4DiT/qdiff/quant_layer.py
code served (permissive licence) · get_code("3ef53e0af07e8e17")
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 ndarray, ndim 1, dtype family int, shape (1,) 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 numpy as np

def i(x):
    return np.array([x]).astype(np.int32)

ARGS = {
    "x": 42
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type ndarray, ndim 1, dtype family int, shape (1,) — shape (1,) 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
quantize_to_fp8_ste_MM Ran
ran; our contract draft was wrong, not the code
cccrrrccc/FP4DiT/qdiff/quant_layer.py
code served (permissive licence) · get_code("e82768e4a278a16b")
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, 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 logging

torch.manual_seed(0)

# Set up logging
logging.basicConfig(level=logging.INFO)

# Create small test tensors
x_float = torch.randn(2, 4, requires_grad=True)
n_bits = 8
maxval = torch.tensor([1.0], requires_grad=True)
num_mantissa_bits = torch.tensor([3.0], requires_grad=True)
sign_bits = 1

ARGS = {
    'x_float': x_float,
    'n_bits': n_bits,
    'maxval': maxval,
    'num_mantissa_bits': num_mantissa_bits,
    'sign_bits': sign_bits
}
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, 4) — shape (2, 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
RoundStraightThrough Not yet run
unverified (harvested, no recorded run)
cccrrrccc/FP4DiT/qdiff/quant_layer.py
code served (permissive licence) · get_code("bda9db86279f70c1")
How it ran

no invocation recorded.

Also present in other papers' code

Of 4 samples lifted from this paper's linked repositories, 4 carry a function identity and 0 do not. Of the 4 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 4 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

Diffusion Models (DM) have revolutionized the text-to-image visual generation process. However, the large computational cost and model footprint of DMs hinders practical deployment, especially on edge devices. Post-training quantization (PTQ) is a lightweight method to alleviate these burdens without the need for training or fine-tuning. While recent DM PTQ methods achieve W4A8 (i.e., 4-bit weights and 8-bit activations) on integer-based PTQ, two key limitations remain: First, while most existing DM PTQ methods evaluate on classical DMs like Stable Diffusion XL, 1.5 or earlier, which use convolutional U-Nets, newer Diffusion Transformer (DiT) models like the PixArt series, Hunyuan and others adopt fundamentally different transformer backbones to achieve superior image synthesis. Second, integer (INT) quantization is prevailing in DM PTQ but does not align well with the network weight and activation distribution, while Floating-Point Quantization (FPQ) is still under-investigated, yet it holds the potential to better align the weight and activation distributions in low-bit settings for DiT. In this paper, we introduce FP4DiT, a PTQ method that leverages FPQ to achieve W4A6 quantization. Specifically, we extend and generalize the Adaptive Rounding PTQ technique to adequately calibrate weight quantization for FPQ and demonstrate that DiT activations depend on input patch data, necessitating robust online activation quantization techniques. Experimental results demonstrate that FP4DiT achieves higher CLIP, ImageReward and HPSv2 performance compared to integer-based PTQ at the W4A6 and W4A8 precision levels while generating convincing visual content on PixArt-α, PixArt-Σ and Hunyuan. Code is available at https://github.com/cccrrrccc/FP4DiT.

For agents

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

get_harvested_code_for_paper("2503.15465")
get_code_for_paper("2503.15465")
have("2503.15465")

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

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

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

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

Connect an agent — have() is free.