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
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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
"""vLLM general plugin adding DeepSeek-V4.1 recurrent-depth looping & LoopCD-Hidden.

Activated automatically by vLLM in every engine & TP worker process via the
`vllm.general_plugins` entry point when `DSV41_LOOP_DIR` is set in the environment.

Required vLLM CLI flags when active (`DSV41_LOOP_DEPTH > 1` or `control=True`):
    --enforce-eager
    --no-swa-bounded-replay

Environment variables:
    DSV41_LOOP_DIR          Path to trainer ckpt (`ckpt/step-N` or `.../loop`)
                            or sushi export dir (`export-N`). Empty = disabled.
    DSV41_LOOP_DEPTH        Total core passes T >= 1 (1 = stock base bitwise).
    DSV41_LOOP_ZERO         "1" to zero all entry gates and LoRA-B weights
                            (for bitwise T=2(zero) == T=1 identity verification).
    DSV41_LOOP_CD_OMEGA     LoopCD-Hidden strength omega (default 0.0; 0.3 = on).
    DSV41_LOOP_CD_REF       LoopCD reference pass: "prev" (default) or "first".
    DSV41_LOOP_ANCHOR_ONLY  "1" to run `anchor_only_loop` (zero `gs` and `a[:D]`,
                            matching `exl3_mlx.loop.anchor_only_loop` op-for-op).
"""

from __future__ import annotations

import logging
import math
import os
from dataclasses import dataclass
from typing import Any

import torch
from torch import nn

from .math_ops import (
    LayerLoRA,
    LoopAdapterBundle,
    WorkspaceEntryWeights,
    entry_apply,
    grouped_wo_a_lora_delta,
    load_loop_bundle,
    loop_cd,
    lora_delta,
    pad_and_slice_column,
    pad_and_slice_row,
)

logger = logging.getLogger("dsv41_loop")

_REGISTERED = False


@dataclass(frozen=True)
class LoopRuntimeConfig:
    loop_dir: str
    depth: int
    zero: bool
    cd_omega: float
    cd_ref: str
    anchor_only: bool

    @classmethod
    def from_env(cls) -> LoopRuntimeConfig | None:
        loop_dir = os.environ.get("DSV41_LOOP_DIR", "").strip()
        if not loop_dir:
            return None
        depth = int(os.environ.get("DSV41_LOOP_DEPTH", "1"))
        if depth < 1:
            raise ValueError(f"DSV41_LOOP_DEPTH must be >= 1, got {depth}")
        zero = os.environ.get("DSV41_LOOP_ZERO", "0").strip().lower() in ("1", "true", "yes")
        cd_omega = float(os.environ.get("DSV41_LOOP_CD_OMEGA", "0.0"))
        cd_ref = os.environ.get("DSV41_LOOP_CD_REF", "prev").strip().lower()
        if cd_ref not in ("prev", "first"):
            raise ValueError(f"DSV41_LOOP_CD_REF must be 'prev' or 'first', got {cd_ref!r}")
        anchor_only = os.environ.get("DSV41_LOOP_ANCHOR_ONLY", "0").strip().lower() in (
            "1",
            "true",
            "yes",
        )
        return cls(
            loop_dir=loop_dir,
            depth=depth,
            zero=zero,
            cd_omega=cd_omega,
            cd_ref=cd_ref,
            anchor_only=anchor_only,
        )


def _tp_all_reduce(x: torch.Tensor) -> torch.Tensor:
    from vllm.distributed import tensor_model_parallel_all_reduce

    return tensor_model_parallel_all_reduce(x)


def _tp_info() -> tuple[int, int]:
    from vllm.distributed import (
        get_tensor_model_parallel_rank,
        get_tensor_model_parallel_world_size,
    )

    return get_tensor_model_parallel_rank(), get_tensor_model_parallel_world_size()


