ncnn icon indicating copy to clipboard operation
ncnn copied to clipboard

ARM fp16 arithmetic produces all-NaN output for a ViT-tiny graph / model (ncnn 20260526)

Open cesarpgouveia opened this issue 3 months ago • 1 comments

On arm64-v8a, setting use_fp16_arithmetic = true makes a ViT-tiny (patch16, 224×224, 256-d output) return 256/256 non-finite values. use_fp16_storage and fp32 are numerically clean on the identical setup (cosine ≥0.9994 vs the ONNX reference).

Environment: ncnn 20260526, arm64-v8a static build, Samsung Galaxy A35 (Exynos 1380, Cortex-A78+A55, asimdhp present, no i8mm), Android 14.

Repro: load the model from file into a raw ncnn::Net, single-threaded, no app framework; set opt.use_fp16_arithmetic = true; run one 1×3×224×224 float input. Output blob is entirely NaN. Set it to false → correct output.

The model was converted from ONNX with pnnx. x86 is unaffected. Happy to provide a reproducing .param/.bin if useful.

cesarpgouveia avatar Aug 25 '26 15:08 cesarpgouveia

Hi @cesarpgouveia ,thanks for detailed report. Could you update to the latest master and re-run this model first? Several ARM fp16 arithmetic fixes landed after this report:

  • #6979 (2026-09-09) arm: fp16 tanh_ps_f16 saturated at 1.044, fast gelu returned +0.022*|x| for large negative x
  • #6982 (2026-09-09) riscv: same fp16 tanh saturation

x86 is unaffected by construction, the CPU fp16 arithmetic path only exists for ARM. If the non-finite output is still there after the update, this small tool scans every blob and prints the first one containing inf/nan plus the layer that produces it, which shows where the graph first goes wrong:

g++ -O2 -std=c++11 -fopenmp ncnn_blob_scan.cpp -o ncnn_blob_scan \
    -I <ncnn>/src -I <ncnn>/build/src -L <ncnn>/build/src -lncnn -lpthread
./ncnn_blob_scan model.param model.bin 224 224 3 --raw your_input.bin

--fp32 / --fp16 / --nopack reproduce the three configurations you tested. It would also help to know the layer list of the model: awk 'NR>2{print $1}' model.param | sort -u.

// g++ -O2 -std=c++11 -fopenmp ncnn_blob_scan.cpp -o ncnn_blob_scan -I ncnn/src -I ncnn/build/src -L ncnn/build/src -lncnn -lpthread
// ./ncnn_blob_scan model.param model.bin [w h c] [--raw in.bin] [--fp32|--fp16|--nopack] [--threads N]
#include "net.h"
#include "cpu.h"
#include "c_api.h"
#include <algorithm>
#include <cmath>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>

struct Blob
{
    std::string name, layer_type, layer_name;
};

static std::vector<std::string> tokens(const char* line)
{
    std::vector<std::string> t;
    const char* p = line;
    while (*p)
    {
        while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') p++;
        const char* b = p;
        while (*p && *p != ' ' && *p != '\t' && *p != '\r' && *p != '\n') p++;
        if (p > b) t.push_back(std::string(b, p - b));
    }
    return t;
}

// blob index order matches ncnn: bottoms take a slot on first appearance, tops always a fresh slot
static int parse_param(const char* path, std::vector<Blob>& blobs)
{
    FILE* fp = fopen(path, "rb");
    if (!fp) { fprintf(stderr, "cannot open %s\n", path); return -1; }
    char line[8192];
    if (!fgets(line, sizeof(line), fp) || !fgets(line, sizeof(line), fp)) { fclose(fp); return -1; }
    std::vector<std::string> names;
    while (fgets(line, sizeof(line), fp))
    {
        std::vector<std::string> t = tokens(line);
        if (t.size() < 4) continue;
        int n_in = atoi(t[2].c_str()), n_out = atoi(t[3].c_str());
        if ((int)t.size() < 4 + n_in + n_out) continue;
        for (int j = 0; j < n_in; j++)
        {
            if (std::find(names.begin(), names.end(), t[4 + j]) != names.end()) continue;
            Blob b = {t[4 + j], "(external)", ""};
            blobs.push_back(b);
            names.push_back(b.name);
        }
        for (int j = 0; j < n_out; j++)
        {
            Blob b = {t[4 + n_in + j], t[0], t[1]};
            blobs.push_back(b);
            names.push_back(b.name);
        }
    }
    fclose(fp);
    return 0;
}

// extract(..., 0) already unpacks and converts to fp32; index is relative to the whole blob
static void scan(const ncnn::Mat& m, size_t& nan, size_t& inf, size_t& idx, float& val)
{
    nan = inf = 0;
    idx = (size_t)-1;
    val = 0.f;
    if (m.elembits() != 32) return;
    size_t off = 0;
    for (int q = 0; q < (m.dims <= 2 ? 1 : m.c); q++)
    {
        const ncnn::Mat ch = m.dims <= 2 ? m : m.channel(q);
        const size_t n = (size_t)ch.w * ch.h * ch.d * ch.elempack;
        const float* p = ch;
        for (size_t i = 0; i < n; i++)
        {
            if (!std::isnan(p[i]) && !std::isinf(p[i])) continue;
            if (std::isnan(p[i])) nan++;
            else inf++;
            if (idx == (size_t)-1) { idx = off + i; val = p[i]; }
        }
        off += n;
    }
}

