ncnn icon indicating copy to clipboard operation
ncnn copied to clipboard

pnnx: exported python loses precision for float16 scalar-left division

Open Edwardssss opened this issue 1 month ago • 0 comments

error log | 日志或报错信息 | ログ

The exported PyTorch model produces a different float16 result for scalar-left division. No exception is raised, but the output differs from the source model:

Input:    [[5.0, -5.0]] (float16)
Expected: [[0.60009765625, -0.60009765625]]
Actual:   [[0.599609375, -0.599609375]]

The absolute difference is 0.00048828125 for each element.

context | 编译/运行环境 | バックグラウンド

  • ncnn master: c15904bb8918187ec100f1ebe708942af83b84be
  • OS: Linux
  • Python: 3.13.11
  • Converter: pnnx
  • Input dtype: torch.float16
  • Affected output: pnnx-exported PyTorch Python model

The issue reproduces with both TorchScript scalar-left division and ONNX Div with scalar or single-element initializers. It is not specific to the ONNX sequence elimination changes.

how to reproduce | 复现步骤 | 再現方法

  1. Save and run the following script to generate scalar_div.pt:

    import torch
    
    class Model(torch.nn.Module):
        def forward(self, x):
            return torch.div(3.0, x)
    
    x = torch.tensor([[5.0, -5.0]], dtype=torch.float16)
    model = Model().eval()
    torch.jit.trace(model, x).save('scalar_div.pt')
    print('Expected:', model(x).tolist())
    
  2. Convert the model with pnnx:

    pnnx scalar_div.pt inputshape=[1,2]f16
    
  3. Run the exported model from the same directory:

    import torch
    import scalar_div_pnnx
    
    x = torch.tensor([[5.0, -5.0]], dtype=torch.float16)
    y = scalar_div_pnnx.Model().eval()(x)
    print('Actual:', y.tolist())
    

more | 其他 | その他

The exported expression uses 3.0 / x, invoking Tensor.__rtruediv__. Its reciprocal-then-multiply path rounds twice for float16, unlike torch.div(3.0, x).

Exporting literal-left division as torch.div(a, b) instead preserves the original operation's result. The regression test fails on the unmodified master and passes with this change.

The source reproducer deliberately uses torch.div, not Python 3.0 / x: tracing the latter can already record reciprocal/multiply operations in the source graph, which is a different case.

Edwardssss avatar Oct 15 '26 04:10 Edwardssss