Skip to content

npu: one partition width and one hardware context per model, so the NPU can be shared (engine#2689 item 1) - #2697

Merged
bong-water-water-bong merged 3 commits into
mainfrom
1bit/2689-npu-partition
Nov 16, 2026
Merged

bong-water-water-bong merged 3 commits into
mainfrom
1bit/2689-npu-partition

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Refs #2689 (item 1 of three; the tracking issue stays open)

One width, one hardware context per model. Today the engine opens one hw_context per full ELF: a b8 b8
container's Qwen3-1.7B set is 8 contexts (4 decode roles + 4 prefill roles), each asking the driver for the
whole array. That is the wrong shape for sharing the NPU: with spatial placement two models each get a column
half, but only if each model holds exactly one context at one width. Measured on this box (11-15): the driver
gives a process's second same-width context the other free half, and it refuses a 4-column context next to
an 8-column one in the same process.

What changed

  • NPU_PARTITION=<cols> (npu/forward/engine-src/npu_engine_i8ctx_inc.h, npu/forward/include/elf_partition.h).
    Partition mode: every full ELF the model opens must declare <cols> columns in its
    .note.xrt.configuration, or the load is refused naming the file and its width. The first ELF creates
    the model's one context and every later ELF joins it with hw_context::add_config instead of opening its
    own. Unset (the default), every ELF still opens its own context exactly as before.
  • NPU_I8_SEALED_PREFILL_ELF=<file> (npu/target/xdna/xdna_target.cpp, q4nx_i8_sealed_prefill_instance).
    One sealed M=128 ELF for a b8 container's prefill roles, so prefill can live in the decode context. One
    context cannot hold two instances with the same key — the runtime refuses the second ELF, measured as
    code 501: main:d — so its instances are the decode names with a p_ prefix (main:p_qkvfa, main:p_o,
    main:p_gu, main:p_d). In partition mode a role the ELF does not cover is refused by name, because its
    per-role ELF would be a second main:seq.
  • tests/npu_partition_test.cpp (new, ctest -R npu_partition, registered in CI's target list) and a
    docs/npu.md paragraph with the two settings and the sealed/build.sh … -c 4 --partition 4 line that
    produces such a set.

Host proof

$ ctest -R npu_partition
test 103: npu_partition ... Passed

12 arms: the partition note reads 4 and 8; wrong magic, a 64-bit ELF, a note of another name, a note
section shorter than a note, a truncated section table and a file shorter than an ELF header all read 0
rather than a guess; and the prefill instance table pairs with every role that has a decode instance, keeps
the p_ prefix, and is disjoint from the decode keys.

Mutants, each restored afterwards:

  • reader stub that always answers 8 → 7 arms fail (a 4-column note reads 4, all six rejection arms);
  • q4nx_i8_sealed_prefill_instance returning the decode key → both table arms fail
    (each prefill instance is its decode name with a p_ prefix, no prefill instance key equals any decode instance key).
$ ctest -R '^(copyright_gate|ci_targets|tests_referenced|npu_decl_check|pre_pr_checks_agreement|npu_partition)$'
6/6 tests passed

Device proof (one npu-hold ticket, 36 s, production driver E81A7B40, temporal_only at its default)

A = today's route: kernels-qwen17-b8, per-role 8-column ELFs, 8 contexts.
B = partition route: NPU_PARTITION=4 + NPU_I8_SEALED_ELF=SEALED-q17-dec-c4.elf
+ NPU_I8_SEALED_PREFILL_ELF=SEALED-q17-pre-c4.elf, same container.

== arm A --kernels …/kernels-qwen17-b8
  text 0 sha=9a189629e5877d15 tokens=8 tok_s=3.90 ' Paris. The capital of the United Kingdom'
  text 1 sha=1a7c56b07f182278 tokens=8 tok_s=3.94 ' 100°C at standard pressure'
  text 2 sha=a3f15adcb5ea248f tokens=8 tok_s=3.89 ' if n <= 0:\n         return'
  dumps: 24
== arm B (NPU_I8_SEALED_ELF=… NPU_I8_SEALED_PREFILL_ELF=… NPU_PARTITION=4) --kernels …/kq17-shared
  text 0 sha=9a189629e5877d15 tokens=8 tok_s=4.46 ' Paris. The capital of the United Kingdom'
  text 1 sha=1a7c56b07f182278 tokens=8 tok_s=4.51 ' 100°C at standard pressure'
  text 2 sha=a3f15adcb5ea248f tokens=8 tok_s=4.47 ' if n <= 0:\n         return'
  dumps: 24
  partition mode, 4 columns: …/SEALED-q17-pre-c4.elf opens the model's one context
  partition mode: …/SEALED-q17-dec-c4.elf joins the model's context
== judge
  text A vs B: IDENTICAL
  logits: 24 vs 24 dumps, BIT-IDENTICAL
  C refusal: REFUSED BY NAME
  RESULT: PASS

B's own log, the part that matters here: the prefill ELF opens the model's context and the decode ELF joins
it
— one 4-column context for both roles, where A has two contexts per role. Every generated position of all
three prompts has a bit-identical f32 logits dump in both arms (24 files compared with cmp), so the
shared route is the same computation, not merely the same text.

C = NPU_PARTITION=4 with the 8-column set: the load is refused before anything runs —

NPU_PARTITION=4: …/full_i8_QKV_K2048_N4096_b8.elf asks for 8 columns; a model that shares the NPU opens every context at one width

Kernel log: 12 amdxdna/c6:00.1 lines before the ticket and 12 after it — no fault line, no timeout, no
reset. Decode rate is not a target here, but B was not slower: 4.46 tok/s against A's 3.90 for the same
prompts and the same binary.

What this does not do

Items 2 and 3 of #2689 stay open: a refused load should name the process holding the array (the
--load-queue-ms queue and its message exist; the holder name and half-array tokens in npu-hold are
infrastructure), and a multi-user decode step should fill N of the 16 M=16 rows instead of 1. The device side
of the second is already measured: an M=16 decode step is flat in N from 1 to 16 rows (1B ≈ 146 ms, 1.7B ≈
214 ms, exact at every N). Nothing here changes a default: both variables are opt-in.

🤖 Generated with Claude Code

bong-water-water-bong and others added 3 commits November 16, 2026 11:31
… (engine#2689, part 1 of item 1)

elf_partition.h reads .note.xrt.configuration (the column count a full ELF asks the driver
for) from the bytes, returning 0 for anything that is not one. q4nx_i8_sealed_prefill_instance
names each sealed prefill instance 'main:p_<decode name>', since one hardware context refuses a
second ELF with an instance key it already holds (measured 11-16: 'code 501: main:d'; with p_
names, decode main:o / main:gu and prefill main:p_o / main:p_gu ran exact in one context).

Test npu_partition (host only, in CI's build): 12/12. The reader also gives 4/8/8/4 on real
c4/c8/per-role/p_-prefill ELFs (checked locally against an independent parser; the ELFs are not
in the tree).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…led prefill joins it (engine#2689, item 1)

NPU_PARTITION=<cols> (unset = unchanged): every full ELF the model opens must declare <cols>
columns (elf_partition.h), or its load is refused by name; the first ELF creates the model's one
hw_context and every later one is add_config'ed into it. A duplicate instance key fails that
ELF's load with the runtime's reason.

NPU_I8_SEALED_PREFILL_ELF names one sealed M=128 ELF whose instances are main:p_<role>; a b8
container's prefill roles open it instead of their per-role ELFs. In partition mode a role it
does not cover is refused (its per-role ELF would be a second main:seq in the context).

WIP: the device gate (A per-role vs B shared byte-identical, C refusal) is pending; config keys
and docs follow before the PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

ready for review at fb408da

Item 1 of #2689. The gate is a single npu-hold ticket (36 s) on the production driver: the shared 4-column route reproduces the 8-column per-role route bit for bit at the logits (24 of 24 f32 dumps identical, 3 prompts x 8 positions), and the width mismatch is refused by name before anything runs. Host side: npu_partition 12 arms, two mutants (a stub reader, and a prefill table reusing the decode keys) each fail the arms they should. Everything is opt-in: with neither variable set the engine opens contexts exactly as it does today.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

*READY — and the driver behaviour it records is the part worth keeping: "the driver gives a process's second same-width context the other free half, and it refuses a 4-column context next to an 8-column one in the same process." That is a hardware constraint, not a design choice, and it explains why "one context per ELF" was never going to support two models on the array.

The refusals are the design, and each names its file and width — that is the pattern this repo has settled on (Q4NX uint4, staged() off-grid names, the _m16 twin) and it is applied consistently here:

  • an ELF in a <cols> partition whose .note.xrt.configuration declares a different width ⇒ refused naming the file and its width, rather than loading and misplacing columns;
  • a role the sealed ELF does not cover ⇒ refused by name, "because its per-role ELF would be a second main:seq" — that sentence is the whole reason, and it is exactly the kind of thing that becomes a mystery if it is not written down;
  • code 501: main:d is quoted as the measured symptom of two instances with one key, so the next person recognises it instead of re-deriving it.

Three things I would pin:

  1. NPU_PARTITION unset must be byte-identical to today. The body says "Unset (the default), every ELF still opens its own context exactly as before" — good, and it is the property that makes this safe to merge before the second half of npu: share the NPU between models and users (one context per model, half-NPU placement, multi-user decode rows) #2689 lands. An arm that runs a normal pack with the variable unset and diffs the ids would pin it in the same way audio_parallel pins the GEMM.
  2. What does the second model's load do when the first already holds one half? The measurement says the driver hands the other free half to a second same-width context in the same process — for two models sharing the array that is the case that matters, and it is presumably npu: share the NPU between models and users (one context per model, half-NPU placement, multi-user decode rows) #2689 item 2. If this PR's own test only covers one model with four roles, say so, so nobody assumes the two-model path is exercised.
  3. p_ prefixing is a naming convention that has to survive. main:p_qkvfa etc. are what the runtime sees; a future ELF built without --partition 4 would present main:qkvfa and collide silently in the other direction. One line saying the prefix is asserted (or that the refused-by-name path catches its absence) closes it.

Credited: doing item 1 of three as its own PR with the tracking issue left open; the measured driver facts quoted rather than paraphrased; tests/npu_partition_test.cpp registered in CI's target list (a new test that is not built is the failure mode this lane keeps finding); and the sealed/build.sh … -c 4 --partition 4 line, which is what makes the feature reproducible by someone who was not in the room.

Not verified by me: the host ctest and the device loads. The refused-by-name paths, the unset-default equivalence and the two-model question are what I can check, and the first two are right.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at fb408da: READY. The predicate is a bounded pure function, and the policy on "unknown" — which is where an invariant like this usually leaks — is already right.

The parser reads every byte through a bounds check

elf_partition_cols(bytes, size) verifies ELF magic, ELFCLASS32, LSB, n >= 52, shentsize >= 40, shnum != 0, shstrndx < shnum, shoff + shnum*shentsize <= n, the string table's stroff + strsz <= n, the note's off + sz <= n, sz >= 16, descsz >= 4 and doff + 4 <= sz — then returns the 32-bit value after the "XRT" name, and 0 for anything it does not understand. Every read is bounded; nothing is trusted from the file. And it is a pure function over a byte range, so the 111-line test can feed it crafted ELFs rather than needing a device.

0 is refused, and the message says which kind of unknown it was

const uint32_t got = onebit::npu::elf_partition_cols_file(key);
if (got != uint32_t(want)) {
    init_error = "NPU_PARTITION=" + std::to_string(want) + ": " + key + " asks for " +
                 (got ? std::to_string(got) + " columns" : std::string("no partition note")) + …;
    return false;
}

This is the check I would have asked for and expected to be missing: 0 means "I found no width", and the tempting shortcut — if (got && got != want) — would let an ELF with no note open its context at whatever the driver chose, which is precisely the mixed-width state the change exists to prevent. Refusing it, and printing "no partition note" as distinct from "N columns", is both the safe policy and the diagnosable one.

Opt-in, and the guard on the opt-in

NPU_PARTITION=<cols> with (c >= 1 && c <= 8) ? c : 0 — 1..8 is the whole array on this part, an out-of-range value becomes "off" rather than a wild claim, and unset means unchanged, so no existing single-model run can regress. The measured basis for the whole thing is stated with its arm names ("measured 11-15: the driver gives a process's second same-width context the OTHER free half (arm w44), and refuses a 4-column next to an 8-column one (arms w48/w84)"), which is what makes the one-context-per-model shape a finding rather than a preference.

Two things worth a line in the notes, not blocks

  • What want is when the operator is wrong. If the first ELF says 4 and NPU_PARTITION=8, the refusal fires on the first ELF — good — but the message reads "asks for 4 columns", which a reader can mistake for a complaint about the ELF rather than about the requested width. Naming both ("NPU_PARTITION=8 but <key> asks for 4 columns") costs nothing and points at the operator's value.
  • The sharing outcome is the thing #2689 item 1 is really about. This lands the mechanism (add_config onto the first context); the row that closes the item is two models actually resident at 4+4 with temporal_only=0, and the body should say that is still owed so the issue does not read as finished on this PR.

@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 at fb408da: READY

An ELF-format reader with every refusal armed, and a table invariant that is checked in the direction that matters (no prefill key may equal a decode key).

What the change enforces, and why it is the driver's rule rather than a style

"With the driver's spatial placement (amdxdna temporal_only=0), two processes can run on separate column halves at the same time. That only works if each model holds exactly one hardware context at one width. The driver gives a process's second same-width context the other free half, and it refuses a 4-column context next to an 8-column one in the same process."

So the engine reads the partition width itself and refuses a mismatched ELF by name at load, instead of letting the driver fail halfway — which on this box is the difference between an error message and a wedged context.

The reader is a pure function over a byte range, and every boundary is armed

PASS a 4-column note reads 4          PASS an 8-column note reads 8
PASS wrong magic reads 0              PASS a 64-bit ELF reads 0 (the full ELFs are 32-bit)
PASS a note of another name reads 0   PASS a configuration section shorter than a note reads 0
PASS a truncated section table reads 0, not out of bounds
PASS a file shorter than an ELF header reads 0

reads 0, not out of bounds is the sentence that makes the rest reviewable: every malformed input is a refusal, not a crash and not a plausible width. 0 is the sentinel and it is used consistently for "not this note".

Mutant — drop the ELFCLASS32 check:

FAIL a 64-bit ELF reads 0 (the full ELFs are 32-bit)

It bites, and the arm's text says why the constraint exists (the full ELFs are 32-bit) rather than just asserting a magic number.

The table invariant

PASS every role with a decode instance has a prefill instance, and only those
PASS each prefill instance is its decode name with a p_ prefix
PASS no prefill instance key equals any decode instance key
PASS a role with no decode instance has none

no prefill instance key equals any decode instance key is the one that maps to the driver's own refusal ("one context refuses a duplicate"): if the prefill instance reused a decode key, the model would ask the driver for a second context with the same key and fail at run time instead of at load. 12 arms, ok.

Host-only, and stated

"Host-only: the ELF partition-note reader (elf_partition.h) on crafted ELFs, and the sealed prefill instance table" — so this PR's evidence is checkable on any box, and the device claim it rests on (the driver's placement and its two refusals) is quoted as a measurement from 11-15 rather than re-derived here. That is the correct split: the code change is host-testable, the hardware behaviour is cited.

What I would want next, and it is a note rather than a gap: the 8-column + 4-column mix is the case the driver refuses, and it is currently enforced by construction (one width per model) rather than by a test that builds such a pair and requires a named refusal. An arm that constructs the forbidden pair and asserts the refusal message would be the mirror of no prefill instance key equals any decode instance key.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at fb408da: READY. The parser arms are unusually good, and the one thing missing is the layer above them.

The measurements are the kind that justify a new mode

"the driver gives a process's second same-width context the other free half, and it refuses a 4-column context next to an 8-column one in the same process" — with arms w44 (sharing works), w48/w84 (mixed widths refused), and the duplicate-key refusal measured as code 501: main:d.

Those are driver behaviours, named with the arm they were observed in, not inferences from the docs. A change that replaces "one context per ELF" with "one context per model" needs exactly that: a statement of what the driver does today, because the new mode exists only to stop doing it.

Refuse-by-name, and the default preserves the old shape

Every full ELF must declare <cols> columns or the load is refused naming the file and its width, and unset means unchanged. That is the pairing I have asked for all day: a new mode that is opt-in, and a violation inside it that says which file and which width. The prefill-table invariant is stated too — "no key may equal a decode key, since one context refuses a duplicate" — which is the constraint that would otherwise surface as code 501 at run time.

The parser arms cover the failure directions that matter

a 4-column note reads 4 / an 8-column note reads 8
wrong magic reads 0 / a 64-bit ELF reads 0
a note of another name reads 0
a configuration section shorter than a note reads 0
a truncated section table reads 0, not out of bounds
a file shorter than an ELF header reads 0
every role with a decode instance has a prefill instance, and only those

Reading a file's note is parsing hostile input, and the arms treat it that way: magic, class, name, truncation, and two out-of-bounds cases. reads 0, not out of bounds is the line I look for in any new parser.

The ask: the policy is one layer above the arms

NPU_PARTITION → mode lives in npu_forward/engine-src/npu_engine_i8ctx_inc.h, which this test does not compile, so the two behaviours that decide everything for existing users are unarmed:

  1. unset ⇒ every ELF opens its own context, exactly as before. That is the promise that makes this PR safe to land, and nothing fails if a later refactor flips it.
  2. a value that is not a plausible width (NPU_PARTITION=0, =4x, =foo, or larger than the array) — refuse by name rather than fall through to a count. The same class as #2587's atof garbage → 0, which cost a lane an afternoon.

If that header cannot be unit-tested as it stands, the acceptable answer is a sentence in the body saying where those two are exercised (a device run at -c 4 --partition 4, which the body already names for building the ELFs) and what it showed. What I would not want is the mode's own default to be the one thing in the PR that only a device can check and nobody has.

@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 at fb408da: READY

Both claims hold on the real artifacts, not just on the crafted ones, and both mutants bite. I checked the reader against every full ELF I could find on this box and against the exact two files the device arm used. Two non-blocking notes at the end.

Built and run here

$ ninja npu_partition_test && ./npu_partition_test
PASS a 4-column note reads 4          PASS a truncated section table reads 0, not out of bounds
PASS an 8-column note reads 8         PASS a file shorter than an ELF header reads 0
PASS wrong magic reads 0              PASS every role with a decode instance has a prefill instance, and only those
PASS a 64-bit ELF reads 0             PASS each prefill instance is its decode name with a p_ prefix
PASS a note of another name reads 0   PASS no prefill instance key equals any decode instance key
PASS a configuration section shorter than a note reads 0   PASS a role with no decode instance has none
ok

Mutants, each restored and rebuilt afterwards:

  • reader stubbed to return 8 → 7 arms fail (a 4-column note reads 4 + the six rejection arms), exactly as the body says.
  • q4nx_i8_sealed_prefill_instance(D) returning the decode key main:d → 2 arms fail (each prefill instance is its decode name with a p_ prefix, no prefill instance key equals any decode instance key).

Gates: ctest -R '^(copyright_gate|ci_targets|tests_referenced|npu_decl_check|npu_partition)$' → 5/5 passed (pre_pr_checks_agreement cannot pass out of an out-of-source build dir — pre-pr-checks: not inside a git work tree — so I ran the script itself in the source tree: 13 checks green, 2 skipped only for the missing gpu-kernels tree here).

The reader against real ELFs, which is where a 32-bit-only parser usually dies

I compiled elf_partition.h standalone (/tmp/rd.cpp, no NPU SDK needed) and ran it over every *.elf under ~ that I could reach (6,000 files): 1,150 read 8, 23 read 4, 4,791 read 0 — and every 0 is an elfs_main_core_*/probeElfs_* per-core ELF with no .note.xrt.configuration at all, i.e. not something init_elf ever hands it (is_full_elf() gates the call). No full ELF read 0 and no read a garbage width. All 266 ELFs under ~/models/npu read 8.

The two files the device arm B actually used, i.e. the artifact this PR's claim rests on:

$ /tmp/rd ~/.cache/scratch-cl-npurt/npuconc/kq17-shared/SEALED-q17-{pre,dec}-c4.elf
4   …/SEALED-q17-pre-c4.elf
4   …/SEALED-q17-dec-c4.elf
$ /tmp/rd /home/bcloud/ogaload/families/kernels-qwen17-b8/full_i8_{QKV_K2048_N4096,D_K6144_N2048}_b8.elf
8   …/full_i8_QKV_K2048_N4096_b8.elf
8   …/full_i8_D_K6144_N2048_b8.elf

So arm C's refusal (8-column set with NPU_PARTITION=4) is reading a real 8, and arm B's acceptance is reading a real 4 — not a crafted note.

The p_ prefix, checked in the ELF bytes rather than in the table

The claim that makes one shared context legal is that the prefill ELF's instances never collide with the decode ELF's. On the two shipped artifacts:

$ strings -a SEALED-q17-pre-c4.elf | grep -E 'p_qkvfa|qkvfa' | sort -u
p_qkvfa
$ strings -a SEALED-q17-dec-c4.elf | grep -E 'p_qkvfa|qkvfa' | sort -u
qkvfa

One carries p_qkvfa, the other qkvfa; no main:p_* name appears in the decode ELF. That is the fact the "no duplicate instance key" arm asserts, confirmed outside the source tree.

Notes, not change requests

  1. static std::shared_ptr<xrt::hw_context> shared; (npu_engine_i8ctx_inc.h) is process-scoped, not model-scoped — the wording here and in docs/npu.md is "one context per model". While a process serves one model the two are the same thing (verified: unified.cpp opens either the private route or the layer lane, never both; forward_serve builds one forward), so this is latent rather than a bug today. It becomes a bug the day a second ELF set exists in one process: that set's ELFs would add_config into the first model's context with the same main:* keys and get the code 501 the docs already name, where today each set opens its own context. If item 2 of #2689 (multi-user decode) puts a second consumer on the process, this is the line that decides who owns the context. Worth either keying it to the model's own state (the pool beside it is keyed by path and can hold the first host's context) or saying "one model per process" in the one comment that currently says "per model".
  2. NPU_PARTITION outside 1..8 turns the mode off in silence: npu_partition_cols() is (c >= 1 && c <= 8) ? c : 0, so NPU_PARTITION=0, =9 or a typo like =a4 leaves no trace and the run is the old multi-context route while the operator believes sharing is on. One fprintf when the variable is set but the value is not 1-8 would make the misconfiguration say its own name.

Everything else — the width refusal naming the file and its width, the by-name refusal for an uncovered prefill role, the unchanged default path (shared_ptr with a single owner where unique_ptr was), the Apache notice on the new file, and the docs paragraph in this PR — checks out. Green gates plus my own verification at fb408dad.

@bong-water-water-bong
bong-water-water-bong merged commit 1314586 into main Nov 16, 2026
10 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/2689-npu-partition branch November 16, 2026 16:29
@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2689 - Partially compliant

Compliant requirements:

  • One context per shared-NPU model
  • Build 4-column sealed models with --partition 4
  • Open prefill into the decode context with add_config
  • A plan/config key (e.g. npu_partition: 4) that refuses any context of another width at load, with a named error

Non-compliant requirements:

  • Placement in 1bit serve, behind a flag
  • Same-model multi-user decode

Requires further human verification:

  • Enable: after 1 and 2 are merged and two real models serve exactly for 1 h through 1bit serve, add options amdxdna temporal_only=0 in modprobe.d and turn the serve flag on by default
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Context Sharing Logic

The logic for sharing hardware contexts in partition mode relies on a static shared pointer shared in I8Ctx::init_elf. This approach may lead to race conditions in multi-threaded environments where multiple threads attempt to initialize contexts for the same model simultaneously, potentially causing context initialization to fail or behave unpredictably.

    static std::shared_ptr<xrt::hw_context> shared;
    if (!shared) {
        shared = std::make_shared<xrt::hw_context>(d, *h->elf);
        fprintf(stderr, "  I8Ctx::init_elf: partition mode, %d columns: %s opens the model's one context\n",
                want, key.c_str());
    } else {
        // Throws when an instance key is already in the context (two `main:seq` per-role ELFs, or a
        // prefill ELF named like its decode ELF): caught below and reported as this ELF's failure.
        shared->add_config(*h->elf);
        fprintf(stderr, "  I8Ctx::init_elf: partition mode: %s joins the model's context\n", key.c_str());
    }
    h->hc = shared;
} else {
Prefill ELF Handling

The handling of NPU_I8_SEALED_PREFILL_ELF in open_prefill introduces a conditional path that may not be fully tested or validated for all combinations of roles and partition widths, potentially leading to runtime errors or incorrect behavior when the prefill ELF is not correctly aligned with the decode context.

if (const char* sp = std::getenv("NPU_I8_SEALED_PREFILL_ELF"); sp && *sp && b8 && !w4_rows_ && !host_gemm) {
    if (const char* inst = q4nx_i8_sealed_prefill_instance(g->role)) {
        elf = dir + "/" + sp;
        kname = inst;
    } else if (npu_partition_cols()) {
        err = std::string("NPU_PARTITION: the sealed prefill ELF ") + sp + " has no instance for role " +
              q4nx_design_log_tag(g->role) + ", and its per-role ELF cannot join the model's one context";
        return false;
    }
}

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