class ShardedLayerLoRA:
    """TP-sharded, device-resident LoRA weights for one adapted DeepSeek-V4.1 layer."""

    def __init__(
        self,
        raw: LayerLoRA,
        *,
        scale: float,
        tp_rank: int,
        tp_size: int,
        wq_b_local_out: int,
        wo_a_local_groups: int,
        wo_b_local_in: int,
        shexp_local_inter: int | None,
        device: torch.device,
    ) -> None:
        self.scale = float(scale)

        def mv(t: torch.Tensor) -> torch.Tensor:
            return t.to(device=device, dtype=torch.float32).contiguous()

        self.wq_a = None if raw.wq_a is None else (mv(raw.wq_a[0]), mv(raw.wq_a[1]))
        self.wkv = None if raw.wkv is None else (mv(raw.wkv[0]), mv(raw.wkv[1]))

        if raw.wq_b is not None:
            b_shard = pad_and_slice_column(raw.wq_b[1], tp_rank, tp_size, wq_b_local_out)
            self.wq_b: tuple[torch.Tensor, torch.Tensor] | None = (
                mv(raw.wq_b[0]),
                mv(b_shard),
            )
        else:
            self.wq_b = None

        if raw.wo_a is not None:
            g0 = tp_rank * wo_a_local_groups
            g1 = g0 + wo_a_local_groups
            self.wo_a: tuple[torch.Tensor, torch.Tensor] | None = (
                mv(raw.wo_a[0][g0:g1]),
                mv(raw.wo_a[1][g0:g1]),
            )
        else:
            self.wo_a = None

        if raw.wo_b is not None:
            a_shard = pad_and_slice_row(raw.wo_b[0], tp_rank, tp_size, wo_b_local_in)
            self.wo_b: tuple[torch.Tensor, torch.Tensor] | None = (
                mv(a_shard),
                mv(raw.wo_b[1]),
            )
        else:
            self.wo_b = None

        self.w1 = None
        self.w3 = None
        self.w2 = None
        if raw.has_shared_expert_lora() and shexp_local_inter is None:
            raise RuntimeError(
                "LayerLoRA contains shared_experts weights (w1/w3/w2), but "
                "shared_experts module is absent/fused (shexp_local_inter=None)."
            )
        if shexp_local_inter is not None:
            if raw.w1 is not None:
                self.w1 = (
                    mv(raw.w1[0]),
                    mv(pad_and_slice_column(raw.w1[1], tp_rank, tp_size, shexp_local_inter)),
                )
            if raw.w3 is not None:
                self.w3 = (
                    mv(raw.w3[0]),
                    mv(pad_and_slice_column(raw.w3[1], tp_rank, tp_size, shexp_local_inter)),
                )
            if raw.w2 is not None:
                self.w2 = (
                    mv(pad_and_slice_row(raw.w2[0], tp_rank, tp_size, shexp_local_inter)),
                    mv(raw.w2[1]),
                )


def _install_attention_hooks(attn: nn.Module) -> None:
    """Wrap attention projections on an adapted layer to inject stem LoRA when active."""
    if getattr(attn, "_dsv41_loop_hooks_installed", False):
        return
    attn._dsv41_loop_hooks_installed = True
    attn._dsv41_lora_active = False
    attn._dsv41_lora: ShardedLayerLoRA | None = None

    # Force BF16 qr before wq_b and BF16 inverse-rotated input before wo_a.
    attn.__dict__["_can_fuse_query_quant"] = False
    attn.wo_a.requires_unquantized_input = True
    if getattr(attn, "accepts_unnormed_unroped_query", False):
        raise NotImplementedError(
            f"{attn.prefix}: accepts_unnormed_unroped_query=True (chunk-interleaved Q) "
            "is not supported with dsv41_loop wq_b LoRA."
        )
    # P0-4 fix: fail fast at init if attention subclass lacks dsv41_o_proj attributes (e.g. SM80 Ampere).
    if not (hasattr(attn, "_einsum_recipe") and hasattr(attn, "_tma_aligned_scales")):
        raise NotImplementedError(
            f"{attn.prefix} ({type(attn).__name__}): missing _einsum_recipe/_tma_aligned_scales; "
            "dsv41_loop requires FlashMLA or FlashInfer SM120 attention."
        )

    orig_fused_wqa_wkv = attn._fused_wqa_wkv_gemm
    orig_wq_b_proj = attn._wq_b_proj
    orig_o_proj = attn._o_proj

    def hooked_fused_wqa_wkv(hidden_states: torch.Tensor) -> torch.Tensor:
        qr_kv = orig_fused_wqa_wkv(hidden_states)
        if not attn._dsv41_lora_active or attn._dsv41_lora is None:
            return qr_kv
        lora = attn._dsv41_lora
        if lora.wq_a is None and lora.wkv is None:
            return qr_kv
        out = qr_kv.clone()
        if lora.wq_a is not None:
            out[..., : attn.q_lora_rank] += lora_delta(
                hidden_states, lora.wq_a[0], lora.wq_a[1], lora.scale, out.dtype
            )
        if lora.wkv is not None:
            out[..., attn.q_lora_rank :] += lora_delta(
                hidden_states, lora.wkv[0], lora.wkv[1], lora.scale, out.dtype
            )
        return out

    def hooked_wq_b_proj(
        qr: Any,
        qr_scale: torch.Tensor | None = None,
    ) -> torch.Tensor:
        q = orig_wq_b_proj(qr, qr_scale)
        if not attn._dsv41_lora_active or attn._dsv41_lora is None:
            return q
        lora = attn._dsv41_lora
        if lora.wq_b is None:
            return q
        if not isinstance(qr, torch.Tensor):
            raise TypeError(
                f"{attn.prefix}: expected BF16 tensor qr for wq_b LoRA, got {type(qr)}"
            )
        return q + lora_delta(qr, lora.wq_b[0], lora.wq_b[1], lora.scale, q.dtype)

    def hooked_o_proj(attn_out: Any, positions: torch.Tensor) -> torch.Tensor:
        if not attn._dsv41_lora_active or attn._dsv41_lora is None:
            return orig_o_proj(attn_out, positions)
        lora = attn._dsv41_lora
        if lora.wo_a is None and lora.wo_b is None:
            return orig_o_proj(attn_out, positions)
        if not isinstance(attn_out, torch.Tensor):
            raise TypeError(
                f"{attn.prefix}: expected unquantized tensor attn_out for wo_a/wo_b LoRA, "
                f"got {type(attn_out)}"
            )
        o = attn_out[:, : attn.n_local_heads, :]
        cos_sin_cache = attn.rotary_emb.cos_sin_cache
        heads_per_group = attn.n_local_heads // attn.n_local_groups
        z = attn.wo_a.grouped_forward(
            o,
            positions,
            cos_sin_cache,
            n_groups=attn.n_local_groups,
            heads_per_group=heads_per_group,
            nope_dim=attn.nope_head_dim,
            rope_dim=attn.rope_head_dim,
            o_lora_rank=attn.o_lora_rank,
            einsum_recipe=attn._einsum_recipe,
            tma_aligned_scales=attn._tma_aligned_scales,
        )
        if lora.wo_a is not None:
            x_groups = attn.wo_a.grouped_input(
                o,
                positions,
                cos_sin_cache,
                n_groups=attn.n_local_groups,
                heads_per_group=heads_per_group,
                nope_dim=attn.nope_head_dim,
                rope_dim=attn.rope_head_dim,
            )
            z = z + grouped_wo_a_lora_delta(
                x_groups, lora.wo_a[0], lora.wo_a[1], lora.scale, z.dtype
            )
        z_flat = z.flatten(1)
        out = attn._wo_b_proj(z_flat)
        if lora.wo_b is not None:
            d = lora_delta(z_flat, lora.wo_b[0], lora.wo_b[1], lora.scale, out.dtype)
            if getattr(attn.wo_b, "reduce_results", True):
                d = _tp_all_reduce(d)
            out = out + d
        return out

    attn._fused_wqa_wkv_gemm = hooked_fused_wqa_wkv
    attn._wq_b_proj = hooked_wq_b_proj
    attn._o_proj = hooked_o_proj


def _install_shared_expert_hooks(layer: nn.Module, *, expect_shared_lora: bool = False) -> None:
    """Wrap `layer.ffn.shared_experts` (DeepseekV4MLP) for w1/w3/w2 LoRA."""
    # P0-5 fix: check `has_fused_shared_experts` BEFORE checking `shexp is None`!
    experts = getattr(layer.ffn, "experts", None)
    if getattr(experts, "has_fused_shared_experts", False):
        raise NotImplementedError(
            "dsv41_loop requires unfused shared_experts (has_fused_shared_experts=False) "
            "on adapted layers."
        )
    shexp = getattr(layer.ffn, "shared_experts", None)
    if shexp is None:
        if expect_shared_lora:
            raise RuntimeError(
                "dsv41_loop adapter has shared_experts LoRA weights, but layer.ffn.shared_experts is None."
            )
        return
    if getattr(shexp, "_dsv41_loop_hooks_installed", False):
        return
    shexp._dsv41_loop_hooks_installed = True
    shexp._dsv41_lora_active = False
    shexp._dsv41_lora: ShardedLayerLoRA | None = None

    orig_forward = shexp.forward

    def hooked_forward(x: torch.Tensor) -> torch.Tensor:
        if not shexp._dsv41_lora_active or shexp._dsv41_lora is None:
            return orig_forward(x)
        lora = shexp._dsv41_lora
        if lora.w1 is None and lora.w3 is None and lora.w2 is None:
            return orig_forward(x)
        gate_up, _ = shexp.gate_up_proj(x)
        if lora.w1 is not None or lora.w3 is not None:
            inter_local = gate_up.shape[-1] // 2
            gate_up = gate_up.clone()
            if lora.w1 is not None:
                gate_up[..., :inter_local] += lora_delta(
                    x, lora.w1[0], lora.w1[1], lora.scale, gate_up.dtype
                )
            if lora.w3 is not None:
                gate_up[..., inter_local:] += lora_delta(
                    x, lora.w3[0], lora.w3[1], lora.scale, gate_up.dtype
                )
        act = shexp.act_fn(gate_up)
        out, _ = shexp.down_proj(act)
        if lora.w2 is not None:
            d = lora_delta(act, lora.w2[0], lora.w2[1], lora.scale, out.dtype)
            if getattr(shexp.down_proj, "reduce_results", False):
                d = _tp_all_reduce(d)
            out = out + d
        return out

    shexp.forward = hooked_forward


