File size: 36,081 Bytes
df64eb3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 | diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp
index 5fef4c4..7d3d5bd 100644
--- a/src/llama-graph.cpp
+++ b/src/llama-graph.cpp
@@ -1935,6 +1935,13 @@ ggml_tensor * llm_graph_context::build_lora_mm_id(
ggml_mul_mat_id(ctx0, w, cur_mm, ids) :
ggml_mul_mat_id(ctx0, cached ? moe_cache->get_experts(w) : w, cur_mm, slots);
+ // TIP: a looped block that routes again selects other experts than its first pass, but a device copy of host
+ // experts only holds the experts of the first selection (see llama_context::sched_copy_experts).
+ // the later selections therefore read the host experts in place, on the CPU.
+ if (moe_cache_pass > 0 && slots == nullptr && w->buffer != nullptr && ggml_backend_buffer_is_host(w->buffer)) {
+ ggml_backend_sched_set_tensor_backend(sched, res, backend_cpu);
+ }
+
if (w->type == GGML_TYPE_NVFP4) {
ggml_prec_set_acc(res, GGML_PREC_BF16);
}
@@ -2546,7 +2553,7 @@ ggml_tensor * llm_graph_context::build_moe_ffn(
// the experts of host-resident layers may be read from the MoE cache (see llama_moe_cache::build_lookup)
const llama_moe_cache_lookup cache = moe_cache == nullptr ? llama_moe_cache_lookup{} :
- moe_cache->build_lookup(*this, { il, up_exps, gate_exps, down_exps, gate_up_exps, weight_before_ffn }, selected_experts);
+ moe_cache->build_lookup(*this, { il, up_exps, gate_exps, down_exps, gate_up_exps, weight_before_ffn, moe_cache_pass }, selected_experts);
cur = ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens);
diff --git a/src/llama-graph.h b/src/llama-graph.h
index ff155f1..0d2682b 100644
--- a/src/llama-graph.h
+++ b/src/llama-graph.h
@@ -1146,6 +1146,7 @@ struct llm_graph_context {
const llama_memory_context_i * mctx;
const llama_cross * cross;
const llama_moe_cache * moe_cache;
+ int32_t moe_cache_pass = 0; // TIP: which expert selection of the current layer this is, for graphs that route a layer more than once
const llama_hadamard * hdmd;
diff --git a/src/llama-moe-cache.cpp b/src/llama-moe-cache.cpp
index ba35af0..037a299 100644
--- a/src/llama-moe-cache.cpp
+++ b/src/llama-moe-cache.cpp
@@ -343,11 +343,16 @@ struct llama_moe_cache::impl {
moe_cache_lru lru;
};
+ // TIP: selections of one layer that one graph may look up, see get_slot_map
+ static constexpr int32_t max_pass = 32;
+
struct layer {
int32_t ig = -1; // -1 if the layer is not cached
ggml_tensor * slot_map = nullptr; // I32 [1, n_expert] in host memory
ggml_tensor * slot_map_cpu = nullptr; // looked up in place of slot_map by the graphs with a CPU part, if cpu_share > 0, its data is not used
ggml_tensor * cpu_map = nullptr; // I32 [1, n_expert] in host memory, if cpu_share > 0
+ std::vector<ggml_tensor *> slot_map_pass; // TIP: aliases of slot_map for the later selections of the layer in one graph, their data is not used
+ std::vector<ggml_tensor *> slot_map_cpu_pass; // TIP: the same for slot_map_cpu
std::vector<int32_t> cpu_experts; // experts set in cpu_map
uint32_t cpu_acc = 0; // fraction of a miss carried over to the next plan, in 1/65536
std::vector<ggml_tensor *> experts; // host expert tensors, in the order of the banks
@@ -517,6 +522,7 @@ struct llama_moe_cache::impl {
g.lru.init(model.layers.size(), n_expert, g.n_slots);
n_tensors[g.id] += g.ref.size()*(1 + g.layers.size());
n_tensors_host += g.layers.size()*(n_zero > 0 ? 3 : 1); // slot maps and CPU map
+ n_tensors_host += g.layers.size()*(n_zero > 0 ? 2 : 1)*(max_pass - 1); // TIP: slot map aliases of the later passes
}
if (n_tensors_host == 0) {
throw std::runtime_error("MoE cache is too small to hold the experts of one token");
@@ -571,11 +577,25 @@ struct llama_moe_cache::impl {
ggml_format_name(l.slot_map, "moe_cache.slot_map-%d", il);
layer_of[l.slot_map] = { il, false };
buf_host_size += GGML_PAD(ggml_nbytes(l.slot_map), alignment_host);
+ for (int32_t p = 1; p < max_pass; ++p) { // TIP
+ ggml_tensor * alias = ggml_new_tensor_2d(ctx_host.get(), GGML_TYPE_I32, 1, g.ref[0]->ne[2]);
+ ggml_format_name(alias, "moe_cache.slot_map-%d.%d", il, p);
+ layer_of[alias] = { il, false };
+ buf_host_size += GGML_PAD(ggml_nbytes(alias), alignment_host);
+ l.slot_map_pass.push_back(alias);
+ }
if (n_zero > 0) {
l.slot_map_cpu = ggml_new_tensor_2d(ctx_host.get(), GGML_TYPE_I32, 1, g.ref[0]->ne[2]);
ggml_format_name(l.slot_map_cpu, "moe_cache.slot_map_cpu-%d", il);
layer_of[l.slot_map_cpu] = { il, true };
buf_host_size += GGML_PAD(ggml_nbytes(l.slot_map_cpu), alignment_host);
+ for (int32_t p = 1; p < max_pass; ++p) { // TIP
+ ggml_tensor * alias = ggml_new_tensor_2d(ctx_host.get(), GGML_TYPE_I32, 1, g.ref[0]->ne[2]);
+ ggml_format_name(alias, "moe_cache.slot_map_cpu-%d.%d", il, p);
+ layer_of[alias] = { il, true };
+ buf_host_size += GGML_PAD(ggml_nbytes(alias), alignment_host);
+ l.slot_map_cpu_pass.push_back(alias);
+ }
l.cpu_map = ggml_new_tensor_2d(ctx_host.get(), GGML_TYPE_I32, 1, g.ref[0]->ne[2]);
ggml_format_name(l.cpu_map, "moe_cache.cpu_map-%d", il);
buf_host_size += GGML_PAD(ggml_nbytes(l.cpu_map), alignment_host);
@@ -688,7 +708,8 @@ struct llama_moe_cache::impl {
// the slot map of layer il, if its experts can be read from the cache for n_tokens tokens, nullptr otherwise
// cpu_part: the graph computes the misses in the CPU map of the layer (see get_cpu_map)
- ggml_tensor * get_slot_map(int32_t il, int64_t n_tokens, int64_t n_expert_used, bool cpu_part) const {
+ // pass: which selection of the layer in the graph (TIP), 0 for the first
+ ggml_tensor * get_slot_map(int32_t il, int64_t n_tokens, int64_t n_expert_used, bool cpu_part, int32_t pass) const {
if (il < 0 || il >= (int32_t) layers.size() || layers[il].ig < 0) {
return nullptr;
}
@@ -699,6 +720,13 @@ struct llama_moe_cache::impl {
return nullptr;
}
GGML_ASSERT(!cpu_part || l.slot_map_cpu != nullptr);
+ if (pass > 0) {
+ // TIP: a later selection of the same layer in the same graph (a looped block that routes again).
+ // the scheduler copies a host weight once per graph, so each selection looks up its own alias of the slot map:
+ // it then gets its own copy, hence its own copy callback, which uploads the experts of that selection
+ const std::vector<ggml_tensor *> & aliases = cpu_part ? l.slot_map_cpu_pass : l.slot_map_pass;
+ return pass - 1 < (int32_t) aliases.size() ? aliases[pass - 1] : nullptr;
+ }
return cpu_part ? l.slot_map_cpu : l.slot_map;
}
@@ -899,7 +927,7 @@ llama_moe_cache_lookup llama_moe_cache::build_lookup(const llm_graph_context & g
}
ggml_tensor * cpu_map = cpu_part ? pimpl->get_cpu_map(il, selected_experts->ne[1]) : nullptr;
- ggml_tensor * slot_map = pimpl->get_slot_map(il, selected_experts->ne[1], selected_experts->ne[0], cpu_map != nullptr);
+ ggml_tensor * slot_map = pimpl->get_slot_map(il, selected_experts->ne[1], selected_experts->ne[0], cpu_map != nullptr, layer.pass);
if (slot_map == nullptr) {
return {};
}
diff --git a/src/llama-moe-cache.h b/src/llama-moe-cache.h
index 833eac3..c45b6ad 100644
--- a/src/llama-moe-cache.h
+++ b/src/llama-moe-cache.h
@@ -17,6 +17,7 @@ struct llama_moe_cache_layer {
ggml_tensor * down_exps;
ggml_tensor * gate_up_exps;
bool weight_before_ffn; // the router weights scale the expert input
+ int32_t pass = 0; // TIP: which selection of this layer in the graph, 0 for the first (a looped block may route again)
};
// the lookup of the selected experts of a layer in the MoE cache, see llama_moe_cache::build_lookup
diff --git a/src/models/models.h b/src/models/models.h
index 3b4f04c..5a56f53 100644
--- a/src/models/models.h
+++ b/src/models/models.h
@@ -1,5 +1,6 @@
#pragma once
+#include "tip.h"
#include "llama-model.h"
#include "llama-graph.h"
#include "llama-model-loader.h"
@@ -2831,7 +2832,7 @@ struct llama_model_qwen35 : public llama_model_base {
llama_model_qwen35(const struct llama_model_params & params) : llama_model_base(params) {}
void load_arch_hparams(llama_model_loader & ml) override;
void load_arch_tensors(llama_model_loader & ml) override;
- uint32_t graph_nodes_per_tensor() const override { return 32; }
+ uint32_t graph_nodes_per_tensor() const override { return 32 * tip_cfg::get().graph_scale(); } // TIP: room for the looped blocks
struct graph : public llm_build_delta_net_base {
graph(const llm_graph_params & params);
@@ -3083,7 +3084,7 @@ struct llama_model_qwen35moe : public llama_model_base {
llama_model_qwen35moe(const struct llama_model_params & params) : llama_model_base(params) {}
void load_arch_hparams(llama_model_loader & ml) override;
void load_arch_tensors(llama_model_loader & ml) override;
- uint32_t graph_nodes_per_tensor() const override { return 32; }
+ uint32_t graph_nodes_per_tensor() const override { return 32 * tip_cfg::get().graph_scale(); } // TIP: room for the looped blocks
struct graph : public llm_build_delta_net_base {
graph(const llm_graph_params & params);
@@ -3101,7 +3102,8 @@ struct llama_model_qwen35moe : public llama_model_base {
ggml_tensor * build_layer_ffn(
ggml_tensor * cur,
- int il);
+ int il,
+ ggml_tensor * selected_experts = nullptr);
ggml_tensor * build_norm_gated(
ggml_tensor * input,
diff --git a/src/models/qwen35.cpp b/src/models/qwen35.cpp
index 5b05fc6..0b1c5b6 100644
--- a/src/models/qwen35.cpp
+++ b/src/models/qwen35.cpp
@@ -1,5 +1,10 @@
#include "models.h"
#include "llama-memory-recurrent.h"
+#include "tip.h"
+
+// The TIP code in this file is Copyright (c) 2026 Vincent Mathieu Malet and is licensed
+// for non-commercial use only (PolyForm-Noncommercial-1.0.0), see LICENSE-TIP.md.
+// The rest of this file is llama.cpp, MIT.
void llama_model_qwen35::load_arch_hparams(llama_model_loader & ml) {
ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
@@ -159,49 +164,120 @@ llama_model_qwen35::graph::graph(const llm_graph_params & params) :
ggml_tensor * inp_pos = build_inp_pos();
ggml_tensor * inp_out_ids = build_inp_out_ids();
+ const tip_cfg & loop = tip_cfg::get();
+ int loop_il_max = 0; // deepest full-attention layer: where the depth law reaches R
+ for (int il = 0; il < n_layer; ++il) {
+ if (!hparams.is_recr(il)) {
+ loop_il_max = il;
+ }
+ }
+ if (loop.n > 1) {
+ static bool logged = false;
+ if (!logged) {
+ logged = true;
+ LLAMA_LOG_INFO("%s: TIP active: R=%d beta=%.4f depth_law=%d decode_max=%d prefill=%d\n",
+ __func__, loop.n, loop.beta_at(0, loop.n), loop.depth_law, loop.decode_max, loop.prefill ? 1 : 0);
+ }
+ }
+
// MTP/NextN layers are loaded as extra decoder blocks but not executed in the main pass.
for (int il = 0; il < n_layer; ++il) {
res->t_layer_inp[il] = inpL;
- ggml_tensor * inpSA = inpL;
+ // TIP: iterate the block R times on its own hidden state (see tip.h).
+ // R == 1 (default, recurrent layers, prompt-processing batches) is the stock graph.
+ const bool is_full_attn = !hparams.is_recr(il);
+ const int R = loop.iterations(il, loop_il_max, is_full_attn, ubatch.n_seq_tokens);
+
+ ggml_tensor * s0 = inpL; // anchor: the layer's original input
+ ggml_tensor * s = inpL; // current iterate
+ ggml_tensor * frozen = nullptr; // per-token convergence latch (adaptive depth)
+
+ for (int t = 0; t < R; ++t) {
+ const bool last = t == R - 1;
+
+ // input injection: pull the iterate back toward the layer's original input
+ ggml_tensor * in_t = s;
+ const float beta = loop.beta_at(t, R);
+ if (t > 0 && beta > 0.0f) {
+ in_t = ggml_add(ctx0,
+ ggml_scale(ctx0, s, 1.0f - beta),
+ ggml_scale(ctx0, s0, beta));
+ cb(in_t, "loop_inject", il);
+ }
- cur = build_norm(inpL, model.layers[il].attn_norm, nullptr, LLM_NORM_RMS, il);
- cb(cur, "attn_norm", il);
+ ggml_tensor * inpSA = in_t;
- ggml_build_forward_expand(gf, cur);
+ cur = build_norm(in_t, model.layers[il].attn_norm, nullptr, LLM_NORM_RMS, il);
+ cb(cur, "attn_norm", il);
- // Determine layer type and build appropriate attention mechanism
- if (hparams.is_recr(il)) {
- // Linear attention layer (gated delta net)
- cur = build_layer_attn_linear(inp->get_recr(), cur, il);
- } else {
- // Full attention layer
- cur = build_layer_attn(inp->get_attn(), cur, inp_pos, il);
- }
+ ggml_build_forward_expand(gf, cur);
- if (il == n_layer - 1 && crop_before_nextn(inp_out_ids)) {
- cur = ggml_get_rows(ctx0, cur, inp_out_ids);
- inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
- }
+ // Determine layer type and build appropriate attention mechanism
+ if (hparams.is_recr(il)) {
+ // Linear attention layer (gated delta net)
+ cur = build_layer_attn_linear(inp->get_recr(), cur, il);
+ } else {
+ // Full attention layer. Looped: K/V of the current positions are rewritten at
+ // every iteration, the last write is what later tokens attend to.
+ cur = build_layer_attn(inp->get_attn(), cur, inp_pos, il);
+ }
+
+ // The stock single-pass graph keeps only the output rows between attention and FFN.
+ // Under the loop that extraction moves after the block (see below), so that every
+ // iteration works on the same rows.
+ const bool crop = R == 1 && il == n_layer - 1 && crop_before_nextn(inp_out_ids);
+ if (crop) {
+ cur = ggml_get_rows(ctx0, cur, inp_out_ids);
+ inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
+ }
+
+ // Residual connection (against this iteration's block input)
+ cur = ggml_add(ctx0, cur, inpSA);
+ cb(cur, "attn_residual", il);
- // Residual connection
- cur = ggml_add(ctx0, cur, inpSA);
- cb(cur, "attn_residual", il);
+ if (!loop.ffn_last || last) {
+ // Save the tensor before post-attention norm for residual connection
+ ggml_tensor * ffn_residual = cur;
- // Save the tensor before post-attention norm for residual connection
- ggml_tensor * ffn_residual = cur;
+ // Post-attention norm
+ ggml_tensor * attn_post_norm = build_norm(cur, model.layers[il].attn_post_norm, nullptr, LLM_NORM_RMS, il);
+ cb(attn_post_norm, "attn_post_norm", il);
- // Post-attention norm
- ggml_tensor * attn_post_norm = build_norm(cur, model.layers[il].attn_post_norm, nullptr, LLM_NORM_RMS, il);
- cb(attn_post_norm, "attn_post_norm", il);
+ // Dense FFN layer - without residual connection
+ cur = build_layer_ffn(attn_post_norm, il);
+ cb(cur, "ffn_out", il);
- // Dense FFN layer - without residual connection
- cur = build_layer_ffn(attn_post_norm, il);
- cb(cur, "ffn_out", il);
+ // Residual connection for FFN - add to the tensor from before post_attention_layernorm
+ cur = ggml_add(ctx0, cur, ffn_residual);
+ cb(cur, "post_ffn", il);
+ }
+
+ // adaptive depth: per token, once cos(s_{t+1}, s_t) reaches tau the token stops moving
+ // (monotone latch).
+ if (loop.adaptive_tau > 0.0f && R > 1 && t > 0) {
+ ggml_tensor * dot = ggml_sum_rows(ctx0, ggml_mul(ctx0, cur, s)); // [1, n_tokens]
+ ggml_tensor * na = ggml_sqrt(ctx0, ggml_sum_rows(ctx0, ggml_sqr(ctx0, cur)));
+ ggml_tensor * nb = ggml_sqrt(ctx0, ggml_sum_rows(ctx0, ggml_sqr(ctx0, s)));
+ ggml_tensor * cosv = ggml_div(ctx0, dot, ggml_scale_bias(ctx0, ggml_mul(ctx0, na, nb), 1.0f, 1e-12f));
+ ggml_tensor * conv = loop.adaptive_soft > 0.0f
+ ? ggml_sigmoid(ctx0, ggml_scale_bias(ctx0, cosv, 1.0f / loop.adaptive_soft, -loop.adaptive_tau / loop.adaptive_soft))
+ : ggml_step(ctx0, ggml_scale_bias(ctx0, cosv, 1.0f, -loop.adaptive_tau));
+ frozen = frozen
+ ? ggml_sub(ctx0, ggml_add(ctx0, frozen, conv), ggml_mul(ctx0, frozen, conv)) // probabilistic OR
+ : conv;
+ ggml_tensor * gate = ggml_scale_bias(ctx0, frozen, -1.0f, 1.0f); // 1 - frozen
+ cur = ggml_add(ctx0, s, ggml_mul(ctx0, ggml_sub(ctx0, cur, s), gate));
+ cb(cur, "loop_adaptive_gate", il);
+ }
- // Residual connection for FFN - add to the tensor from before post_attention_layernorm
- cur = ggml_add(ctx0, cur, ffn_residual);
- cb(cur, "post_ffn", il);
+ s = cur;
+ }
+ if (R > 1 && il == n_layer - 1 && crop_before_nextn(inp_out_ids)) {
+ // looped last layer: output-row extraction after the whole block
+ s = ggml_get_rows(ctx0, s, inp_out_ids);
+ }
+ cur = s;
cur = build_cvec(cur, il);
cb(cur, "l_out", il);
diff --git a/src/models/qwen35moe.cpp b/src/models/qwen35moe.cpp
index c92b84d..509a381 100644
--- a/src/models/qwen35moe.cpp
+++ b/src/models/qwen35moe.cpp
@@ -1,4 +1,9 @@
#include "models.h"
+#include "tip.h"
+
+// The TIP code in this file is Copyright (c) 2026 Vincent Mathieu Malet and is licensed
+// for non-commercial use only (PolyForm-Noncommercial-1.0.0), see LICENSE-TIP.md.
+// The rest of this file is llama.cpp, MIT.
#include "llama-memory-recurrent.h"
void llama_model_qwen35moe::load_arch_hparams(llama_model_loader & ml) {
@@ -171,49 +176,133 @@ llama_model_qwen35moe::graph::graph(const llm_graph_params & params) :
ggml_tensor * inp_pos = build_inp_pos();
ggml_tensor * inp_out_ids = build_inp_out_ids();
+ const tip_cfg & loop = tip_cfg::get();
+ int loop_il_max = 0; // deepest full-attention layer: where the depth law reaches R
+ for (int il = 0; il < n_layer; ++il) {
+ if (!hparams.is_recr(il)) {
+ loop_il_max = il;
+ }
+ }
+
// MTP/NextN layers are loaded as extra decoder blocks but not executed in the main pass.
for (int il = 0; il < n_layer; ++il) {
res->t_layer_inp[il] = inpL;
- ggml_tensor * inpSA = inpL;
-
- cur = build_norm(inpL, model.layers[il].attn_norm, nullptr, LLM_NORM_RMS, il);
- cb(cur, "attn_norm", il);
-
- ggml_build_forward_expand(gf, cur);
-
- // Determine layer type and build appropriate attention mechanism
- if (hparams.is_recr(il)) {
- // Linear attention layer (gated delta net)
- cur = build_layer_attn_linear(inp->get_recr(), cur, il);
- } else {
- // Full attention layer
- cur = build_layer_attn(inp->get_attn(), cur, inp_pos, il);
+ // TIP: iterate the block R times on its own hidden state (see tip.h).
+ // R == 1 (default, recurrent layers, prompt-processing batches) is the stock graph.
+ // The expert router runs inside the block, so it re-routes at every iteration.
+ const bool is_full_attn = !hparams.is_recr(il);
+ const int R = loop.iterations(il, loop_il_max, is_full_attn, ubatch.n_seq_tokens);
+
+ ggml_tensor * s0 = inpL; // anchor: the layer's original input
+ ggml_tensor * s = inpL; // current iterate
+ ggml_tensor * frozen = nullptr; // per-token convergence latch (adaptive depth)
+ ggml_tensor * route = nullptr; // experts chosen at the first iteration (frozen routing)
+
+ for (int t = 0; t < R; ++t) {
+ const bool last = t == R - 1;
+
+ // input injection: pull the iterate back toward the layer's original input
+ ggml_tensor * in_t = s;
+ const float beta = loop.beta_at(t, R);
+ if (t > 0 && beta > 0.0f) {
+ in_t = ggml_add(ctx0,
+ ggml_scale(ctx0, s, 1.0f - beta),
+ ggml_scale(ctx0, s0, beta));
+ cb(in_t, "loop_inject", il);
+ }
+
+ ggml_tensor * inpSA = in_t;
+
+ cur = build_norm(in_t, model.layers[il].attn_norm, nullptr, LLM_NORM_RMS, il);
+ cb(cur, "attn_norm", il);
+
+ ggml_build_forward_expand(gf, cur);
+
+ // Determine layer type and build appropriate attention mechanism
+ if (hparams.is_recr(il)) {
+ // Linear attention layer (gated delta net)
+ cur = build_layer_attn_linear(inp->get_recr(), cur, il);
+ } else {
+ // Full attention layer. Looped: K/V of the current positions are rewritten at
+ // every iteration, the last write is what later tokens attend to.
+ cur = build_layer_attn(inp->get_attn(), cur, inp_pos, il);
+ }
+
+ // The stock single-pass graph keeps only the output rows between attention and FFN.
+ // Under the loop that extraction moves after the block (see below), so that every
+ // iteration works on the same rows.
+ const bool crop = R == 1 && il == n_layer - 1 && crop_before_nextn(inp_out_ids);
+ if (crop) {
+ cur = ggml_get_rows(ctx0, cur, inp_out_ids);
+ inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
+ }
+
+ // Residual connection (against this iteration's block input)
+ cur = ggml_add(ctx0, cur, inpSA);
+ cb(cur, "attn_residual", il);
+
+ if (!loop.ffn_last || last) {
+ // Save the tensor before post-attention norm for residual connection
+ ggml_tensor * ffn_residual = cur;
+
+ // Post-attention norm
+ ggml_tensor * attn_post_norm = build_norm(cur, model.layers[il].attn_post_norm, nullptr, LLM_NORM_RMS, il);
+ cb(attn_post_norm, "attn_post_norm", il);
+
+ // TIP_FREEZE_ROUTE: choose the experts once, from the first iteration's
+ // FFN input, and dispatch every iteration of this token to that same set. Only the
+ // discrete choice is frozen: the gate weights are still recomputed each iteration.
+ ggml_tensor * sel = nullptr;
+ if (loop.freeze_route && R > 1) {
+ if (route == nullptr) {
+ // top-k of the router logits == top-k of their softmax
+ route = ggml_argsort_top_k(ctx0, build_lora_mm(model.layers[il].ffn_gate_inp, attn_post_norm), n_expert_used);
+ cb(route, "loop_frozen_route", il);
+ }
+ sel = route;
+ }
+
+ // Free routing selects again at each iteration: tell the MoE expert cache
+ // (--moe-cache-mib) that this is another selection of the same layer, so that it
+ // uploads the experts of this one too. Frozen routing is a single selection.
+ moe_cache_pass = sel == nullptr ? t : 0;
+
+ // MOE FFN layer
+ cur = build_layer_ffn(attn_post_norm, il, sel);
+ moe_cache_pass = 0;
+ cb(cur, "ffn_out", il);
+
+ // Residual connection for FFN - add to the tensor from before post_attention_layernorm
+ cur = ggml_add(ctx0, cur, ffn_residual);
+ cb(cur, "post_moe", il);
+ }
+
+ // adaptive depth: per token, once cos(s_{t+1}, s_t) reaches tau the token stops moving
+ // (monotone latch).
+ if (loop.adaptive_tau > 0.0f && R > 1 && t > 0) {
+ ggml_tensor * dot = ggml_sum_rows(ctx0, ggml_mul(ctx0, cur, s)); // [1, n_tokens]
+ ggml_tensor * na = ggml_sqrt(ctx0, ggml_sum_rows(ctx0, ggml_sqr(ctx0, cur)));
+ ggml_tensor * nb = ggml_sqrt(ctx0, ggml_sum_rows(ctx0, ggml_sqr(ctx0, s)));
+ ggml_tensor * cosv = ggml_div(ctx0, dot, ggml_scale_bias(ctx0, ggml_mul(ctx0, na, nb), 1.0f, 1e-12f));
+ ggml_tensor * conv = loop.adaptive_soft > 0.0f
+ ? ggml_sigmoid(ctx0, ggml_scale_bias(ctx0, cosv, 1.0f / loop.adaptive_soft, -loop.adaptive_tau / loop.adaptive_soft))
+ : ggml_step(ctx0, ggml_scale_bias(ctx0, cosv, 1.0f, -loop.adaptive_tau));
+ frozen = frozen
+ ? ggml_sub(ctx0, ggml_add(ctx0, frozen, conv), ggml_mul(ctx0, frozen, conv)) // probabilistic OR
+ : conv;
+ ggml_tensor * gate = ggml_scale_bias(ctx0, frozen, -1.0f, 1.0f); // 1 - frozen
+ cur = ggml_add(ctx0, s, ggml_mul(ctx0, ggml_sub(ctx0, cur, s), gate));
+ cb(cur, "loop_adaptive_gate", il);
+ }
+
+ s = cur;
}
-
- if (il == n_layer - 1 && crop_before_nextn(inp_out_ids)) {
- cur = ggml_get_rows(ctx0, cur, inp_out_ids);
- inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
+ if (R > 1 && il == n_layer - 1 && crop_before_nextn(inp_out_ids)) {
+ // looped last layer: output-row extraction after the whole block
+ s = ggml_get_rows(ctx0, s, inp_out_ids);
}
-
- // Residual connection
- cur = ggml_add(ctx0, cur, inpSA);
- cb(cur, "attn_residual", il);
-
- // Save the tensor before post-attention norm for residual connection
- ggml_tensor * ffn_residual = cur;
-
- // Post-attention norm
- ggml_tensor * attn_post_norm = build_norm(cur, model.layers[il].attn_post_norm, nullptr, LLM_NORM_RMS, il);
- cb(attn_post_norm, "attn_post_norm", il);
-
- // MOE FFN layer
- cur = build_layer_ffn(attn_post_norm, il);
- cb(cur, "ffn_out", il);
-
- // Residual connection for FFN - add to the tensor from before post_attention_layernorm
- cur = ggml_add(ctx0, cur, ffn_residual);
- cb(cur, "post_moe", il);
+ cur = s;
cur = build_cvec(cur, il);
cb(cur, "l_out", il);
@@ -464,7 +553,7 @@ ggml_tensor * llama_model_qwen35moe::graph::build_layer_attn_linear(
return cur;
}
-ggml_tensor * llama_model_qwen35moe::graph::build_layer_ffn(ggml_tensor * cur, const int il) {
+ggml_tensor * llama_model_qwen35moe::graph::build_layer_ffn(ggml_tensor * cur, const int il, ggml_tensor * selected_experts) {
// Check if this is an MoE layer
GGML_ASSERT(model.layers[il].ffn_gate_inp != nullptr);
@@ -479,7 +568,8 @@ ggml_tensor * llama_model_qwen35moe::graph::build_layer_ffn(ggml_tensor * cur, c
LLM_FFN_SILU, true,
hparams.expert_weights_scale,
LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il,
- nullptr, model.layers[il].ffn_gate_up_exps);
+ nullptr, model.layers[il].ffn_gate_up_exps,
+ selected_experts);
cb(moe_out, "ffn_moe_out", il);
// Add shared experts if present - following Qwen3Next reference implementation
diff --git a/src/models/tip.h b/src/models/tip.h
new file mode 100644
index 0000000..c331c77
--- /dev/null
+++ b/src/models/tip.h
@@ -0,0 +1,134 @@
+#pragma once
+
+// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
+// Thinking in Place - Copyright (c) 2026 Vincent Mathieu Malet. Non-commercial use only; commercial use
+// requires a licence from the author. See LICENSE-TIP.md.
+
+// TIP (Thinking in Place) — anchored recurrent depth, training-free.
+//
+// Each selected FULL-ATTENTION layer block (norm -> attn -> residual -> norm -> ffn -> residual)
+// is iterated R times on its own hidden state at inference, on frozen weights:
+//
+// s_0 = layer input
+// in_t = (1 - beta) * s_t + beta * s_0 (t > 0 : input injection, the anchor)
+// s_{t+1} = Block(in_t)
+//
+// Recurrent-state layers (gated delta net / linear attention) are never looped: their sequential
+// state must advance exactly once per token.
+//
+// K/V of the current positions are rewritten at every iteration; the last (converged) iteration
+// is what stays in the cache for future tokens.
+//
+// All knobs are environment variables, read once. TIP_N=1 (default) builds the stock graph.
+//
+// TIP_N R, iterations of the deepest looped layer (default 1 = off)
+// TIP_BETA_LAW how the anchor strength is derived (default budget)
+// "budget" : beta = 1 - 0.618 / N, one value for every layer, from the budget
+// "ref" : beta = 1 - 0.618 / 12 = 0.9485, whatever the budget
+// "layer" : beta(il) = 1 - 0.618 / R(il), from each layer's own iterations
+// TIP_BETA an explicit anchor strength in [0,1], overrides the law
+// TIP_BETA_SCHEDULE "linear" : anneal beta from BETA_MIN (t=0) to beta (default off)
+// TIP_BETA_MIN start of the anneal (default 0.3)
+// TIP_DEPTH_LAW "sqrt" | "log" | "square" | "flat" : R per layer (default sqrt, the validated law)
+// TIP_LAYERS csv of layer indices to loop (default all full-attention)
+// TIP_FFN_LAST 1 : run the FFN only on the last iteration (default 0)
+// TIP_FREEZE_ROUTE MoE only: keep the experts chosen at iteration 0 (default 1 ; 0 = re-route every iteration)
+// TIP_DECODE_MAX largest ubatch (tokens per sequence) still looped (default 32)
+// TIP_PREFILL 1 : loop prompt-processing batches too (default 0)
+// TIP_ADAPTIVE_TAU per-token freeze once cos(s_t, s_{t-1}) >= tau (default 0 = off)
+// TIP_ADAPTIVE_SOFT width of a soft (sigmoid) freeze instead of a step (default 0 = step)
+
+#include <algorithm>
+#include <cmath>
+#include <cstdlib>
+#include <cstring>
+#include <vector>
+
+struct tip_cfg {
+ int n = 1;
+ static constexpr float phi_inv = 0.6180339887f; // 1/phi
+ float beta = -1.0f; // explicit value (TIP_BETA), < 0 = derived from the law
+ int beta_law = 0; // 0 budget, 1 ref, 2 layer
+ bool beta_anneal = false;
+ float beta_min = 0.3f;
+ int depth_law = 1; // 0 flat, 1 sqrt, 2 log, 3 square
+ bool ffn_last = false;
+ bool freeze_route = true;
+ int decode_max = 32;
+ bool prefill = false;
+ float adaptive_tau = 0.0f;
+ float adaptive_soft = 0.0f;
+ std::vector<int> layers; // empty = every full-attention layer
+
+ static float clamp01(float v) { return v < 0.0f ? 0.0f : (v > 1.0f ? 1.0f : v); }
+
+ static const tip_cfg & get() {
+ static const tip_cfg cfg = [] {
+ tip_cfg c;
+ if (const char * e = getenv("TIP_N")) { c.n = std::max(1, atoi(e)); }
+ if (const char * e = getenv("TIP_BETA")) { c.beta = clamp01((float) atof(e)); }
+ if (const char * e = getenv("TIP_BETA_LAW")) { c.beta_law = !strcmp(e, "ref") ? 1 : (!strcmp(e, "layer") || !strcmp(e, "phi")) ? 2 : 0; }
+ if (const char * e = getenv("TIP_BETA_SCHEDULE")){ c.beta_anneal = !strcmp(e, "linear"); }
+ if (const char * e = getenv("TIP_BETA_MIN")) { c.beta_min = clamp01((float) atof(e)); }
+ if (const char * e = getenv("TIP_DEPTH_LAW")) {
+ c.depth_law = !strcmp(e, "flat") ? 0 : !strcmp(e, "log") ? 2 : !strcmp(e, "square") ? 3 : 1;
+ }
+ if (const char * e = getenv("TIP_FFN_LAST")) { c.ffn_last = atoi(e) != 0; }
+ if (const char * e = getenv("TIP_FREEZE_ROUTE")) { c.freeze_route = atoi(e) != 0; }
+ if (const char * e = getenv("TIP_DECODE_MAX")) { c.decode_max = atoi(e); }
+ if (const char * e = getenv("TIP_PREFILL")) { c.prefill = atoi(e) != 0; }
+ if (const char * e = getenv("TIP_ADAPTIVE_TAU")) { c.adaptive_tau = (float) atof(e); }
+ if (const char * e = getenv("TIP_ADAPTIVE_SOFT")){ c.adaptive_soft = (float) atof(e); }
+ if (const char * e = getenv("TIP_LAYERS")) {
+ for (const char * p = e; *p; ) {
+ c.layers.push_back(atoi(p));
+ while (*p && *p != ',') { p++; }
+ if (*p == ',') { p++; }
+ }
+ }
+ return c;
+ }();
+ return cfg;
+ }
+
+ // Iterations for layer `il`. `il_max` = index of the deepest full-attention layer.
+ // `n_seq_tokens` = tokens per sequence in this ubatch: large batches are prompt processing,
+ // nothing is sampled from them except their last position, so they run once unless forced.
+ int iterations(int il, int il_max, bool is_full_attn, int64_t n_seq_tokens) const {
+ if (n <= 1 || !is_full_attn) {
+ return 1;
+ }
+ if (!layers.empty() && std::find(layers.begin(), layers.end(), il) == layers.end()) {
+ return 1;
+ }
+ if (!prefill && n_seq_tokens > decode_max) {
+ return 1;
+ }
+ if (depth_law == 0 || il_max <= 0) {
+ return n;
+ }
+ float raw, raw_max;
+ switch (depth_law) {
+ case 1: raw = sqrtf((float) il); raw_max = sqrtf((float) il_max); break;
+ case 3: raw = (float) il * (float) il; raw_max = (float) il_max * (float) il_max; break;
+ default: raw = logf((float) std::max(il, 1)); raw_max = logf((float) il_max); break;
+ }
+ const float scale = raw_max > 0.0f ? (float) n / raw_max : 1.0f;
+ return std::max(1, (int) std::lround(raw * scale));
+ }
+
+ // The loop adds graph nodes in proportion to the budget: scale the graph size with it.
+ uint32_t graph_scale() const { return 1 + (uint32_t) n / 8; }
+
+ // Anchor strength at iteration t of a layer that runs R iterations.
+ float beta_at(int t, int R) const {
+ const float layer_beta = beta >= 0.0f ? beta // explicit
+ : beta_law == 1 ? 1.0f - phi_inv / 12.0f // reference budget
+ : beta_law == 2 ? 1.0f - phi_inv / (float) std::max(R, 1) // this layer's iterations
+ : 1.0f - phi_inv / (float) std::max(n, 1); // the budget
+ if (beta_anneal && R > 1) {
+ return beta_min + ((float) t / (float) (R - 1)) * (layer_beta - beta_min);
+ }
+ return layer_beta;
+ }
+};
|