Skip to content

npu-pack: import links the kernel set into the container, so the last step of the OGA-pack route is not a hand-made symlink - #1290

Merged
bong-water-water-bong merged 7 commits into
mainfrom
1bit/671-pack-import-kernels
Nov 6, 2026
Merged

bong-water-water-bong merged 7 commits into
mainfrom
1bit/671-pack-import-kernels

Conversation

@bong-water-water-bong

@bong-water-water-bong bong-water-water-bong commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

What this closes

1bit npu-pack import writes a model directory, and 1bit serve -m <dir> --device npu looks for that
directory's kernels in <dir>/npu/. Nothing filled that in: after every import the last step was a
hand-made symlink, which is the one command in the route that the docs cannot give a user because it
depends on where their kernel set lives. This PR makes it part of the import:

$ 1bit npu-pack import ~/models/oga/Phi-3.5-mini-instruct_rai_1.8.0_npu_4K \
      -o ctr-phi35-kern --weight-layout b8 --kernels ~/ogaload/oga13/kernels-phi35-b8
imported 291 tensors, 454392 q4_1 tiles into ctr-phi35-kern
  ...
  kernels:    ctr-phi35-kern/npu -> /home/bcloud/ogaload/oga13/kernels-phi35-b8  (8 full_i8 ELFs: 4 M=16 twins, 8 of the _b8 family)

Two properties, both deliberate

  • The set is checked against --weight-layout before anything is written. The forward resolves kernels
    by name (full_i8_<role>_K<k>_N<n>[_b8][_m16].elf), so a b8 container linked to a row-major set loads
    and then fails at serve time with "no ELF for K=.. N=.." — which reads like a broken container. That is
    now refused by name, and because the check runs first, a bad --kernels leaves no container behind.
  • An existing npu/ that is a real directory is left alone (and named in a warning): replacing someone's
    kernels to make room for a link is not an importer's decision. A stale link is replaced, which is what
    re-running an import over its own output does.

Leaving --kernels out is exactly the previous behaviour, so no existing container changes.

Measured proof

Device-free first — the refusal cases, which is where a wrong set would otherwise be discovered two
commands later:

$ 1bit npu-pack import <pack> -o /tmp/x --kernels ~/ogaload/oga13/kernels-phi35-b8      # row-major names
1bit npu-pack: --kernels .../kernels-phi35-b8: this set is the _b8 (blocked) family but the container
  declares no weight layout, so it needs `--weight-layout b8` to say so      (rc 1, /tmp/x not created)
$ 1bit npu-pack import <pack> -o /tmp/x --kernels /tmp/not-a-set
1bit npu-pack: --kernels /tmp/not-a-set: no full_i8_*.elf in that directory: ...

Then on the array, on the container this PR's flag produced, with no hand-made symlink anywhere in
the run
— npu-hold -l ogaload-671-kernels-array -t 8 (inside the c31 hold: no ticket over 10 min),
queued 358 s, held 25 s, rc 0, amdxdna ERROR 0:

== 8 ELFs via /tmp/ctr-phi35-kern/npu, layout "q4nx_weight_layout": "b8"
1bit serve: /tmp/ctr-phi35-kern is a model-generic container: serving it through the per-op forward (kernels /tmp/ctr-phi35-kern/npu)
[forward] weight layout: b8 blocked 8x8 microtiles, tile-n-major (kernels carry the _b8 suffix)
full ELF ok: uuid=b1bb97a1... x8 (eight distinct uuids)
1bit forward-serve: ctr-phi35-kern ready on http://127.0.0.1:18772 (full ELF)
== serve: 'The capital of France is' -> ' Paris.\n\n\n### Answer'   (8 greedy tokens)

(The 20.9 s that request took is not a speed number: the box was at loadavg 12-15, and this container's
prefill term is what #1243 fixes.) An earlier attempt at this leg was blocked for 361 s by another lane's
idle forward-serve holding the engine device lock; a host-GEMM run of the same container gave the same
answer text. Both are recorded in the lane's state file rather than dropped.

tests/npu_pack_import_test.cpp gains a device-free leg for kernel_set_refusal() (b8 set for a b8
container accepted; row-major set for a b8 container refused; b8 set with no layout key refused; empty
directory, a directory with no ELF, and a non-.elf file all refused) — run by ctest's existing
npu_pack_import entry with no pack present.

Docs: docs/npu.md, "Linking the kernel set the container will be served with" (in the OGA pack section,
next to the import/conversion contract it belongs to).

Part of #671: this removes the last hand step in the route the issue describes. The tracker's own closing
bar is measurement (vendor-parity rows), so it is not closed by this PR — the ledger of what has landed and
what remains is in a comment on the issue.

…ast step of the OGA-pack route is not a hand-made symlink

`1bit serve -m <dir> --device npu` looks for a model directory's kernels in `<dir>/npu/`, and
nothing filled that in: after every import the last step was a symlink made by hand, which is the one
command the route cannot give a user because it depends on where their kernel set lives.

   1bit npu-pack import <pack> -o <dir> --weight-layout b8 --kernels <kernel dir>

checks the set against --weight-layout *before* it writes anything -- a b8 container needs the _b8 ELF
names and a no-layout container needs the plain ones, and the wrong family links cleanly and then fails
at load with "no ELF for K=.. N=..", which reads like a broken container -- then links the directory as
<dir>/npu and prints what it linked (ELF count, M=16 twins, family). An existing npu/ that is a real
directory is left alone and named; a stale link is replaced, which is what re-importing over its own
output does. Leaving --kernels out is exactly the previous behaviour.

Measured on the Phi-3.5-mini pack (import device-free, both refusals and the accepted case):
  --kernels <row-major set> with no --weight-layout  -> rc 1, nothing written, named refusal
  --kernels <dir with no full_i8 ELF>                -> rc 1, nothing written, named refusal
  --weight-layout b8 --kernels kernels-phi35-b8      -> 291 tensors, 454392 tiles, fp32 scale/zero
     exact for 100.00% of groups, 'npu -> ... (8 full_i8 ELFs: 4 M=16 twins, 8 of the _b8 family)'
A serve of that container, with no hand-made link anywhere in the run, reports
  'is a model-generic container: serving it through the per-op forward (kernels <dir>/npu)'
and answers 'The capital of France is' -> ' Paris.' (the array leg was blocked: another lane's
forward-serve held the engine device lock for 4h41 at the time of the run).

Test: tests/npu_pack_import_test.cpp gains a device-free leg for kernel_set_refusal() (b8/b8 ok,
rm/b8 refused, b8/no-layout refused, empty dir, no-ELF dir, a non-.elf file), run by ctest's existing
npu_pack_import entry with no pack present. Docs: docs/npu.md, the new subsection in the OGA-pack
section.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY at bbc9f129.

Built this head and ran the documented commands against the real pack and the real b8 set (Phi-3.5-mini-instruct_rai_1.8.0_npu_4K

  • ~/ogaload/oga13/kernels-phi35-b8), plus its own test:
ctest -R npu_pack_import                                                Passed  0.15 s
--kernels <b8 set>, no --weight-layout                                  rc 1, no container written
  "this set is the _b8 (blocked) family but the container declares no weight layout, so it needs `--weight-layout b8`"
--kernels on a directory with no ELFs                                   rc 1, no container written
  "no full_i8_*.elf in that directory: a kernel set is the forward's per-shape ELFs, named full_i8_<role>_K<k>_N<n>[_b8][_m16].elf …"
--weight-layout b8 with a row-major set                                 rc 1
  "the container declares q4nx_weight_layout "b8" but this set has no _b8 ELF, so the forward would look for names that are not there"

(The rc=1s are the tool's own — the first pass of this through tail printed rc=0, which is my own recurring trap, not yours.)

The happy path is the body's line, verbatim, 12.4 s, rc 0:

kernels:    /tmp/x1290/npu -> /home/bcloud/ogaload/oga13/kernels-phi35-b8  (8 full_i8 ELFs: 4 M=16 twins, 8 of the _b8 family)

and /tmp/x1290/npu is a symlink that resolves to all eight ELFs.

Both deliberate properties hold, tested by doing them:

  • re-running the import over its own output replaces the stale link (rc 0, same summary line);
  • a npu/ that is a real directory is left alone: kernels: /tmp/x1290/npu already holds its own kernels; --kernels … not linked, rc 0, and the marker file I put in it survived — so an importer cannot eat someone's kernels, which is the right
    call and the one I would have argued for.

The unit test's refusal matrix is the useful part beyond the happy path: it pins the mixed case (a row-major container
accepting a set that also carries b8 twins) and full_i8_*.elf.bak not being a kernel, which are exactly the shapes a
name-based check gets wrong.

One form nit, TISSUES-ALL rule 3: the body references #671 in prose and has no Fixes/Refs line. If this is one step
of that umbrella rather than its end, Refs #671 plus a line in the issue about what remains is what the board reads; if the
hand-made-symlink step was the last thing #671 needed, Fixes #671 and the issue closes itself.

Not re-run: the on-array serve row. The NPU lock is still pinned by another lane's idle host-GEMM serve (reported to the
orchestrator), and the container this PR produced is linked correctly, which is the part import owns.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY at 9cfebb60 — I compiled the test and the importer at this head and ran it (all checks passed), then falsified the new refusal and watched five of its arms go red, which is what makes the green meaningful.