def _register_pass_swa_caches(
    attn: nn.Module,
    cache_config: Any,
    num_passes: int,
) -> None:
    """Register per-pass 128-token `DeepseekV4SWACache` modules (Inkling 2 pattern)."""
    from vllm.models.deepseek_v41.attention import DeepseekV4SWACache

    attn._base_swa_cache_layer = attn.swa_cache_layer
    if num_passes <= 1:
        attn.pass_swa_caches = nn.ModuleList()
        return
    packed_stride_align = (
        math.lcm(attn.swa_bytes_per_token, attn.compressed_bytes_per_token)
        if attn.kv_mxfp8
        else None
    )
    attn.pass_swa_caches = nn.ModuleList(
        [
            DeepseekV4SWACache(
                head_dim=attn.head_dim,
                window_size=attn.window_size,
                dtype=attn.kv_cache_torch_dtype,
                prefix=f"{attn.prefix}.swa_cache.pass{p}",
                cache_config=cache_config,
                backend_cls=attn.swa_backend_cls,
                block_size=attn.swa_cache_layer.block_size,
                packed_bytes_per_token=attn.swa_bytes_per_token,
                packed_page_alignment=attn.kv_page_alignment,
                packed_block_stride_alignment=packed_stride_align,
                bounded_replay=False,
            )
            for p in range(1, num_passes)
        ]
    )


def _set_layer_lora_active(layer: nn.Module, active: bool) -> None:
    if hasattr(layer.attn, "_dsv41_lora_active"):
        layer.attn._dsv41_lora_active = active
    shexp = getattr(layer.ffn, "shared_experts", None)
    if shexp is not None and hasattr(shexp, "_dsv41_lora_active"):
        shexp._dsv41_lora_active = active


def _set_layer_swa_pass(layer: nn.Module, pass_idx: int) -> None:
    attn = layer.attn
    if pass_idx == 0:
        attn.swa_cache_layer = attn._base_swa_cache_layer
    else:
        attn.swa_cache_layer = attn.pass_swa_caches[pass_idx - 1]


def _materialize_mhc_post(
    hidden_states: Any,
    residual: torch.Tensor,
    post_mix: torch.Tensor,
    res_mix: torch.Tensor,
    *,
    fuse_mhc_all_reduce: bool,
    boundary_all_reduce_fn: Any,
    mhc_post_fn: Any,
) -> torch.Tensor:
    """Fold delayed FFN output into the 4-stream hyper-connection state `[T, hc, D]`."""
    if not isinstance(hidden_states, torch.Tensor):
        raise TypeError(
            f"boundary layer produced unfinalized MoEOutput ({type(hidden_states)}); "
            "defer_finalize must be disabled on loop boundary layers."
        )
    if fuse_mhc_all_reduce:
        hidden_states = boundary_all_reduce_fn(hidden_states)
    return mhc_post_fn(hidden_states, residual, post_mix, res_mix)


