File size: 38,015 Bytes
6c6d106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
From a9cbbc9507f222b763994cb8f61ae482772b89c4 Mon Sep 17 00:00:00 2001
From: esokullu <esokullu@gmail.com>
Date: Sun, 29 Nov 2026 14:53:13 +0300
Subject: [PATCH] model : add bailingmoe2_loop architecture for looped
 BailingMoeV2 models

Assisted-by: Antigravity
---
 conversion/__init__.py          |   1 +
 conversion/bailingmoe.py        |  59 +++++++++
 gguf-py/gguf/constants.py       |  37 ++++++
 src/llama-arch.cpp              |   8 ++
 src/llama-arch.h                |   4 +
 src/llama-context.cpp           |   2 +-
 src/llama-model.cpp             |   7 +-
 src/llama-quant.cpp             |   4 +
 src/models/bailingmoe2-loop.cpp | 135 ++++++++++++++++++++
 src/models/bailingmoe2.cpp      | 218 +++++++++++++++++++-------------
 src/models/models.h             |  47 +++++++
 tests/test-llama-archs.cpp      |  10 ++
 12 files changed, 441 insertions(+), 91 deletions(-)
 create mode 100644 src/models/bailingmoe2-loop.cpp

diff --git a/conversion/__init__.py b/conversion/__init__.py
index 6796820..7ee19d4 100644
--- a/conversion/__init__.py
+++ b/conversion/__init__.py
@@ -31,6 +31,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
     "BaichuanForCausalLM": "baichuan",
     "BailingMoeForCausalLM": "bailingmoe",
     "BailingMoeV2ForCausalLM": "bailingmoe",
+    "LoopedBailingMoeV2ForCausalLM": "bailingmoe",
     "BailingMoeV3ForCausalLM": "bailingmoe3",
     "BailingMoeV3VLForConditionalGeneration": "bailingmoe3",
     "BambaForCausalLM": "granite",
diff --git a/conversion/bailingmoe.py b/conversion/bailingmoe.py
index 18fe8a2..a647ab3 100644
--- a/conversion/bailingmoe.py
+++ b/conversion/bailingmoe.py
@@ -230,3 +230,62 @@ class SarvamMoEModel(BailingMoeV2Model):
                 t = inner()
                 return t - t.mean()
         return super().filter_tensors((name, gen))
+
+
+@ModelBase.register("LoopedBailingMoeV2ForCausalLM")
+@ModelBase.example("webbrain-one/WebBrain-RingLoop-16B-A1.4B")
+class LoopedBailingMoeV2Model(BailingMoeV2Model):
+    model_arch = gguf.MODEL_ARCH.BAILINGMOE2_LOOP
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        self.core_start = int(self.hparams["loop_core_start"])
+        self.core_end   = int(self.hparams["loop_core_end"])
+        self.num_passes = int(self.hparams["loop_num_passes"])
+        self.gate_rank  = int(self.hparams["loop_gate_rank"])
+        self._loop_queries: dict[int, dict[str, Tensor]] = {}
+
+    def set_gguf_parameters(self):
+        super().set_gguf_parameters()
+        self.gguf_writer.add_loop_start(self.core_start)
+        self.gguf_writer.add_loop_end(self.core_end)
+        self.gguf_writer.add_loop_count(self.num_passes)
+        self.gguf_writer.add_loop_gate_rank(self.gate_rank)
+
+    def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: int) -> gguf.GGMLQuantizationType | bool:
+        if new_name.endswith(("loop_msg_query.weight", "_ctrl_down.weight", "_ctrl_gain.weight", "_ctrl_forget.weight")):
+            return gguf.GGMLQuantizationType.F32
+        return super().tensor_force_quant(name, new_name, bid, n_dims)
+
+    def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
+        if name.startswith("loop_adapter."):
+            parts = name.split(".")
+            kind = parts[1]
+            idx = int(parts[2])
+            phys_bid = self.core_start + idx
+
+            if kind in ("attn_readers", "mlp_readers") and parts[3] == "q":
+                site = "attn" if kind == "attn_readers" else "mlp"
+                entry = self._loop_queries.setdefault(idx, {})
+                entry[site] = data_torch.float()
+                if "attn" in entry and "mlp" in entry:
+                    stacked = torch.stack([entry["attn"], entry["mlp"]], dim=0)
+                    yield self.format_tensor_name(gguf.MODEL_TENSOR.LOOP_MSG_QUERY, phys_bid, ".weight"), stacked
+                return
+
+            gate_map = {
+                ("attn_gates", "w_down"):   gguf.MODEL_TENSOR.LOOP_ATTN_CTRL_DOWN,
+                ("attn_gates", "w_gain"):   gguf.MODEL_TENSOR.LOOP_ATTN_CTRL_GAIN,
+                ("attn_gates", "w_forget"): gguf.MODEL_TENSOR.LOOP_ATTN_CTRL_FORGET,
+                ("mlp_gates",  "w_down"):   gguf.MODEL_TENSOR.LOOP_FFN_CTRL_DOWN,
+                ("mlp_gates",  "w_gain"):   gguf.MODEL_TENSOR.LOOP_FFN_CTRL_GAIN,
+                ("mlp_gates",  "w_forget"): gguf.MODEL_TENSOR.LOOP_FFN_CTRL_FORGET,
+            }
+            if (kind, parts[3]) in gate_map:
+                yield self.format_tensor_name(gate_map[(kind, parts[3])], phys_bid, ".weight"), data_torch.float()
+                return
+
+            raise ValueError(f"Unrecognized loop_adapter tensor: {name}")
+
+        yield from super().modify_tensors(data_torch, name, bid)
+
diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py
index 347378e..c416127 100644
--- a/gguf-py/gguf/constants.py
+++ b/gguf-py/gguf/constants.py
@@ -728,6 +728,7 @@ class MODEL_ARCH(IntEnum):
     PLM              = auto()
     BAILINGMOE       = auto()
     BAILINGMOE2      = auto()