Build + run (g++-16 -std=c++20, this box, the tree's own npu/ sources plus -lpcre2-8 — the same objects onebit_npu holds):

tests/npu_pack_import_test tests/golden
  … weight layout: b8 allowed, pb16i/t2s/unknown refused
  all npu-pack checks passed -- pack leg SKIPPED, no pack directory given      rc 0

The crafted/golden legs include the new test_kernel_set_refusal(); check() is silent on success, so a green run plus the summary line is the evidence it ran rather than skipped.

The new arms bite — mutant test. I compiled the same test against a pack_import.cpp whose kernel_set_refusal() returns "accept" unconditionally:

FAIL kernels: a b8 set is refused when the container declares no layout (it needs --weight-layout b8)
FAIL kernels: a row-major set is refused for a b8 container
FAIL kernels: an empty directory is refused
FAIL kernels: a directory with no full_i8 ELF is refused
FAIL kernels: a file that is not an .elf is not a kernel
                                                                          rc 1

Five refusals red, the three acceptance arms still green — so the arm tests the rule and not itself. The rule is the one the body states, including the subtlety that a mixed set (row-major ELFs with b8 twins alongside) is accepted for a row-major container, which is what a real ogaload set looks like.

"Checked before anything is written" is true in the code, not just in the prose. In pack_import.cpp the refusal runs at :1845, the --kernels directory is read and validated there, and import_pack(...) (the first thing that writes) is called after it — so a bad --kernels leaves no container behind, which is the property a user notices.

"A real directory is left alone" is implemented as the body says: fs::is_directory && !fs::is_symlink → warning that names both paths and keeps the directory, otherwise fs::remove + create_directory_symlink. Replacing someone's kernels silently would be the wrong default, and this does not.

Docs: docs/npu.md gains the --kernels form of the import plus why the set must match --weight-layout; the tool's own output line (kernels: <dir>/npu -> <set> (N full_i8 ELFs: … M=16 twins, … _b8 family)) is what a user can check afterwards. Tool + header + test + docs in one PR.

Not run: a real end-to-end import (1bit npu-pack import … --kernels …) with a live pack and kernel set — that needs the 1bit binary, and I did not spend the queue's time on an engine build for a link-and-refuse path whose logic the test covers directly. The pack leg of the test is also skipped without a pack directory; if a pack is handy for the next run, tests/npu_pack_import_test <golden> <pack dir> exercises it.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY at 0315a13a — main merges only; the reviewed content is byte-identical to the head I verdicted.

Checked rather than assumed: the PR's own added lines (own diff vs merge-base, which excludes everything main brought in) hash to 4837f32f4f28 at the head I reviewed and to the same value here, so no line of this PR's change moved — only its base did (the branch now sits on newer main).

Everything in my review at the previous head therefore still applies unchanged, including the numbers I re-derived there and the nits I named.

@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

671 - Partially compliant

Compliant requirements:

  • Import Ryzen AI OGA NPU model packs on Linux through the engine
  • Parse quantized weights into Q4NX container with layout-version field
  • Generate per-shape full ELFs for the pack model's geometry
  • Ensure the last step of the OGA-pack route is not a hand-made symlink
  • Support for the first pack (Qwen2.5-0.5B-Instruct npu_4K) with greedy output identical to vendor stack

Non-compliant requirements:

  • Support for a second pack from the public collection

Requires further human verification:

  • Verification that the second pack from the public collection works as expected
  • Confirmation that the performance metrics (decode tok/s at ctx 128/512/2048 and prefill at 128/2048) match vendor stack
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Kernel Set Validation

The new kernel_set_refusal function validates that the kernel set matches the declared weight layout before any files are written. This is a good defensive measure to prevent containers from being created that would fail at serve time due to mismatched kernel names. However, the validation logic could be made more robust by ensuring that all kernel files in the set are properly named and match the expected pattern for the given layout.

std::string kernel_set_refusal(const std::vector<std::string>& file_names, const std::string& layout) {
    bool any_elf = false, any_b8 = false, any_plain = false;
    for (const std::string& n : file_names) {
        if (n.rfind("full_i8_", 0) != 0 || n.size() < 9 || n.compare(n.size() - 4, 4, ".elf") != 0)
            continue;
        any_elf = true;
        if (n.find("_b8") != std::string::npos) any_b8 = true;
        else any_plain = true;
    }
    if (!any_elf)
        return "no full_i8_*.elf in that directory: a kernel set is the forward's per-shape ELFs, named "
               "full_i8_<role>_K<k>_N<n>[_b8][_m16].elf, and nothing was found to link in";
    if (layout == "b8" && !any_b8)
        return "the container declares q4nx_weight_layout \"b8\" but this set has no _b8 ELF, so the "
               "forward would look for names that are not there";
    if (layout != "b8" && !any_plain)
        return "this set is the _b8 (blocked) family but the container declares no weight layout, so it "
               "needs `--weight-layout b8` to say so";
    return "";
}
Symlink Creation

The code creates a symlink from <out_dir>/npu to the kernel set directory. This is a clean way to handle the kernel linking, but it's important to ensure that the symlink is created with an absolute path to avoid issues when the model directory is moved. The code already handles this correctly by using fs::absolute(kernels).

if (!kernels.empty()) {
    // A model directory carries its own kernels in `npu/`; serve resolves the link, so the
    // container stays usable from wherever it was written.  An existing `npu/` that is a real
    // directory is left alone (and named), because deleting someone's kernels to make room for a
    // link is not an importer's decision.
    const std::string link = out + "/npu";
    std::error_code ec;
    const fs::file_status st = fs::symlink_status(link, ec);
    size_t n = 0, n_m16 = 0, n_b8 = 0;
    for (fs::directory_iterator it(kernels, ec), end; !ec && it != end; it.increment(ec)) {
        const std::string f = it->path().filename().string();
        if (f.rfind("full_i8_", 0) != 0 || f.size() < 9 || f.compare(f.size() - 4, 4, ".elf") != 0)
            continue;
        n++;
        if (f.find("_m16") != std::string::npos) n_m16++;
        if (f.find("_b8") != std::string::npos) n_b8++;
    }
    if (fs::is_directory(st) && !fs::is_symlink(st)) {
        std::printf("  kernels:    %s already holds its own kernels; --kernels %s not linked\n",
                    link.c_str(), kernels.c_str());
        std::fprintf(stderr,
                     "WARNING: %s is a real directory, so the imported container keeps it. Remove\n"
                     "  it and re-run the import if the set at %s is the one it should serve.\n",
                     link.c_str(), kernels.c_str());
    } else {
        fs::remove(link, ec);  // a stale link (or a stray file) is replaced, not merged
        fs::create_directory_symlink(fs::absolute(kernels), link, ec);
        if (ec) throw std::runtime_error("cannot link " + link + " -> " + kernels + ": " + ec.message());
        std::printf("  kernels:    %s -> %s  (%zu full_i8 ELFs: %zu M=16 twins, %zu %s)\n", link.c_str(),
                    kernels.c_str(), n, n_m16, n_b8,
                    layout == "b8" ? "of the _b8 family" : "of the row-major family");
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant