Skip to content

npu-pack: a stale TMPDIR is not a reason to refuse a 1.9 pack - #1604

Merged
bong-water-water-bong merged 3 commits into
mainfrom
1bit/npu-pack-tmpdir-fallback
Nov 9, 2026
Merged

bong-water-water-bong merged 3 commits into
mainfrom
1bit/npu-pack-tmpdir-fallback

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

temp_directory_path() throws when TMPDIR names a directory that no longer exists — the ordinary state of a long-lived shell after a reboot has cleared /tmp, and exactly the state this box was in when I hit it. Every npU-pack command on a 1.9 pack died before reading anything:

1bit npu-pack: filesystem error: temp_directory_path: No such file or directory [/nonexistent-dir]

That reads as "the pack is broken" when the pack is fine and the environment variable is stale. It also meant npu-pack info, documented as writing nothing, could not even describe the pack.

The change

The canonical copy's directory is now chosen from a list instead of assumed — the temporary directory, then /tmp, then the current directory — taking the first that is a directory and is writable in fact (the check opens the file, because the copy is written immediately after).

Two notes, each only when it applies:

note: the temporary directory is unusable (<the error>), so the 1.9 pack's canonical copy goes elsewhere
note: the 1.9 pack's canonical copy is /path/… (remove it when done)

The second fires whenever the chosen directory is not the temporary one: the copy is a few hundred MB of scratch and should never appear somewhere unexplained. When nothing is usable, the refusal names that rather than surfacing a bare filesystem error mid-call.

Verified

TMPDIR before after
/nonexistent-dir filesystem error: temp_directory_path …, nothing else both notes, then the JSON, rc 0
normal JSON JSON, unchanged

Not fixed here, and worth a follow-up

npu-pack info still writes that copy for a 1.9 pack, because reading its geometry correctly requires the 1.8 form. The help text says info "writes nothing" — true before 1.9 support, not true now. Left alone deliberately: fixing it means either teaching the geometry reader the 1.9 block directly (which the measured table exists for, but the reader is built around the 1.8 offsets) or giving info a read-only path through the normaliser. Separate change, separate review.

bong added 3 commits November 8, 2026 15:36
… and stop mis-gating rope on column count

Three genre-A packs' worth of gap, all found on amd/Qwen3-1.7B-awq-quant-onnx-hybrid
and each one enough on its own to produce fluent garbage:

1. SPLIT q/k/v. 11 of the 134 genre-A packs (Qwen3 x7, gemma-2 x3, Qwen2.5-14B)
   ship q/k/v as three separate MatMulNBits nodes joined by Concat instead of one
   fused qkv_proj node, and the importer refused all 84 layer projections by name.
   The plan now falls back to the split spelling when the fused node is absent, and
   the import decodes each projection whole -- the container stores q/k/v
   separately either way, so nothing downstream can tell the two layouts apart.
   The attention biases follow the same split (one per projection).

2. PER-HEAD QK GAINS. These packs also carry q_norm/k_norm as graph initializers
   (`attn.q_norm.layernorm.weight`, F16 [head_dim]). The forward turns QK norm on
   from model_type alone, so dropping the gains leaves q and k normalised by an
   uninitialised vector. My first attempt at this sat inside the .fconst payload
   section, which a genre-A pack never enters -- so it compiled, ran, and did
   nothing. It now lives with the other genre-A norms. On this pack: 395 tensors
   (196 projections + 56 QK gains + 84 split biases + embedding + final norm +
   head), against 339 before the gains landed.

3. ROPE WAS GATED ON A MEAN OF PER-COLUMN CORRELATIONS. For head_dim 128 the last
   columns of cos_cache barely vary over the positions a cache holds, so their
   per-column correlation is noise: Qwen3-1.7B's correct theta (1e6) scored
   0.9826 by that mean and lost to the declared 1e4, which scores 0.17. One flat
   Pearson r over the whole cache matrix gives 1.000000 at the right theta, so
   the check now adopts 1e6 and says so. The warning that used to fire before the
   check (and contradict a passing note two lines later) now fires only when no
   plain theta explains the cache.

Evidence, amd/Qwen3-1.7B-awq-quant-onnx-hybrid (hidden 2048, 16/8 heads, head_dim
128, 28 layers, IM 6144): plan incomplete 84 -> 0; import 395 tensors / 210,016
tiles; self-check corr 0.996766 against the pack's fp16 embedding (controls 0.0016
and 0.8703, both failing); rope adopted 1e6 at corr 1.0000. Greedy text on the host
GEMM:

    'The capital of France is' -> ' Paris. The capital of the United States is Washington, D'
    '2 + 2 ='                  -> ' 4, 2 + 2 + 2 ='
    'Why is the sky blue?'     -> ' What is the scientific explanation for this phenomenon? What is the'

The first answer is the same one the .fconst Qwen3-1.7B packs give through the same
forward, which is the cross-check that the two import paths agree for one model.
…ndex

Review finding, and it was exactly right: "self_attn." is TEN characters, so

    substr(11, 1)   ->  '_'      the manifest recorded …attn._norm.layernorm.weight
    substr(10, 1)   ->  'q'      what the comment intended

so the source string the plan recorded for a split pack's QK-norm gains named a tensor that exists
in no pack. Nothing failed at the time, because the import reads those norms by its own correct
name and the container round-tripped -- the manifest simply said something untrue, which is the
shape that gets trusted later.

Fixed by removing the index arithmetic rather than correcting the offset: the leaf now comes from a
substring test on the name (`find("q_norm")`), so there is no length to be off by one.

Verified on the pack this branch is for -- amd/Qwen3-1.7B-awq-quant-onnx-hybrid, whose graph carries
`attn.q_proj`/`k_proj`/`v_proj` and no `attn.qkv_proj` -- where `npu-pack info` now reports
`graph:model.layers.N.attn.q_norm.layernorm.weight` (and k_norm likewise) with an empty refusal, and
the import still lands 395 tensors / 210,016 tiles. The first pack I reached for,
Qwen3-1.7B_rai_1.8.0_npu_4K, turned out to be the wrong evidence and this message said so before I
checked: it has no MatMulNBits initializers at all (its weights are in the .fconst), so the split
branch is unreachable there. Recording that because the review's point was precisely that the branch
compiles and runs in every test without ever executing.
`temp_directory_path()` throws when TMPDIR names a directory that no longer exists -- the ordinary state of a
long-lived shell after a reboot has cleared /tmp, and exactly what this box was in when I hit this: every
`npu-pack` command on a 1.9 pack died with

    1bit npu-pack: filesystem error: temp_directory_path: No such file or directory [/nonexistent-dir]

before reading anything, which reads as "the pack is broken" when the pack is fine and the environment variable
is stale. It also means `npu-pack info`, documented as writing nothing, could not even describe the pack.

Now the canonical copy's directory is chosen from a list rather than assumed: the temporary directory, then
`/tmp`, then the current directory, taking the first that is a directory AND writable in fact (the copy is
written immediately after, so the check opens it). Two notes, each only when it applies:

    note: the temporary directory is unusable (<the error>), so the 1.9 pack's canonical copy goes elsewhere
    note: the 1.9 pack's canonical copy is /path/… (remove it when done)

The second fires whenever the chosen directory is not the temporary one -- the copy is a few hundred MB of
scratch and it should never appear somewhere unexplained. When no directory is usable the refusal names that,
rather than surfacing a bare filesystem error mid-call.

Verified: `TMPDIR=/nonexistent-dir npu-pack info <1.9 pack>` now prints both notes and the JSON (rc 0), where
it previously printed the filesystem error and nothing else; with a normal TMPDIR the output is unchanged.

One thing this does NOT fix, and it is worth a follow-up: `npu-pack info` still *writes* that copy for a 1.9
pack, because reading the pack's geometry correctly requires the 1.8 form. The help text says info "writes
nothing", which was true before 1.9 support and is not now. Not touched here.
@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

TMPDIR fallback logic may not handle all edge cases

The fallback logic for choosing a writable directory when TMPDIR is invalid attempts to check if directories are writable by opening a file for writing. However, this check may not be sufficient in all cases, such as when the directory exists but has restrictive permissions or is mounted read-only. This could lead to a false positive where a directory is considered writable but fails during actual file creation, potentially causing the function to fall back to the current directory even when a valid writable directory exists elsewhere.

for (const auto& d : dirs) {
    std::error_code ec;
    if (!fs::is_directory(d, ec) || ec) continue;
    const fs::path cand = d / name;
    // Writable in fact, not just in theory: the copy is written immediately after this.
    std::ofstream probe(cand, std::ios::binary | std::ios::app);
    if (!probe) continue;
    probe.close();
    work = cand.string();
    // Say where it went whenever that is not the ordinary place: the copy is a few hundred MB and it is scratch.
    std::error_code ec2;
    const fs::path tmpdir = [&] { try { return fs::temp_directory_path(); } catch (...) { return fs::path(); } }();
    if (tmpdir.empty() || fs::weakly_canonical(cand.parent_path(), ec2) != fs::weakly_canonical(tmpdir, ec2))
        std::fprintf(stderr, "1bit npu-pack: note: the 1.9 pack's canonical copy is %s (remove it when done)\n",
                     work.c_str());
    break;
}
if (work.empty())
    throw std::runtime_error(pack_dir + ": this is a Ryzen AI 1.9 pack, whose Token .fconst has to be rewritten into "
                                        "its 1.8 form before it can be read, and no writable directory is available "
                                        "for that copy (tried the temporary directory, /tmp and the current "
                                        "directory)");
Potential performance regression in RoPE theta verification

The updated RoPE theta verification logic now computes a single Pearson correlation coefficient over the entire cache matrix instead of averaging per-column correlations. While this change aims to improve accuracy, it introduces a more computationally intensive loop structure that iterates over all positions and indices, potentially leading to a performance regression, especially for large cache matrices. This change should be validated for performance impact on typical hardware.

// ONE Pearson r over the whole cache matrix, not a mean of per-column r's. For a large
// head_dim the last columns barely vary -- cos(p * inv) is nearly flat over the positions the
// cache holds -- so their per-column r is noise, and averaging it in drags a CORRECT theta
// below the 0.99 gate. Measured on Qwen3-1.7B-awq-quant-onnx-hybrid (head_dim 128): the mean
// of the 57 usable columns gives 0.9826 at the right theta 1e6, while the flat r gives
// 1.000000 and the declared 1e4 sits at 0.17 either way.
double sx = 0, sy = 0, sxx = 0, syy = 0, sxy = 0;
int64_t used = 0;
for (int64_t i = 0; i < half; ++i) {
    const double inv = 1.0 / std::pow(th, 2.0 * double(i) / double(HD2));
    for (int64_t pp = 0; pp < pmax; ++pp) {
        const double y = cache[size_t(pp) * size_t(half) + size_t(i)];
        const double x = std::cos(double(pp) * inv);
        sx += x; sy += y; sxx += x * x; syy += y * y; sxy += x * y;
        ++used;
    }
}
const double np = double(used);
const double cx = sxx - sx * sx / np, cy = syy - sy * sy / np;
if (used > 0 && cx > 1e-12 && cy > 1e-12) {
    const double corr = (sxy - sx * sy / np) / std::sqrt(cx * cy);
    if (corr == corr && corr > best_corr) { best_corr = corr; best_theta = th; }
}

@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 142854cc5976 (full head 142854cc5976 — the sha the table shows; the .fconst copy and the qkv/bias naming below are both from this diff).

The mechanism is verified, not taken from the description — I compiled the throw case rather than trusting cppreference:

$ TMPDIR=/nonexistent-x1 ./tmpt
threw: filesystem error: temp_directory_path: No such file or directory [/nonexistent-x1]
$ TMPDIR=/tmp ./tmpt
ok /tmp

so a post-reboot shell with a stale TMPDIR really does make temp_directory_path() throw, and the old code really did die before reading anything. The replacement is the right shape: a list of candidates, the first that is a directory and writable in fact (it opens the file, which is correct because the copy is written immediately), /tmp unconditionally in the list but skipped by the is_directory test if absent, and a refusal that names all three when none works instead of surfacing a bare filesystem error mid-call. The "note only when it is not the temporary directory" comparison via weakly_canonical is the right condition — the note exists to explain an unexpected file, so it must stay quiet in the expected case.

Two things to add, neither blocking the fix:

  1. The diff has a second half the body does not mention, and a reviewer reading the description would not know to look at it: ga_proj now names the fused model.layers.N.attn.qkv_proj when it is in the graph and the split spelling when it is not, plus the fused_bias / own_bias choice for MatMulNBits.bias. I read it — it is a refusal-message improvement in the same family as the rest of this file, it is backed by a real measurement ("11 genre-A packs (Qwen3 x7, gemma-2 x3, Qwen2.5-14B) ship q/k/v as three separate MatMulNBits joined by Concat"), and it does not change what is imported. But it is 149 lines whose body describes the TMPDIR half only; one paragraph saying "and a q/k/v refusal now names the node that actually carries them" makes the diff reviewable by someone who did not write it.

  2. The fallback's last resort is the current directory, and the copy is never removed — fs::remove appears only for a stale link (:2912), so the 291 MB .fconst stays for the caller to delete. That is pre-existing behaviour and the note says "remove it when done", but after a reboot the copy now lands in $PWD, which for a developer is likely a repo worktree — and "a large untracked file in the working tree" plus git add -A is precisely the failure mode of #1564. A $HOME/.cache/1bit candidate before current_path(), or one clause in the note ("and do not add it to the repository"), closes that without changing anything else.

And the follow-up you scoped out is the right one: npu-pack info writes a few hundred MB despite its help text saying it writes nothing, and "teach the geometry reader the 1.9 block" versus "give info a read-only path through the normaliser" is a real design choice, not a cleanup. Worth an issue so it does not live only in a PR body — it is the kind of contradiction a user hits and reports as "info wrote 291 MB to my /tmp".

@bong-water-water-bong
bong-water-water-bong merged commit 7974a64 into main Nov 9, 2026
9 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/npu-pack-tmpdir-fallback branch November 9, 2026 03:19
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.

2 participants