def run_looped_layers(
    model: Any,
    *,
    hidden_states: torch.Tensor,
    positions: torch.Tensor,
    input_ids: torch.Tensor | None,
    pre_mix: torch.Tensor | None,
    post_mix: torch.Tensor | None,
    res_mix: torch.Tensor | None,
    residual: torch.Tensor | None,
    aux_hidden_by_layer: dict[int, torch.Tensor],
    engram_hashes: torch.Tensor | None,
    engram_mask: torch.Tensor | None,
    cfg: LoopRuntimeConfig,
    bundle: LoopAdapterBundle,
    device_entries: dict[int, WorkspaceEntryWeights],
    boundary_all_reduce_fn: Any,
    mhc_post_fn: Any,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
    """Execute prelude -> T core passes (with WorkspaceEntry & per-pass SWA) -> LoopCD -> coda.

    Separated from vLLM's `DeepseekV4Model.forward` so it can be unit-tested directly
    without requiring CUDA kernels.
    """
    core_start = bundle.core_start
    core_end = bundle.core_end
    start_layer = model.start_layer
    end_layer = model.end_layer

    if start_layer > core_start or end_layer < core_end:
        raise NotImplementedError(
            f"Pipeline parallelism splitting the loop core [{core_start}, {core_end}) "
            f"across ranks [{start_layer}, {end_layer}) is not supported."
        )

    # 1. Prelude: layers [start_layer, core_start), never adapted.
    hidden_states, residual, post_mix, res_mix, pre_mix = model._run_layers(
        range(start_layer, core_start),
        hidden_states,
        positions,
        input_ids,
        pre_mix,
        post_mix,
        res_mix,
        residual,
        aux_hidden_by_layer,
        engram_hashes,
        engram_mask,
    )

    # Materialize anchor 4-stream state [T, hc, D] and save anchor pre_mix (pre_lag).
    anchor_h = _materialize_mhc_post(
        hidden_states,
        residual,
        post_mix,
        res_mix,
        fuse_mhc_all_reduce=getattr(model, "fuse_mhc_all_reduce", False),
        boundary_all_reduce_fn=boundary_all_reduce_fn,
        mhc_post_fn=mhc_post_fn,
    )
    anchor_pre = pre_mix

    # P1-4 fix: preserve topk_indices_buffer across passes if core_start is not an index source.
    saved_topk: torch.Tensor | None = None
    core_start_attn = model.layers[core_start].attn
    topk_buf = getattr(model, "topk_indices_buffer", None)
    if (
        cfg.depth > 1
        and topk_buf is not None
        and not getattr(core_start_attn, "is_index_source", True)
    ):
        saved_topk = topk_buf[: positions.shape[0]].clone()

    # 2. Core passes p = 0 .. depth - 1 over layers [core_start, core_end).
    s_first: torch.Tensor | None = None
    s_prev: torch.Tensor | None = None
    s_curr: torch.Tensor | None = None
    s_pre_curr: torch.Tensor | None = None

    try:
        for p in range(cfg.depth):
            if p > 0 and saved_topk is not None and topk_buf is not None:
                topk_buf[: positions.shape[0]].copy_(saved_topk)

            if p == 0:
                # P1-5 fix: clone anchor_h on pass 0 when looping so in-place mHC ops cannot corrupt it.
                pass_in = anchor_h.clone() if cfg.depth > 1 else anchor_h
            else:
                slot = min(p, bundle.passes - 1)
                ew = device_entries[slot]
                # P1-1 fix: use precomputed host bool `ew.is_zero` (zero GPU->CPU syncs!).
                if ew.is_zero:
                    pass_in = anchor_h.clone() if p + 1 < cfg.depth else anchor_h
                else:
                    assert s_curr is not None
                    pass_in = entry_apply(
                        anchor_h,
                        s_curr,
                        ew.gs,
                        ew.gm,
                        ew.a,
                        ew.b,
                        zero_short_circuit=False,
                    )

            # P1-3 fix: honor bundle.control at depth=1 (p=0) too!
            lora_on = (p >= 1) or bundle.control
            for lid in range(core_start, core_end):
                _set_layer_swa_pass(model.layers[lid], p)
                _set_layer_lora_active(model.layers[lid], lora_on)

            p_x, p_res, p_post, p_rmix, p_pre = model._run_layers(
                range(core_start, core_end),
                pass_in,
                positions,
                input_ids,
                anchor_pre,
                None,
                None,
                None,
                aux_hidden_by_layer,
                engram_hashes,
                engram_mask,
            )
            s_next = _materialize_mhc_post(
                p_x,
                p_res,
                p_post,
                p_rmix,
                fuse_mhc_all_reduce=getattr(model, "fuse_mhc_all_reduce", False),
                boundary_all_reduce_fn=boundary_all_reduce_fn,
                mhc_post_fn=mhc_post_fn,
            )
            if p == 0:
                s_first = s_next
            s_prev = s_curr
            s_curr = s_next
            s_pre_curr = p_pre
    finally:
        for lid in range(core_start, core_end):
            _set_layer_swa_pass(model.layers[lid], 0)
            _set_layer_lora_active(model.layers[lid], False)

    assert s_curr is not None and s_pre_curr is not None

    # 3. Optional LoopCD-Hidden contrast before coda layer `core_end` (36).
    coda_in = s_curr
    if cfg.depth >= 2 and cfg.cd_omega != 0.0:
        ref = s_prev if cfg.cd_ref == "prev" else s_first
        assert ref is not None
        coda_in = loop_cd(s_curr, ref, cfg.cd_omega)

    # 4. Coda: layers [core_end, end_layer), LoRA active iff T > 1 or control.
    coda_lora_on = cfg.depth > 1 or bundle.control
    try:
        for lid in range(core_end, end_layer):
            _set_layer_lora_active(model.layers[lid], coda_lora_on)
        return model._run_layers(
            range(core_end, end_layer),
            coda_in,
            positions,
            input_ids,
            s_pre_curr,
            None,
            None,
            None,
            aux_hidden_by_layer,
            engram_hashes,
            engram_mask,
        )
    finally:
        for lid in range(core_end, end_layer):
            _set_layer_lora_active(model.layers[lid], False)


def register() -> None:
    """vLLM general plugin entry point."""
    global _REGISTERED
    if _REGISTERED:
        return
    cfg = LoopRuntimeConfig.from_env()
    if cfg is None:
        return

    # P2-2 fix: guard NVIDIA CUDA import for non-CUDA/CPU discovery processes.
    from vllm.platforms import current_platform

    if not current_platform.is_cuda():
        logger.warning("dsv41_loop: non-CUDA platform detected; skipping NVIDIA model patch.")
        return

    _REGISTERED = True
    bundle = load_loop_bundle(cfg.loop_dir, zero=cfg.zero)
    logger.info(
        "dsv41_loop enabled: dir=%s depth=%d zero=%s cd_omega=%.3f cd_ref=%s "
        "anchor_only=%s core=[%d,%d) trained_passes=%d scale=%.3f control=%s",
        cfg.loop_dir,
        cfg.depth,
        cfg.zero,
        cfg.cd_omega,
        cfg.cd_ref,
        cfg.anchor_only,
        bundle.core_start,
        bundle.core_end,
        bundle.passes,
        bundle.lora_scale,
        bundle.control,
    )

    # If depth == 1 and not control, model runs bitwise stock; no hooks needed.
    if cfg.depth == 1 and not bundle.control:
        logger.info("dsv41_loop depth=1 (stock mode): skipping model patching for bitwise identity.")
        return

    # P0-5 fix: prevent MegaMoE from fusing shared_experts away before model init.
    import vllm.envs as vllm_envs

    vllm_envs.VLLM_DISABLE_DSV4_MEGAMOE_SHARED_EXPERT_FUSION = True

    import vllm.models.deepseek_v41.nvidia.model as dsv41_mod
    from vllm.model_executor.models.utils import extract_layer_index

    orig_model_init = dsv41_mod.DeepseekV4Model.__init__
    orig_model_forward = dsv41_mod.DeepseekV4Model.forward
    orig_model_load_weights = dsv41_mod.DeepseekV4Model.load_weights
    orig_causal_init = dsv41_mod.DeepseekV41LLMForCausalLM.__init__
    orig_defer_finalize = dsv41_mod.DeepseekV4MoE.defer_finalize
    orig_select_attn_cls = dsv41_mod._select_dsv4_attn_cls

    # Disable sequence parallel for looped execution (matches Inkling2LoopModel).
    dsv41_mod._use_sequence_parallel = lambda _vllm_config: False

    # P0-3 fix: disable specialized_decode at module level BEFORE lazy build!
    if hasattr(dsv41_mod, "specialized_decode_config"):
        dsv41_mod.specialized_decode_config = lambda _vllm_config: None
    if hasattr(dsv41_mod, "records_decode_metadata"):
        dsv41_mod.records_decode_metadata = lambda _vllm_config: False

    # P0-2 fix: prevent `defer_finalize()` from mutating `moe_config` on loop boundary layers!
    boundary_layers = {bundle.core_start - 1, bundle.core_end - 1}

    def patched_defer_finalize(self: Any) -> None:
        if extract_layer_index(self.prefix) in boundary_layers:
            return
        orig_defer_finalize(self)

    dsv41_mod.DeepseekV4MoE.defer_finalize = patched_defer_finalize

    # P0-4 fix: ensure attention subclass uses standard un-interleaved Q and dsv41_o_proj,
    # including GB10 DGX Spark (SM121 compute capability 12.1 -> DeepseekV4FlashInferSM120Attention)!
    def patched_select_attn_cls(vllm_config: Any) -> Any:
        cls = orig_select_attn_cls(vllm_config)
        if torch.cuda.is_available() and torch.cuda.get_device_capability()[0] == 12:
            sm120_cls = getattr(dsv41_mod, "DeepseekV4FlashInferSM120Attention", None)
            if sm120_cls is not None and cls is not sm120_cls:
                logger.info(
                    "dsv41_loop: SM12x Blackwell detected; selecting %s instead of %s.",
                    sm120_cls.__name__,
                    cls.__name__,
                )
                return sm120_cls
        if cls.__name__ in ("DeepseekV4MegaAttnAttention", "DeepseekV41HopperAttention"):
            logger.info(
                "dsv41_loop: overriding %s -> DeepseekV4FlashMLAAttention for LoRA/loop compatibility.",
                cls.__name__,
            )
            return dsv41_mod.DeepseekV4FlashMLAAttention
        return cls

    dsv41_mod._select_dsv4_attn_cls = patched_select_attn_cls

    def patched_causal_init(self: Any, *args: Any, **kwargs: Any) -> None:
        orig_causal_init(self, *args, **kwargs)
        self.specialized_decode_config = None
        self.specialized_decode = None
        self.records_decode_metadata = False

    def patched_model_init(self: Any, *, vllm_config: Any, prefix: str = "") -> None:
        # P2-4 fix: clear message covering depth > 1 or control=True.
        if not vllm_config.model_config.enforce_eager:
            raise RuntimeError(
                "dsv41_loop requires --enforce-eager when DSV41_LOOP_DEPTH > 1 or control=True "
                "(CUDA graph capture would freeze per-pass SWA cache and LoRA hook state)."
            )
        # P0-6 fix: fail fast instead of silently mutating Worker-only cache_config!
        if getattr(vllm_config.cache_config, "swa_bounded_replay", False):
            raise RuntimeError(
                "dsv41_loop requires --no-swa-bounded-replay on the CLI so EngineCore, "
                "Scheduler, and all Workers agree on SWA KV cache layout."
            )

        orig_model_init(self, vllm_config=vllm_config, prefix=prefix)
        assert self.decoder_replay_layers is None, "decoder_replay_layers must be None for dsv41_loop"

        # P2-1 fix: fail fast before loading 300+ GB weights if PP splits the loop core.
        if self.start_layer > bundle.core_start or self.end_layer < bundle.core_end:
            raise NotImplementedError(
                f"dsv41_loop does not support pipeline parallelism splitting loop core "
                f"[{bundle.core_start}, {bundle.core_end}) across rank layers "
                f"[{self.start_layer}, {self.end_layer})."
            )

        # P2-5 fix: guard EAGLE3 aux capture on boundaries.
        aux_conflict = set(getattr(self, "aux_hidden_state_layers", ())) & {
            bundle.core_start,
            bundle.core_end,
        }
        if aux_conflict:
            raise NotImplementedError(
                f"dsv41_loop does not support aux_hidden_state_layers on loop boundaries: {aux_conflict}"
            )

        # P0-5 fix: fail fast if native MegaMoE is enabled with TP > 1 (needs sequence parallel).
        _, tp_size = _tp_info()
        sample_ffn = self.layers[bundle.core_start].ffn
        if getattr(sample_ffn, "use_native_mega_moe", False) and tp_size > 1:
            raise NotImplementedError(
                "dsv41_loop disables sequence parallel, which is incompatible with native MegaMoE at TP > 1."
            )

        # P1-4 fix: assert candidate_source_layer < core_start so candidate blocks stay immutable across passes.
        cand_src = getattr(self.layers[bundle.core_start].attn, "candidate_source_layer", -1)
        if cand_src >= bundle.core_start:
            raise NotImplementedError(
                f"dsv41_loop requires candidate_source_layer ({cand_src}) < core_start ({bundle.core_start})."
            )

        # Backup guard on boundary layers' defers_finalize
        for b_lid in boundary_layers:
            if self.start_layer <= b_lid < self.end_layer:
                moe = self.layers[b_lid].ffn
                moe.defers_finalize = lambda _n: False  # type: ignore[method-assign]

        # Register per-pass SWA caches on core layers and install LoRA hooks on core + coda.
        for lid in range(bundle.core_start, bundle.core_end):
            _register_pass_swa_caches(
                self.layers[lid].attn, vllm_config.cache_config, cfg.depth
            )
            _install_attention_hooks(self.layers[lid].attn)
            raw_core = bundle.core_lora.get(lid)
            _install_shared_expert_hooks(
                self.layers[lid],
                expect_shared_lora=bool(raw_core and raw_core.has_shared_expert_lora()),
            )

        for lid in range(max(bundle.core_end, self.start_layer), self.end_layer):
            if lid in bundle.coda_lora:
                _install_attention_hooks(self.layers[lid].attn)
                raw_coda = bundle.coda_lora[lid]
                _install_shared_expert_hooks(
                    self.layers[lid],
                    expect_shared_lora=raw_coda.has_shared_expert_lora(),
                )

        self._dsv41_loop_cfg = cfg
        self._dsv41_loop_bundle = bundle
        self._dsv41_loop_entries: dict[int, WorkspaceEntryWeights] = {}
        self._dsv41_loop_weights_bound = False

    def _bind_loop_weights(self: Any) -> None:
        if self._dsv41_loop_weights_bound:
            return
        tp_rank, tp_size = _tp_info()
        sample_layer = self.layers[bundle.core_start]
        device = sample_layer.attn_norm.weight.device

        # P1-2 fix: apply exact `anchor_only_loop` transform (gs=0, a[:D]=0) at bind time!
        self._dsv41_loop_entries = {
            q: (ew.anchor_only() if cfg.anchor_only else ew).to(device)
            for q, ew in bundle.entries.items()
        }

        def bind_layer(lid: int, raw: LayerLoRA) -> None:
            layer = self.layers[lid]
            attn = layer.attn
            wq_b_local_out = attn.n_local_heads * attn.head_dim
            wo_a_local_groups = attn.n_local_groups
            wo_b_local_in = attn.n_local_groups * attn.o_lora_rank
            shexp = getattr(layer.ffn, "shared_experts", None)
            shexp_local_inter = (
                shexp.gate_up_proj.output_size_per_partition // 2
                if shexp is not None
                else None
            )
            sharded = ShardedLayerLoRA(
                raw,
                scale=bundle.lora_scale,
                tp_rank=tp_rank,
                tp_size=tp_size,
                wq_b_local_out=wq_b_local_out,
                wo_a_local_groups=wo_a_local_groups,
                wo_b_local_in=wo_b_local_in,
                shexp_local_inter=shexp_local_inter,
                device=device,
            )
            attn._dsv41_lora = sharded
            if shexp is not None:
                shexp._dsv41_lora = sharded

        for lid, raw in bundle.core_lora.items():
            if self.start_layer <= lid < self.end_layer:
                bind_layer(lid, raw)
        for lid, raw in bundle.coda_lora.items():
            if self.start_layer <= lid < self.end_layer:
                bind_layer(lid, raw)

        self._dsv41_loop_weights_bound = True
        msg = (
            f"dsv41_loop: bound weights on tp_rank={tp_rank}/{tp_size} device={device} "
            f"(depth={cfg.depth} zero={cfg.zero} cd_omega={cfg.cd_omega:.3f} entries={len(self._dsv41_loop_entries)} "
            f"core={len(bundle.core_lora)} coda={len(bundle.coda_lora)} anchor_only={cfg.anchor_only})"
        )
        logger.info("%s", msg)
        print(f"[{msg}]", flush=True)

    def patched_load_weights(self: Any, weights: Any) -> set[str]:
        loaded = orig_model_load_weights(self, weights)
        _bind_loop_weights(self)
        return loaded

    def patched_model_forward(
        self: Any,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
        intermediate_tensors: Any,
        inputs_embeds: torch.Tensor | None = None,
        lookback_token_ids: torch.Tensor | None = None,
        decode_step: Any = None,
    ) -> Any:
        if decode_step is not None:
            raise RuntimeError("dsv41_loop: decode_step must be None (specialized_decode disabled)")
        if not self._dsv41_loop_weights_bound:
            _bind_loop_weights(self)

        orig_run_layers = self._run_layers

        def looped_run_layers(
            layer_ids: range,
            hidden_states: Any,
            pos: torch.Tensor,
            in_ids: torch.Tensor | None,
            pre_mix: torch.Tensor | None,
            post_mix: torch.Tensor | None,
            res_mix: torch.Tensor | None,
            residual: torch.Tensor | None,
            aux_hidden_by_layer: dict[int, torch.Tensor],
            engram_hashes: torch.Tensor | None = None,
            engram_mask: torch.Tensor | None = None,
        ) -> Any:
            if layer_ids.start == self.start_layer and layer_ids.stop == self.end_layer:
                self._run_layers = orig_run_layers
                try:
                    return run_looped_layers(
                        self,
                        hidden_states=hidden_states,
                        positions=pos,
                        input_ids=in_ids,
                        pre_mix=pre_mix,
                        post_mix=post_mix,
                        res_mix=res_mix,
                        residual=residual,
                        aux_hidden_by_layer=aux_hidden_by_layer,
                        engram_hashes=engram_hashes,
                        engram_mask=engram_mask,
                        cfg=self._dsv41_loop_cfg,
                        bundle=self._dsv41_loop_bundle,
                        device_entries=self._dsv41_loop_entries,
                        boundary_all_reduce_fn=dsv41_mod.boundary_all_reduce,
                        mhc_post_fn=dsv41_mod.mhc_post_tilelang,
                    )
                finally:
                    self._run_layers = orig_run_layers
            return orig_run_layers(
                layer_ids,
                hidden_states,
                pos,
                in_ids,
                pre_mix,
                post_mix,
                res_mix,
                residual,
                aux_hidden_by_layer,
                engram_hashes,
                engram_mask,
            )

        self._run_layers = looped_run_layers
        try:
            return orig_model_forward(
                self,
                input_ids,
                positions,
                intermediate_tensors,
                inputs_embeds=inputs_embeds,
                lookback_token_ids=lookback_token_ids,
                decode_step=None,
            )
        finally:
            self._run_layers = orig_run_layers

    dsv41_mod.DeepseekV41LLMForCausalLM.__init__ = patched_causal_init
    dsv41_mod.DeepseekV4Model.__init__ = patched_model_init
    dsv41_mod.DeepseekV4Model.load_weights = patched_load_weights
    dsv41_mod.DeepseekV4Model.forward = patched_model_forward