static void usage(const char* argv0)
{
    printf("usage: %s model.param model.bin [w h c] [--raw in.bin] [--fp32|--fp16|--nopack] [--threads N]\n", argv0);
}

int main(int argc, char** argv)
{
    if (argc < 3) { usage(argv[0]); return -1; }

    int w = 224, h = 224, c = 3, threads = 1, npos = 0;
    const char* raw = 0;
    bool packed = true, storage = true, arithmetic = true, packing = true;

    int i = 3;
    for (; i < argc && argv[i][0] != '-'; i++, npos++)
    {
        int v = atoi(argv[i]);
        if (npos == 0) w = v;
        else if (npos == 1) h = v;
        else c = v;
    }
    if (npos && npos != 3) { fprintf(stderr, "input shape needs w h c\n"); return -1; }
    for (; i < argc; i++)
    {
        if (!strcmp(argv[i], "--fp32")) packed = storage = arithmetic = false;
        else if (!strcmp(argv[i], "--fp16")) arithmetic = false;
        else if (!strcmp(argv[i], "--nopack")) packing = false;
        else if (!strcmp(argv[i], "--raw") && i + 1 < argc) raw = argv[++i];
        else if (!strcmp(argv[i], "--threads") && i + 1 < argc) threads = atoi(argv[++i]);
        else { fprintf(stderr, "unknown option %s\n", argv[i]); return -1; }
    }

    std::vector<Blob> blobs;
    if (parse_param(argv[1], blobs) != 0) return -1;

    ncnn::Net net;
    net.opt.use_vulkan_compute = false;
    net.opt.num_threads = threads;
    net.opt.use_packing_layout = packing;
    net.opt.use_fp16_packed = packed;
    net.opt.use_fp16_storage = storage;
    net.opt.use_fp16_arithmetic = arithmetic;
    if (net.load_param(argv[1]) != 0 || net.load_model(argv[2]) != 0)
    {
        fprintf(stderr, "load model failed\n");
        return -1;
    }

    printf("ncnn %s  asimdhp=%d  fp16_storage=%d fp16_arithmetic=%d packing=%d threads=%d\n",
           ncnn_version(), ncnn::cpu_support_arm_asimdhp(), (int)storage, (int)arithmetic, (int)packing, threads);

    ncnn::Mat in(w, h, c);
    if (raw)
    {
        FILE* fp = fopen(raw, "rb");
        if (!fp || fread(in.data, sizeof(float), (size_t)w * h * c, fp) != (size_t)w * h * c)
        {
            fprintf(stderr, "cannot read %s\n", raw);
            return -1;
        }
        fclose(fp);
    }
    else
    {
        float* p = in;
        for (size_t k = 0; k < (size_t)w * h * c; k++) p[k] = (float)((k * 2654435761u) % 2048) / 1024.f - 1.f;
    }

    ncnn::Extractor ex = net.create_extractor();
    ex.set_light_mode(false); // keep every intermediate blob alive

    int n_input = 0;
    for (size_t k = 0; k < blobs.size(); k++)
    {
        if (blobs[k].layer_type != "Input") continue;
        ex.input(blobs[k].name.c_str(), in);
        n_input++;
    }
    if (!n_input) { fprintf(stderr, "no Input layer in param\n"); return -1; }

    size_t scanned = 0, bad = 0;
    int first = -1;
    for (size_t k = 0; k < blobs.size(); k++)
    {
        if (blobs[k].layer_type == "(external)") continue;

        ncnn::Mat out;
        if (ex.extract(blobs[k].name.c_str(), out, 0) != 0 || out.empty()) continue;
        scanned++;

        size_t nan = 0, inf = 0, idx = 0;
        float val = 0.f;
        scan(out, nan, inf, idx, val);
        if (!nan && !inf) continue;

        bad++;
        if (first < 0) first = (int)k;
        printf("%s blob[%d] %s %s %dx%dx%d nan=%zu inf=%zu first@%zu=%s\n",
               first == (int)k ? ">>>" : "   ", (int)k, blobs[k].layer_type.c_str(), blobs[k].name.c_str(),
               out.w, out.h, out.c, nan, inf, idx, std::isnan(val) ? "nan" : (val > 0 ? "+inf" : "-inf"));
    }

    printf("scanned %zu blobs, non-finite %zu\n", scanned, bad);
    if (first >= 0)
    {
        printf("FIRST non-finite: blobs[%d] '%s' from %s '%s'\n",
               first, blobs[first].name.c_str(), blobs[first].layer_type.c_str(), blobs[first].layer_name.c_str());
        return 1;
    }
    printf("no inf/nan found\n");
    return 0;
}

Edwardssss avatar Sep 25 '26 09:09 Edwardssss