+    BAILINGMOE2_LOOP = auto()
     BAILINGMOE3      = auto()
     DOTS1            = auto()
     DOTS3NOTE        = auto()
@@ -904,6 +905,9 @@ class MODEL_TENSOR(IntEnum):
     LOOP_V_CTRL_DOWN     = auto()
     LOOP_V_CTRL_GAIN     = auto()
     LOOP_V_CTRL_FORGET   = auto()
+    LOOP_ATTN_CTRL_DOWN   = auto()
+    LOOP_ATTN_CTRL_GAIN   = auto()
+    LOOP_ATTN_CTRL_FORGET = auto()
     LOOP_FFN_CTRL_DOWN   = auto()
     LOOP_FFN_CTRL_GAIN   = auto()
     LOOP_FFN_CTRL_FORGET = auto()
@@ -1758,6 +1762,7 @@ MODEL_ARCH_NAMES: dict[MODEL_ARCH, str] = {
     MODEL_ARCH.PLM:              "plm",
     MODEL_ARCH.BAILINGMOE:       "bailingmoe",
     MODEL_ARCH.BAILINGMOE2:      "bailingmoe2",
+    MODEL_ARCH.BAILINGMOE2_LOOP: "bailingmoe2_loop",
     MODEL_ARCH.BAILINGMOE3:      "bailingmoe3",
     MODEL_ARCH.DOTS1:            "dots1",
     MODEL_ARCH.DOTS3NOTE:        "dots3note",
@@ -1935,6 +1940,9 @@ TENSOR_NAMES: dict[MODEL_TENSOR, str] = {
     MODEL_TENSOR.LOOP_V_CTRL_DOWN:          "blk.{bid}.loop_v_ctrl_down",
     MODEL_TENSOR.LOOP_V_CTRL_GAIN:          "blk.{bid}.loop_v_ctrl_gain",
     MODEL_TENSOR.LOOP_V_CTRL_FORGET:        "blk.{bid}.loop_v_ctrl_forget",
+    MODEL_TENSOR.LOOP_ATTN_CTRL_DOWN:       "blk.{bid}.loop_attn_ctrl_down",
+    MODEL_TENSOR.LOOP_ATTN_CTRL_GAIN:       "blk.{bid}.loop_attn_ctrl_gain",
+    MODEL_TENSOR.LOOP_ATTN_CTRL_FORGET:     "blk.{bid}.loop_attn_ctrl_forget",
     MODEL_TENSOR.LOOP_FFN_CTRL_DOWN:        "blk.{bid}.loop_ffn_ctrl_down",
     MODEL_TENSOR.LOOP_FFN_CTRL_GAIN:        "blk.{bid}.loop_ffn_ctrl_gain",
     MODEL_TENSOR.LOOP_FFN_CTRL_FORGET:      "blk.{bid}.loop_ffn_ctrl_forget",
@@ -5730,6 +5738,35 @@ MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
         MODEL_TENSOR.NEXTN_SHARED_HEAD_NORM,
         MODEL_TENSOR.LAYER_OUT_NORM,
     ],
+    MODEL_ARCH.BAILINGMOE2_LOOP: [
+        MODEL_TENSOR.TOKEN_EMBD,
+        MODEL_TENSOR.OUTPUT_NORM,
+        MODEL_TENSOR.OUTPUT,
+        MODEL_TENSOR.ATTN_NORM,
+        MODEL_TENSOR.ATTN_Q_NORM,
+        MODEL_TENSOR.ATTN_K_NORM,
+        MODEL_TENSOR.ATTN_QKV,
+        MODEL_TENSOR.ATTN_OUT,
+        MODEL_TENSOR.FFN_GATE_INP,
+        MODEL_TENSOR.FFN_EXP_PROBS_B,
+        MODEL_TENSOR.FFN_NORM,
+        MODEL_TENSOR.FFN_GATE,
+        MODEL_TENSOR.FFN_DOWN,
+        MODEL_TENSOR.FFN_UP,
+        MODEL_TENSOR.FFN_GATE_EXP,
+        MODEL_TENSOR.FFN_DOWN_EXP,
+        MODEL_TENSOR.FFN_UP_EXP,
+        MODEL_TENSOR.FFN_GATE_SHEXP,
+        MODEL_TENSOR.FFN_DOWN_SHEXP,
+        MODEL_TENSOR.FFN_UP_SHEXP,
+        MODEL_TENSOR.LOOP_MSG_QUERY,
+        MODEL_TENSOR.LOOP_ATTN_CTRL_DOWN,
+        MODEL_TENSOR.LOOP_ATTN_CTRL_GAIN,
+        MODEL_TENSOR.LOOP_ATTN_CTRL_FORGET,
+        MODEL_TENSOR.LOOP_FFN_CTRL_DOWN,
+        MODEL_TENSOR.LOOP_FFN_CTRL_GAIN,
+        MODEL_TENSOR.LOOP_FFN_CTRL_FORGET,
+    ],
     MODEL_ARCH.BAILINGMOE3: [
         MODEL_TENSOR.TOKEN_EMBD,
         MODEL_TENSOR.OUTPUT_NORM,
diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp
index fe0b808..926497c 100644
--- a/src/llama-arch.cpp
+++ b/src/llama-arch.cpp
@@ -121,6 +121,7 @@ static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
     { LLM_ARCH_PLM,              "plm"              },
     { LLM_ARCH_BAILINGMOE,       "bailingmoe"       },
     { LLM_ARCH_BAILINGMOE2,      "bailingmoe2"      },
+    { LLM_ARCH_BAILINGMOE2_LOOP, "bailingmoe2_loop" },
     { LLM_ARCH_BAILINGMOE3,      "bailingmoe3"      },
     { LLM_ARCH_DOTS1,            "dots1"            },
     { LLM_ARCH_DOTS3NOTE,        "dots3note"        },
@@ -613,6 +614,9 @@ static const std::map<llm_tensor, const char *> LLM_TENSOR_NAMES = {
     { LLM_TENSOR_LOOP_V_CTRL_DOWN,                       "blk.%d.loop_v_ctrl_down" },
     { LLM_TENSOR_LOOP_V_CTRL_GAIN,                       "blk.%d.loop_v_ctrl_gain" },
     { LLM_TENSOR_LOOP_V_CTRL_FORGET,                     "blk.%d.loop_v_ctrl_forget" },
+    { LLM_TENSOR_LOOP_ATTN_CTRL_DOWN,                    "blk.%d.loop_attn_ctrl_down" },
+    { LLM_TENSOR_LOOP_ATTN_CTRL_GAIN,                    "blk.%d.loop_attn_ctrl_gain" },
+    { LLM_TENSOR_LOOP_ATTN_CTRL_FORGET,                  "blk.%d.loop_attn_ctrl_forget" },
     { LLM_TENSOR_LOOP_FFN_CTRL_DOWN,                     "blk.%d.loop_ffn_ctrl_down" },
     { LLM_TENSOR_LOOP_FFN_CTRL_GAIN,                     "blk.%d.loop_ffn_ctrl_gain" },
     { LLM_TENSOR_LOOP_FFN_CTRL_FORGET,                   "blk.%d.loop_ffn_ctrl_forget" },
@@ -1312,6 +1316,9 @@ static const std::map<llm_tensor, llm_tensor_info> LLM_TENSOR_INFOS = {
     {LLM_TENSOR_LOOP_V_CTRL_DOWN,           {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
     {LLM_TENSOR_LOOP_V_CTRL_GAIN,           {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
     {LLM_TENSOR_LOOP_V_CTRL_FORGET,         {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
+    {LLM_TENSOR_LOOP_ATTN_CTRL_DOWN,        {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
+    {LLM_TENSOR_LOOP_ATTN_CTRL_GAIN,        {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
+    {LLM_TENSOR_LOOP_ATTN_CTRL_FORGET,      {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
     {LLM_TENSOR_LOOP_FFN_CTRL_DOWN,         {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
     {LLM_TENSOR_LOOP_FFN_CTRL_GAIN,         {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
     {LLM_TENSOR_LOOP_FFN_CTRL_FORGET,       {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
@@ -1651,6 +1658,7 @@ bool llama_arch_supports_save(llm_arch arch) {
         case LLM_ARCH_APERTUS:
         case LLM_ARCH_STEP35:
         case LLM_ARCH_CLEF: // the head tensors are not saved
+        case LLM_ARCH_BAILINGMOE2_LOOP:
         case LLM_ARCH_INKLING2_LOOP: // the loop tensors are not saved and the cache slots are expanded at load
         case LLM_ARCH_VLLM_DECISION2:
             return false;
diff --git a/src/llama-arch.h b/src/llama-arch.h
index 305aae2..7016aa8 100644
--- a/src/llama-arch.h
+++ b/src/llama-arch.h
@@ -125,6 +125,7 @@ enum llm_arch {
     LLM_ARCH_PLM,
     LLM_ARCH_BAILINGMOE,
     LLM_ARCH_BAILINGMOE2,
+    LLM_ARCH_BAILINGMOE2_LOOP,
     LLM_ARCH_BAILINGMOE3,
     LLM_ARCH_DOTS1,
     LLM_ARCH_DOTS3NOTE,
@@ -632,6 +633,9 @@ enum llm_tensor {
     LLM_TENSOR_LOOP_V_CTRL_DOWN,
     LLM_TENSOR_LOOP_V_CTRL_GAIN,
     LLM_TENSOR_LOOP_V_CTRL_FORGET,
+    LLM_TENSOR_LOOP_ATTN_CTRL_DOWN,
+    LLM_TENSOR_LOOP_ATTN_CTRL_GAIN,
+    LLM_TENSOR_LOOP_ATTN_CTRL_FORGET,
     LLM_TENSOR_LOOP_FFN_CTRL_DOWN,
     LLM_TENSOR_LOOP_FFN_CTRL_GAIN,
     LLM_TENSOR_LOOP_FFN_CTRL_FORGET,
diff --git a/src/llama-context.cpp b/src/llama-context.cpp
index 35308bf..09edd16 100644
--- a/src/llama-context.cpp
+++ b/src/llama-context.cpp
@@ -3163,7 +3163,7 @@ bool llama_context::sched_copy_experts(ggml_backend_t backend, const ggml_tensor
 
     // Later loop passes can select different experts from the same device copy.
     // TODO: copy only the experts needed by each pass (see #32807 and #32809).
-    if (lctx->model.arch == LLM_ARCH_INKLING2_LOOP) {
+    if (lctx->model.arch == LLM_ARCH_INKLING2_LOOP || lctx->model.arch == LLM_ARCH_BAILINGMOE2_LOOP) {
         return false;
     }
 
diff --git a/src/llama-model.cpp b/src/llama-model.cpp
index f06ea2e..d1afda5 100644
--- a/src/llama-model.cpp
+++ b/src/llama-model.cpp
@@ -291,6 +291,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params
             return new llama_model_bailingmoe(params);
         case LLM_ARCH_BAILINGMOE2:
             return new llama_model_bailingmoe2(params);
+        case LLM_ARCH_BAILINGMOE2_LOOP:
+            return new llama_model_bailingmoe2_loop(params);
         case LLM_ARCH_BAILINGMOE3:
             return new llama_model_bailingmoe3(params);
         case LLM_ARCH_SEED_OSS:
@@ -563,7 +565,7 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
     };
 
     auto get_tensor_config = [&]() -> tensor_config {
-        if (ud->model->arch == LLM_ARCH_HRM_TEXT || ud->model->arch == LLM_ARCH_METIS16) {
+        if (ud->model->arch == LLM_ARCH_HRM_TEXT || ud->model->arch == LLM_ARCH_METIS16 || ud->model->arch == LLM_ARCH_BAILINGMOE2_LOOP) {
             // aliased cache slots cannot satisfy the meta-split invariants, so replicate all tensors
             return {GGML_BACKEND_SPLIT_AXIS_MIRRORED, tensor, 0, 0};
         }
@@ -2825,7 +2827,7 @@ void llama_model::print_info() const {
             LLAMA_LOG_INFO("%s: expert_weights_norm   = %d\n",     __func__, hparams.expert_weights_norm);
         }
 
-        if (arch == LLM_ARCH_BAILINGMOE2 || arch == LLM_ARCH_BAILINGMOE3) {
+        if (arch == LLM_ARCH_BAILINGMOE2 || arch == LLM_ARCH_BAILINGMOE2_LOOP || arch == LLM_ARCH_BAILINGMOE3) {
             LLAMA_LOG_INFO("%s: n_layer_dense_lead    = %d\n",     __func__, hparams.n_layer_dense_lead);
             LLAMA_LOG_INFO("%s: n_ff_exp              = %d\n",     __func__, hparams.n_ff_exp());
             LLAMA_LOG_INFO("%s: n_ff_shexp            = %d\n",     __func__, hparams.n_ff_shexp);
@@ -3888,6 +3890,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) {
         case LLM_ARCH_EXAONE_MOE:
         case LLM_ARCH_MINICPM3:
         case LLM_ARCH_BAILINGMOE2:
+        case LLM_ARCH_BAILINGMOE2_LOOP:
         case LLM_ARCH_DOTS1:
         case LLM_ARCH_HUNYUAN_MOE:
         case LLM_ARCH_JAIS2:
diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp
index 38eb0d5..af1bd59 100644
--- a/src/llama-quant.cpp
+++ b/src/llama-quant.cpp
@@ -332,6 +332,10 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param
     }
 
     // inkling2: short conv kernels, clip scales, residual mix queries, the relative bias projection and the loop tensors
+    if (arch == LLM_ARCH_BAILINGMOE2_LOOP) {
+        quantize &= name.find(".loop_") == std::string::npos;
+    }
+
     if (arch == LLM_ARCH_INKLING2 || arch == LLM_ARCH_INKLING2_LOOP) {
         quantize &= name.find("_conv.weight")         == std::string::npos;
         quantize &= name.find("_clip.weight")         == std::string::npos;
diff --git a/src/models/bailingmoe2-loop.cpp b/src/models/bailingmoe2-loop.cpp
new file mode 100644
index 0000000..1f097e3
--- /dev/null
+++ b/src/models/bailingmoe2-loop.cpp
@@ -0,0 +1,135 @@
+#include "models.h"
+
+int llama_model_bailingmoe2_loop::layer_phys(int il) const {
+    return il < n_phys ? il : (int) core_start + (il - n_phys) % (int) (core_end - core_start);
+}
+
+void llama_model_bailingmoe2_loop::load_arch_hparams(llama_model_loader & ml) {
+    llama_model_bailingmoe2::load_arch_hparams(ml);
+
+    ml.get_key(LLM_KV_LOOP_START,     core_start);
+    ml.get_key(LLM_KV_LOOP_END,       core_end);
+    ml.get_key(LLM_KV_LOOP_COUNT,     n_passes);
+    ml.get_key(LLM_KV_LOOP_GATE_RANK, gate_rank);
+
+    n_phys = (int) hparams.n_layer();
+    if (n_passes < 1u || !gate_rank || core_start >= core_end || core_end > (uint32_t) n_phys || hparams.n_layer_nextn) {
+        throw std::runtime_error(format("bailingmoe2_loop: invalid loop core [%u, %u) with %u passes or gate rank %u for %d layers",
+                core_start, core_end, n_passes, gate_rank, n_phys));
+    }
+    const size_t n_slot = (size_t) n_phys + (size_t) (n_passes - 1) * (core_end - core_start);
+    if (n_slot > LLAMA_MAX_LAYERS) {
+        throw std::runtime_error(format("bailingmoe2_loop: %zu cache slots exceed the maximum of %d", n_slot, LLAMA_MAX_LAYERS));
+    }
+
+    hparams.n_layer_all = (uint32_t) n_slot;
+    for (int il = n_phys; il < (int) n_slot; ++il) {
+        const int p = layer_phys(il);
+        hparams.n_head_arr[il]        = hparams.n_head_arr[p];
+        hparams.n_head_kv_arr[il]     = hparams.n_head_kv_arr[p];
+        hparams.n_ff_arr[il]          = hparams.n_ff_arr[p];
+        hparams.n_ff_exp_arr[il]      = hparams.n_ff_exp_arr[p];
+        hparams.n_expert_used_arr[il] = hparams.n_expert_used_arr[p];
+        hparams.is_swa_impl[il]       = hparams.is_swa_impl[p];
+        hparams.is_recr_impl[il]      = hparams.is_recr_impl[p];
+    }
+}
+
+void llama_model_bailingmoe2_loop::load_arch_tensors(llama_model_loader & ml) {
+    llama_model_bailingmoe2::load_arch_tensors(ml);
+
+    const int64_t n_embd = hparams.n_embd;
+    const int64_t rank   = gate_rank;
+    const llm_tensor down[LOOP_CTRL_COUNT]   = { LLM_TENSOR_LOOP_ATTN_CTRL_DOWN,   LLM_TENSOR_LOOP_FFN_CTRL_DOWN };
+    const llm_tensor gain[LOOP_CTRL_COUNT]   = { LLM_TENSOR_LOOP_ATTN_CTRL_GAIN,   LLM_TENSOR_LOOP_FFN_CTRL_GAIN };
+    const llm_tensor forget[LOOP_CTRL_COUNT] = { LLM_TENSOR_LOOP_ATTN_CTRL_FORGET, LLM_TENSOR_LOOP_FFN_CTRL_FORGET };
+
+    loop_layers.resize(core_end - core_start);
+    for (uint32_t il = core_start; il < core_end; ++il) {
+        auto & l = loop_layers[il - core_start];
+        l.msg_query = create_tensor(tn(LLM_TENSOR_LOOP_MSG_QUERY, "weight", il), {n_embd, LOOP_CTRL_COUNT}, TENSOR_NO_SCALE);
+        for (int c = 0; c < LOOP_CTRL_COUNT; ++c) {
+            l.ctrl_down[c]   = create_tensor(tn(down[c],   "weight", il), {2*n_embd, rank}, 0);
+            l.ctrl_gain[c]   = create_tensor(tn(gain[c],   "weight", il), {rank, n_embd}, 0);
+            l.ctrl_forget[c] = create_tensor(tn(forget[c], "weight", il), {rank, n_embd}, 0);
+        }
+    }
+}
+
+void llama_model_bailingmoe2_loop::post_arch_tensors(llama_model_loader &) {
+    for (int il = n_phys; il < (int) hparams.n_layer(); ++il) {
+        layers[il] = layers[layer_phys(il)];
+    }
+}
+
+std::unique_ptr<llm_graph_context> llama_model_bailingmoe2_loop::build_arch_graph(const llm_graph_params & params) const {
+    return std::make_unique<graph>(params);
+}
+
+llama_model_bailingmoe2_loop::graph::graph(const llm_graph_params & params) :
+    llama_model_bailingmoe2::graph(params, no_build{}) {
+    const auto & m = static_cast<const llama_model_bailingmoe2_loop &>(model);
+    const int start = (int) m.core_start;
+    const int end   = (int) m.core_end;
+
+    ggml_tensor * cur         = build_inp_embd(model.tok_embd);
+    ggml_tensor * inp_pos     = build_inp_pos();
+    auto        * inp_attn    = build_attn_inp_kv();
+    ggml_tensor * inp_out_ids = build_inp_out_ids();
+
+    // Prelude layers 0..core_start-1
+    for (int il = 0; il < start; ++il) {
+        cur = build_layer(il, il, cur, inp_pos, inp_attn, inp_out_ids, false);
+    }
+
+    // Every pass restarts from the prelude output
+    ggml_tensor * h_prelude = cur;
+    std::vector<ggml_tensor *> prev_states;
+
+    for (uint32_t pass = 0; pass < m.n_passes; ++pass) {
+        cur = h_prelude;
+        ggml_tensor * key_stack   = nullptr;
+        ggml_tensor * raw_stack_t = nullptr;
+
+        if (pass > 0) {
+            GGML_ASSERT(!prev_states.empty());
+            ggml_tensor * raw_stack = ggml_reshape_3d(ctx0, prev_states[0], n_embd, 1, n_tokens);
+            for (size_t s = 1; s < prev_states.size(); ++s) {
+                raw_stack = ggml_concat(ctx0, raw_stack, ggml_reshape_3d(ctx0, prev_states[s], n_embd, 1, n_tokens), 1);
+            }
+            key_stack   = ggml_rms_norm(ctx0, raw_stack, 1e-6f);
+            raw_stack_t = ggml_cont(ctx0, ggml_transpose(ctx0, raw_stack));
+        }
+
+        std::vector<ggml_tensor *> cur_states;
+        cur_states.reserve((size_t) (end - start));
+
+        for (int ip = start; ip < end; ++ip) {
+            const int il = pass == 0 ? ip : m.n_phys + (int) (pass - 1) * (end - start) + (ip - start);
+            if (pass == 0) {
+                cur = build_layer(il, ip, cur, inp_pos, inp_attn, inp_out_ids, false);
+            } else {
+                const auto & loop = m.loop_layers[(size_t) (ip - start)];
+                ggml_tensor * messages = mix(key_stack, raw_stack_t, loop.msg_query);
+                cur = build_layer(il, ip, cur, inp_pos, inp_attn, inp_out_ids, false, messages, &loop);
+            }
+            cur_states.push_back(cur);
+        }
+        prev_states = std::move(cur_states);
+    }
+
+    // Coda layers core_end..n_phys-1
+    for (int il = end; il < m.n_phys; ++il) {
+        cur = build_layer(il, il, cur, inp_pos, inp_attn, inp_out_ids, il == m.n_phys - 1);
+    }
+
+    cur = build_norm(cur, model.output_norm, NULL, LLM_NORM_RMS, -1);
+
+    cb(cur, "result_norm", -1);
+    res->t_embd = cur;
+
+    cur = build_lora_mm(model.output, cur);
+
+    cb(cur, "result_output", -1);
+    res->t_logits = cur;
+}
diff --git a/src/models/bailingmoe2.cpp b/src/models/bailingmoe2.cpp
index 6bdcded..a349673 100644
--- a/src/models/bailingmoe2.cpp
+++ b/src/models/bailingmoe2.cpp
@@ -32,9 +32,12 @@ void llama_model_bailingmoe2::load_arch_tensors(llama_model_loader &) {
     GGML_ASSERT(n_expert > 0 && "n_expert must be > 0 for bailingmoe2");
     GGML_ASSERT(n_expert_used > 0 && "n_expert_used must be > 0 for bailingmoe2");
 
-    for (int i = 0; i < n_layer_all; ++i) {
+    const int n_phys_layers = n_layer_phys();
+    const int n_load_layers = n_phys_layers + (int) hparams.n_layer_nextn;
+
+    for (int i = 0; i < n_load_layers; ++i) {
         int flags = 0;
-        if (i >= n_layer) {
+        if (i >= n_phys_layers) {
             // skip all tensors in the NextN layers
             flags |= TENSOR_SKIP;
         }
@@ -71,11 +74,11 @@ void llama_model_bailingmoe2::load_arch_tensors(llama_model_loader &) {
         }
 
         // NextN/MTP tensors (preserved but unused) - conditionally load for last nextn_predict_layers
-        if (i >= n_layer) {
-            layer.nextn.eh_proj          = create_tensor(tn(LLM_TENSOR_NEXTN_EH_PROJ, "weight", i), { 2 * n_embd, n_embd }, flags);
-            layer.nextn.embed_tokens     = create_tensor(tn(LLM_TENSOR_NEXTN_EMBED_TOKENS, "weight", i), { n_embd, n_vocab }, TENSOR_NOT_REQUIRED | flags);
-            layer.nextn.enorm            = create_tensor(tn(LLM_TENSOR_NEXTN_ENORM, "weight", i), { n_embd }, flags);
-            layer.nextn.hnorm            = create_tensor(tn(LLM_TENSOR_NEXTN_HNORM, "weight", i), { n_embd }, flags);
+        if (i >= n_phys_layers) {
+            layer.nextn.eh_proj          = create_tensor(tn(LLM_TENSOR_NEXTN_EH_PROJ,          "weight", i), { 2*n_embd, n_embd }, flags);
+            layer.nextn.embed_tokens     = create_tensor(tn(LLM_TENSOR_NEXTN_EMBED_TOKENS,     "weight", i), { n_embd, n_vocab }, flags);
+            layer.nextn.enorm            = create_tensor(tn(LLM_TENSOR_NEXTN_ENORM,            "weight", i), { n_embd }, flags);
+            layer.nextn.hnorm            = create_tensor(tn(LLM_TENSOR_NEXTN_HNORM,            "weight", i), { n_embd }, flags);
             layer.nextn.shared_head_head = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, "weight", i), { n_embd, n_vocab }, TENSOR_NOT_REQUIRED | flags);
             layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i), { n_embd }, TENSOR_NOT_REQUIRED | flags);
             layer.layer_out_norm         = create_tensor(tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd}, flags);
@@ -87,114 +90,153 @@ std::unique_ptr<llm_graph_context> llama_model_bailingmoe2::build_arch_graph(con
     return std::make_unique<graph>(params);
 }
 
-llama_model_bailingmoe2::graph::graph(const llm_graph_params & params) :
-    llm_graph_context(params) {
-    const int64_t n_embd_head = hparams.n_embd_head_v();
+ggml_tensor * llama_model_bailingmoe2::graph::mix(
+        ggml_tensor * key_stack,
+        ggml_tensor * raw_stack_t,
+        ggml_tensor * query) {
+    ggml_tensor * queries = n_tokens == 1 ? query :
+        ggml_repeat(ctx0, query, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd, query->ne[1], n_tokens));
 
-    GGML_ASSERT(n_embd_head == hparams.n_embd_head_k());
+    ggml_tensor * scores = ggml_mul_mat(ctx0, key_stack, queries);
+    scores = ggml_soft_max_ext(ctx0, scores, nullptr, 1.0f/sqrtf(float(n_embd)), 0.0f);
 
-    ggml_tensor * cur;
-    ggml_tensor * inpL;
+    return ggml_mul_mat(ctx0, scores, raw_stack_t); // [LOOP_CTRL_COUNT, n_embd, n_tokens]
+}
 
-    inpL = build_inp_embd(model.tok_embd);
+ggml_tensor * llama_model_bailingmoe2::graph::control(
+        ggml_tensor * cur,
+        ggml_tensor * message,
+        const loop_layer & loop,
+        int ctrl) {
+    ggml_tensor * gate = ggml_concat(ctx0, ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens), ggml_reshape_3d(ctx0, message, n_embd, 1, n_tokens), 1);
+    gate = ggml_reshape_2d(ctx0, ggml_rms_norm(ctx0, gate, 1e-6f), 2*n_embd, n_tokens);
+    gate = build_lora_mm(loop.ctrl_down[ctrl], gate);
 
-    // inp_pos - contains the positions
-    ggml_tensor * inp_pos = build_inp_pos();
+    ggml_tensor * gain   = ggml_tanh(ctx0, build_lora_mm(loop.ctrl_gain[ctrl],   gate));
+    ggml_tensor * forget = ggml_tanh(ctx0, build_lora_mm(loop.ctrl_forget[ctrl], gate));
 
-    auto * inp_attn = build_attn_inp_kv();
+    return ggml_add(ctx0, ggml_sub(ctx0, cur, ggml_mul(ctx0, forget, cur)), ggml_mul(ctx0, gain, message));
+}
 
-    ggml_tensor * inp_out_ids = build_inp_out_ids();
+ggml_tensor * llama_model_bailingmoe2::graph::build_layer(
+        int il,
+        int ip,
+        ggml_tensor * inpL,
+        ggml_tensor * inp_pos,
+        llm_graph_input_attn_kv * inp_attn,
+        ggml_tensor * inp_out_ids,
+        bool apply_out_ids,
+        ggml_tensor * messages,
+        const loop_layer * loop) {
+    GGML_ASSERT(!messages == !loop);
 
-    for (int il = 0; il < n_layer; ++il) {
-        ggml_tensor * inpSA = inpL;
+    const int64_t n_embd_head = hparams.n_embd_head_v();
+    GGML_ASSERT(n_embd_head == hparams.n_embd_head_k());
 
-        // norm
-        cur = build_norm(inpL, model.layers[il].attn_norm, NULL, LLM_NORM_RMS, il);
-        cb(cur, "attn_norm", il);
+    auto message = [&](int ctrl) {
+        return ggml_reshape_2d(ctx0, ggml_cont(ctx0, ggml_view_3d(ctx0, messages, 1, n_embd, n_tokens, messages->nb[1], messages->nb[2], ctrl*messages->nb[0])), n_embd, n_tokens);
+    };
 
-        // self_attention
-        {
-            auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur,
-                    n_embd_head, n_head, n_head_kv, il);
+    ggml_tensor * inpSA = inpL;
+    ggml_tensor * attn_in = (messages && loop) ? control(inpL, message(LOOP_CTRL_ATTN), *loop, LOOP_CTRL_ATTN) : inpL;
 
-            Qcur = build_norm(Qcur, model.layers[il].attn_q_norm, NULL, LLM_NORM_RMS, il);
-            cb(Qcur, "Qcur_normed", il);
+    // norm
+    ggml_tensor * cur = build_norm(attn_in, model.layers[il].attn_norm, NULL, LLM_NORM_RMS, il);
+    cb(cur, "attn_norm", il);
 
-            Qcur = build_rope(Qcur, inp_pos, il);
+    // self_attention
+    {
+        auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur,
+                n_embd_head, n_head, n_head_kv, il);
 
-            Kcur = build_norm(Kcur, model.layers[il].attn_k_norm, NULL, LLM_NORM_RMS, il);
-            cb(Kcur, "Kcur_normed", il);
+        Qcur = build_norm(Qcur, model.layers[il].attn_q_norm, NULL, LLM_NORM_RMS, il);
+        cb(Qcur, "Qcur_normed", il);
 
-            Kcur = build_rope(Kcur, inp_pos, il);
+        Qcur = build_rope(Qcur, inp_pos, il);
 
-            cb(Qcur, "Qcur", il);
-            cb(Kcur, "Kcur", il);
-            cb(Vcur, "Vcur", il);
+        Kcur = build_norm(Kcur, model.layers[il].attn_k_norm, NULL, LLM_NORM_RMS, il);
+        cb(Kcur, "Kcur_normed", il);
 
-            cur = build_attn(inp_attn,
-                    model.layers[il].wo, model.layers[il].wo_b,
-                    Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f / sqrtf(float(n_embd_head)), il);
-        }
+        Kcur = build_rope(Kcur, inp_pos, il);
 
-        if (il == n_layer - 1 && inp_out_ids) {
-            cur   = ggml_get_rows(ctx0, cur, inp_out_ids);
-            inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
-        }
+        cb(Qcur, "Qcur", il);
+        cb(Kcur, "Kcur", il);
+        cb(Vcur, "Vcur", il);
 
-        ggml_tensor * sa_out = ggml_add(ctx0, cur, inpSA);
-        cb(sa_out, "sa_out", il);
+        cur = build_attn(inp_attn,
+                model.layers[il].wo, model.layers[il].wo_b,
+                Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f / sqrtf(float(n_embd_head)), il);
+    }
+
+    if (apply_out_ids && inp_out_ids) {
+        cur   = ggml_get_rows(ctx0, cur, inp_out_ids);
+        inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
+    }
 
-        // MoE branch
-        cur = build_norm(sa_out, model.layers[il].ffn_norm, NULL, LLM_NORM_RMS, il);
-        cb(cur, "ffn_norm", il);
+    ggml_tensor * sa_out = ggml_add(ctx0, cur, inpSA);
+    cb(sa_out, "sa_out", il);
+
+    ggml_tensor * ffn_in = (messages && loop) ? control(sa_out, message(LOOP_CTRL_FFN), *loop, LOOP_CTRL_FFN) : sa_out;
+
+    // MoE branch
+    cur = build_norm(ffn_in, model.layers[il].ffn_norm, NULL, LLM_NORM_RMS, il);
+    cb(cur, "ffn_norm", il);
+
+    if (static_cast<uint32_t>(ip) < hparams.n_layer_dense_lead) {
+        cur = build_ffn(cur,
+                model.layers[il].ffn_up, NULL,
+                model.layers[il].ffn_gate, NULL,
+                model.layers[il].ffn_down, NULL,
+                NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
+        cb(cur, "ffn_out", il);
+    } else {
+        ggml_tensor * moe_out = build_moe_ffn(cur,
+            model.layers[il].ffn_gate_inp,
+            model.layers[il].ffn_up_exps,
+            model.layers[il].ffn_gate_exps,
+            model.layers[il].ffn_down_exps,
+            model.layers[il].ffn_exp_probs_b,
+            n_expert, n_expert_used,
+            LLM_FFN_SILU, hparams.expert_weights_norm,
+            hparams.expert_weights_scale,
+            (llama_expert_gating_func_type) hparams.expert_gating_func,
+            il);
+        cb(moe_out, "ffn_moe_out", il);
 
-        if (static_cast<uint32_t>(il) < hparams.n_layer_dense_lead) {
-            cur = build_ffn(cur,
-                    model.layers[il].ffn_up, NULL,
-                    model.layers[il].ffn_gate, NULL,
-                    model.layers[il].ffn_down, NULL,
+        {
+            ggml_tensor * ffn_shexp =
+                build_ffn(cur,
+                    model.layers[il].ffn_up_shexp, NULL,
+                    model.layers[il].ffn_gate_shexp, NULL,
+                    model.layers[il].ffn_down_shexp, NULL,
                     NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
+            cb(ffn_shexp, "ffn_shexp", il);
+
+            cur = ggml_add(ctx0, moe_out, ffn_shexp);
             cb(cur, "ffn_out", il);
-        } else {
-            ggml_tensor * moe_out = build_moe_ffn(cur,
-                model.layers[il].ffn_gate_inp,
-                model.layers[il].ffn_up_exps,
-                model.layers[il].ffn_gate_exps,
-                model.layers[il].ffn_down_exps,
-                model.layers[il].ffn_exp_probs_b,
-                n_expert, n_expert_used,
-                LLM_FFN_SILU, hparams.expert_weights_norm,
-                hparams.expert_weights_scale,
-                (llama_expert_gating_func_type) hparams.expert_gating_func,
-                il);
-            cb(moe_out, "ffn_moe_out", il);
-
-            {
-                ggml_tensor * ffn_shexp =
-                    build_ffn(cur,
-                        model.layers[il].ffn_up_shexp, NULL,
-                        model.layers[il].ffn_gate_shexp, NULL,
-                        model.layers[il].ffn_down_shexp, NULL,
-                        NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
-                cb(ffn_shexp, "ffn_shexp", il);
-
-                cur = ggml_add(ctx0, moe_out, ffn_shexp);
-                cb(cur, "ffn_out", il);
-            }
         }
+    }
 
-        cur = ggml_add(ctx0, cur, sa_out);
+    cur = ggml_add(ctx0, cur, sa_out);
 
-        cur = build_cvec(cur, il);
-        cb(cur, "l_out", il);
+    cur = build_cvec(cur, il);
+    cb(cur, "l_out", il);
 
-        // input for next layer
-        inpL = cur;
-    }
+    return cur;
+}
 
-    cur = inpL;
+llama_model_bailingmoe2::graph::graph(const llm_graph_params & params) :
+    llm_graph_context(params) {
+    ggml_tensor * inpL        = build_inp_embd(model.tok_embd);
+    ggml_tensor * inp_pos     = build_inp_pos();
+    auto        * inp_attn    = build_attn_inp_kv();
+    ggml_tensor * inp_out_ids = build_inp_out_ids();
+
+    for (int il = 0; il < n_layer; ++il) {
+        inpL = build_layer(il, il, inpL, inp_pos, inp_attn, inp_out_ids, il == n_layer - 1);
+    }
 
-    cur = build_norm(cur, model.output_norm, NULL, LLM_NORM_RMS, -1);
+    ggml_tensor * cur = build_norm(inpL, model.output_norm, NULL, LLM_NORM_RMS, -1);
 
     cb(cur, "result_norm", -1);
     res->t_embd = cur;
diff --git a/src/models/models.h b/src/models/models.h
index 128722e..e122d8e 100644
--- a/src/models/models.h
+++ b/src/models/models.h
@@ -2234,8 +2234,55 @@ struct llama_model_bailingmoe2 : public llama_model_base {
     void load_arch_hparams(llama_model_loader & ml) override;
     void load_arch_tensors(llama_model_loader & ml) override;
 
+    virtual int n_layer_phys() const { return hparams.n_layer(); }
+
+    enum { LOOP_CTRL_ATTN, LOOP_CTRL_FFN, LOOP_CTRL_COUNT };
+
+    struct loop_layer {
+        ggml_tensor * msg_query = nullptr;
+        ggml_tensor * ctrl_down[LOOP_CTRL_COUNT]   = {};
+        ggml_tensor * ctrl_gain[LOOP_CTRL_COUNT]   = {};
+        ggml_tensor * ctrl_forget[LOOP_CTRL_COUNT] = {};
+    };
+
     struct graph : public llm_graph_context {
         graph(const llm_graph_params & params);
+
+    protected:
+        struct no_build {};
+        graph(const llm_graph_params & params, no_build) : llm_graph_context(params) {}
+
+        ggml_tensor * mix(ggml_tensor * key_stack, ggml_tensor * raw_stack_t, ggml_tensor * query);
+        ggml_tensor * control(ggml_tensor * cur, ggml_tensor * message, const loop_layer & loop, int ctrl);
+        ggml_tensor * build_layer(
+                int il, int ip, ggml_tensor * inpL, ggml_tensor * inp_pos,
+                llm_graph_input_attn_kv * inp_attn, ggml_tensor * inp_out_ids,
+                bool apply_out_ids, ggml_tensor * messages = nullptr, const loop_layer * loop = nullptr);
+    };
+
+    std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
+};
+
+struct llama_model_bailingmoe2_loop : public llama_model_bailingmoe2 {
+    llama_model_bailingmoe2_loop(const struct llama_model_params & params) : llama_model_bailingmoe2(params) {}
+    void load_arch_hparams(llama_model_loader & ml) override;
+    void load_arch_tensors(llama_model_loader & ml) override;
+    void post_arch_tensors(llama_model_loader & ml) override;
+
+    int n_layer_phys() const override { return n_phys; }
+    uint32_t graph_nodes_per_tensor() const override { return std::max<uint32_t>(16u, 8u * n_passes); }
+    int layer_phys(int il) const;
+
+    int      n_phys     = 0;
+    uint32_t core_start = 0;
+    uint32_t core_end   = 0;
+    uint32_t n_passes   = 0;
+    uint32_t gate_rank  = 0;
+
+    std::vector<loop_layer> loop_layers;
+
+    struct graph : public llama_model_bailingmoe2::graph {
+        graph(const llm_graph_params & params);
     };
 
     std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp
index d7ecf29..d2f2210 100644
--- a/tests/test-llama-archs.cpp
+++ b/tests/test-llama-archs.cpp
@@ -333,6 +333,8 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
         n_vocab = 3072; // TODO: should be 4096, but user code cannot get `n_vocab_out` yet [TAG_LLAMA_N_VOCAB_OUT]
     } else if (arch == LLM_ARCH_HRM_TEXT) {
         n_layer = 6; // 1 layer per stack x 2 h-cycles x (2 l-cycles + 1) cache slots
+    } else if (arch == LLM_ARCH_BAILINGMOE2_LOOP) {
+        n_layer = 3;
     } else if (arch == LLM_ARCH_INKLING2 || arch == LLM_ARCH_INKLING2_LOOP) {
         n_embd  = 128;
         n_head  = 4;
@@ -780,6 +782,13 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
         ms.add_kv(LLM_KV_MUDD_TAP_INDICES,            std::vector<int32_t>({-1, -1, -1, -1, 0, 2, 1, 3}));
     }
 
+    if (arch == LLM_ARCH_BAILINGMOE2_LOOP) {
+        ms.add_kv(LLM_KV_LOOP_START,     uint32_t(1));
+        ms.add_kv(LLM_KV_LOOP_END,       uint32_t(2));
+        ms.add_kv(LLM_KV_LOOP_COUNT,     uint32_t(2));
+        ms.add_kv(LLM_KV_LOOP_GATE_RANK, uint32_t(8));
+    }
+
     if (arch == LLM_ARCH_INKLING2 || arch == LLM_ARCH_INKLING2_LOOP) {
         const bool loop = arch == LLM_ARCH_INKLING2_LOOP;
         ms.add_kv(LLM_KV_ATTENTION_RELATIVE_LENGTH,   uint32_t(4));
@@ -1198,6 +1207,7 @@ static bool moe_mandatory(const llm_arch arch) {
         case LLM_ARCH_EXAONE_MOE:
         case LLM_ARCH_BAILINGMOE:
         case LLM_ARCH_BAILINGMOE2:
+        case LLM_ARCH_BAILINGMOE2_LOOP:
         case LLM_ARCH_BAILINGMOE3:
         case LLM_ARCH_DOTS1:
         case LLM_ARCH_AFMOE:
-- 
2.43.0