Skip to content

repeating fixes - #389

Open
danielhanchen wants to merge 3 commits into
base/upstream-7e960f40ffrom
repeating-layers
Open

danielhanchen wants to merge 3 commits into
base/upstream-7e960f40ffrom
repeating-layers

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

Adds repeating (looped) layers and the looped Inkling-2-Small architecture: a contiguous block of layers runs several times per token.

  • New GGUF keys %s.loop.core_start / %s.loop.core_end; the pass count reuses %s.num_loops.
  • One block per layer visit: each visit keeps its own KV cache, while the weights stay shared per physical layer.
  • The converter registers the looped architecture as additions only.

Tests:

  • test-llama-archs passes, including a new looped config.
  • Non-looped models give byte-identical logits.
  • In the pin set it merges cleanly on b12559 to b12591.

A looped model runs the layers [loop.core_start, loop.core_end) num_loops
times. The GGUF has one block per layer visit, so every visit keeps its own
KV cache and recurrent state, while the weights stay per physical layer.
The loader validates the layout, the generic scale pass runs over the
physical layers, every visit then shares its layer's weights, and the graph
node budget scales with the pass count.

Inkling 2 uses it for its looped variant (Inkling2LoopForConditionalGeneration):
later passes restart from the prelude state and mix in the previous pass
through low-rank message controllers.
Register Inkling2LoopForConditionalGeneration with its own calls instead of
editing the shared register lines, so the change stays additive next to
other edits around the Inkling 2 converters.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T22:34:04.999253Z 3b34f4f New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6196d9802e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/models/inkling2.cpp
Comment on lines +113 to +116
for (int i = 0; i < n_layer - (int) hparams.loop_n_extra(); ++i) {
auto & layer = layers[i];

const int64_t n_head = hparams.n_head(i);
const int64_t n_head_kv = hparams.n_head_kv(i);
const int64_t n_embd_head = hparams.n_embd_head_k(i);
const int64_t n_ff_exp = hparams.n_ff_exp(i);
const int64_t n_extent = hparams.is_swa(i) ? hparams.n_swa : hparams.n_relative_extent;
const int iv = hparams.loop_visit(i);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Map weight placement to physical layers before loading tensors

For looped models, device assignment still uses the expanded visit count, while this loop creates tensors using physical block indices. With the new test layout (16 visits, 8 physical layers) and n_gpu_layers=8, llama_model_base::load_tensors() sets i_gpu_start=9, but all weights have indices 0–7, so no transformer weights reach the GPU despite requesting partial offload. Full offload across multiple GPUs is also skewed because the physical weights occupy only the beginning of the visit-based device map, potentially exhausting one GPU while leaving another unused. create_tensor() selects its buffer from dev_layer[tn.bid], so copying the layer pointers afterward does not repair placement. Assign physical weights to devices explicitly and keep the per-visit device mapping consistent with their shared weights.

Useful? React with 👍 / 👎.

Comment thread conversion/inkling2.py
Comment on lines +346 to +347
self.gguf_writer.add_tensor(new_name, cast("np.ndarray", packed), raw_dtype=gguf.GGMLQuantizationType.NVFP4)
yield new_name.removesuffix(".weight") + ".scale", torch.from_numpy(scale)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Wire native NVFP4 expert scales through loading and inference

With INKLING2_NVFP4_NATIVE=1, an NVFP4 checkpoint now produces blk.*.ffn_gate_up_exps.scale and blk.*.ffn_down_exps.scale, as confirmed with a synthetic checkpoint. However, neither the generic scale-loading pass in src/llama-model.cpp nor Inkling2's tensor loader requests the fused gate/up scale, so done_getting_tensors() rejects the resulting GGUF with a wrong-tensor-count error. Loading that tensor alone is insufficient: Inkling2's build_moe_ffn() call also leaves all expert-scale arguments null, omitting the required amax / denominator factors. Load the fused gate/up scale and pass both expert scales into the MoE graph before exposing this native conversion path.

Useful? React with 👍 / 👎.

Comment thread conversion/inkling2.py
Comment on lines +237 to +239
missing = sorted(set(self._expected_tensors()) - set(self.model_tensors)) if self.loop is not None else []
if missing:
raise ValueError(f"Inkling2: {len(missing)} missing tensors, first: {missing[:4]}")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Resolve supported tensor aliases before checking required weights

For looped checkpoints using the Transformers tensor names already supported by Inkling2, this compares filtered source names against a native-checkpoint-only list and rejects valid aliases before tensor mapping runs. For example, model.language_model.embed_tokens.weight becomes model.embed_tokens.weight; the existing tensor map resolves this to the same token_embd.weight as model.embed.weight, but this check still raises missing tensors for model.embed.weight. I reproduced that rejection by changing only the embedding alias in an otherwise complete expected-name set. The existing TestInkling2TextNames test also explicitly covers both naming schemes. Validate mapped tensor identities or normalize the supported aliases before calculating the missing set.

Useful? React with 👍 / 👎.

… give later visits their own host weight views

Device placement: the splits and n_gpu_layers counted every layer visit
(n_layer_all), while the weights exist once per physical layer. On
Inkling-2-Mini (48 visits, 24 physical layers) `-ts 1,1` put all repeating
weights on the first GPU (15862.62 of 16332 MiB), and a third GPU got only
visits without weights. The splits now count the layers that hold weights,
every visit runs on the device of its weights, and llama_model_n_layer_weights()
gives common/fit the same unit.

Host weight views: the backend scheduler keys the device copy of a host weight
(op offload) by tensor. A weight shared by every visit kept its copy from the
first pass to the last, so with experts on the CPU the GPU held the copies of
all the looped layers at once (+6561 MiB on Inkling-2-Mini, exactly the 12 core
layers' experts). The later visits of a looped layer now use views of its host
weights, each with its own short-lived copy. Views keep the name, so LoRA
adapters still apply, and the saver writes each weight once.

Models without looped layers are unchanged: n_layer_weights() == n_layer_all
and no views are made.
oobabooga added a commit to unslothai/unsloth that referenced this pull request Nov 20, 2026
…llama.cpp prebuild (#18692)

> **Note:** this targets the next llama.cpp prebuild, not the one
shipped today (`b12572-mix-8eebad4`). It assumes the pin set on
`unslothai/llama.cpp` master, which adds unslothai/llama.cpp#385
(chunked dense bias) and unslothai/llama.cpp#386 (banded flash
attention), plus unslothai/llama.cpp#389 at `3b34f4f`. On today's build
the dense rate from #18689 is the right one.

## Problem

#18689 sized the Inkling 2 compute buffer for the dense
relative-position bias (`512 * (8 * n_head + 4 + 2)` bytes per context
token at ub=512). The next llama.cpp prebuild replaces that path in the
common case:

- #386 runs the relative bias through banded flash attention when flash
attention is on, the cache is f16/bf16/f32, the head size is 64 or 128,
there is one stream and the ubatch is above 32 tokens. Studio's default
launch (flash attention, f16 cache, `--kv-unified`, ub=512) takes this
path.
- #385 chunks the dense bias over query rows once it passes 2^29
elements, for the configurations that still take the dense path.

With the dense rate, Studio would overestimate the banded buffer by
about 11x (77531 vs 7236 MiB at 800K) and pick a much shorter context
than fits.

## Fix

In `_compute_buffer_ctx_bytes`, the `inkling2` branch now:

- takes the banded path when it applies: 18 bytes per cell and
micro-batch token, plus a flat f32 `[ub, ub, n_head]` block;
- keeps the dense rate for the rest (quantized cache, flash attention
off, ubatch of 32 or less). With #385's chunking that rate is exact up
to the first split (32K at ub=512 for 24 heads) and an upper bound after
it.

## Verification

CUDA0 compute buffer of llama-server from the shipped mix source plus
#385, #386 and #389 at `3b34f4f`, on an RTX 6000 Ada, Inkling-2-Mini
UD-Q4_K_XL, `--kv-unified`, compared with Studio's estimate:

| n_ctx | ubatch | slots | cache | flash attn | measured (MiB) |
estimate (MiB) |
|---|---|---|---|---|---|---|
| 65536 | 512 | 4 | f16 | on | 781 | 786 |
| 262144 | 512 | 4 | f16 | on | 2509 | 2514 |
| 800000 | 512 | 4 | f16 | on | 7236 | 7241 |
| 65536 | 256 | 4 | f16 | on | 387 | 389 |
| 65536 | 2048 | 4 | f16 | on | 3350 | 3428 |
| 262144 | 2048 | 4 | f16 | on | 10236 | 10340 |
| 65536 | 512 | 1 | f16 | on | 672 | 781 |
| 65536 | 512 | 4 | q8_0 | on | 4574 | 6522 |
| 131072 | 512 | 4 | q8_0 | on | 6175 | 12858 |
| 262144 | 512 | 4 | q8_0 | on | 12191 | 25530 |
| 32768 | 512 | 4 | f16 | off | 4936 | 4922 |
| 65536 | 512 | 4 | f16 | off | 5159 | 9658 |
| 131072 | 512 | 4 | f16 | off | 5543 | 19130 |

On the banded path the estimate is 0.1% to 2.3% above the measurement
with 4 slots, and 16% above with 1. The dense fallback stays at or above
the measurement, except at 32K without flash attention, where it is 14
MiB (0.3%) below. Above that it is 1.4x to 3.5x high. It only applies to
non-default configurations.

Tests: `test_compute_buffer.py` checks the banded table (at or up to 20%
above the measurement), the dense fallback staying above the chunked
buffer, the two rates, which configurations take the dense path, and the
layer-split delta on both paths. `test_compute_buffer.py` and
`test_kv_cache_estimation.py` pass locally.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants