File size: 34,972 Bytes
2bfd19c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
# Copyright (c) 2025 SandAI. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
MotionCache implementation: Motion-aware token-wise cache reuse + KV compression.

This module provides MotionCache (Xu et al., 2026), which extends FlowCache with:
- Phase 1: chunk-wise binary reuse for structural warm-up (K steps)
- Phase 2: motion-weighted token accumulation and selective residual reuse
- KVCacheCompressor: Dynamic KV cache compression for memory efficiency
"""

import argparse
import gc
import os
import sys
import torch
from types import MethodType

from inference.pipeline import MagiPipeline
from inference.pipeline.video_generate import SampleTransport, find_dit_model
from inference.pipeline.cache import KVCacheCompressor
from inference.pipeline.cache.motioncache import MotionWiseCache
from inference.pipeline.cache.sparse_utils import (
    build_sparse_meta_args,
    latent_mask_to_patch_mask,
    patch_mask_to_flat_indices,
    sparse_gather_sequence,
    sparse_scatter_sequence,
)
from inference.pipeline.cache.utils import (
    generate_dynamic_kv_range,
    get_embedding_and_meta_with_chunk_info,
)
from inference.pipeline.kvcompress import replace_magi
from inference.pipeline.kvcompress.utils import ChunkKVRangeTracker


def setup_motioncache(
    rel_l1_thresh: float = 0.015,
    warmup_steps: int = 5,
    phase1_steps: int = 9,
    alpha: float = 0.5,
    discard_nearly_clean_chunk: bool = False,
    log: bool = False,
    total_cache_chunk_nums: int = 5,
    compress_kv_cache: bool = True,
    metric_stats_path: str = None,
):
    """
    Set up MotionCache with coarse-to-fine reuse and KV compression.

    Args:
        rel_l1_thresh: Token accumulator threshold (tau)
        warmup_steps: Global warm-up steps with reuse disabled (m)
        phase1_steps: Chunk-wise phase duration (K)
        alpha: Soft-mapping floor for static tokens
        discard_nearly_clean_chunk: Whether to skip nearly-clean chunk
        log: Whether to log reuse decisions
        total_cache_chunk_nums: Total number of chunks to cache
        compress_kv_cache: Whether to enable KV cache compression
    """
    SampleTransport.cache_reuse_manager = MotionWiseCache(
        rel_l1_thresh=rel_l1_thresh,
        warmup_steps=warmup_steps,
        phase1_steps=phase1_steps,
        alpha=alpha,
        discard_nearly_clean_chunk=discard_nearly_clean_chunk,
        log=log,
        metric_stats_path=metric_stats_path,
    )

    SampleTransport.kv_compress_manager = None

    SampleTransport.forward_velocity = motioncache_forward_velocity
    SampleTransport.integrate_velocity = motioncache_integrate_velocity
    SampleTransport.total_cache_chunk_nums = total_cache_chunk_nums
    SampleTransport.compress_kv_cache = compress_kv_cache


def motioncache_forward_velocity(self, infer_idx: int, cur_denoise_step: int) -> dict:
    """
    Forward pass with per-chunk TeaCache and KV compression.

    Args:
        self: SampleTransport instance
        infer_idx: Inference index
        cur_denoise_step: Current denoising step

    Returns:
        Dictionary mapping chunk_id to velocity tensor
    """
    # Get cache from class attribute
    cache = SampleTransport.cache_reuse_manager

    # 1. Get current work status
    x = self.xs[infer_idx]
    transport_input = self.transport_inputs[infer_idx]
    batch_size, chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx)

    # 2. Initialize KV cache tracking if needed
    if hasattr(self, 'compress_kv_cache') and self.compress_kv_cache:
        total_cache_len = self.total_cache_chunk_nums * (
            self.chunk_width *
            (transport_input.latent_size[3] // self.model_config.patch_size) *
            (transport_input.latent_size[4] // self.model_config.patch_size)
        )

        if not hasattr(self.inference_params[infer_idx], 'kv_chunk_tracker'):
            self.inference_params[infer_idx].kv_chunk_tracker = ChunkKVRangeTracker(
                total_cache_len=total_cache_len,
                clip_token_nums=chunk_token_nums,
                max_batch_size=1
            )

        if not hasattr(self, 'chunk_query_states'):
            self.chunk_query_states = {}

    # 3. Initialize chunk state
    cache.initialize_chunk_state(transport_input.chunk_num)

    # 4. Extract denoising status
    (denoise_step_per_stage, denoise_stage, denoise_idx), (
        chunk_offset,
        chunk_start,
        chunk_end,
        t_start,
        t_end,
    ) = self.generate_denoise_status_and_sequences(infer_idx, cur_denoise_step)
    self.current_chunk_offset = chunk_offset

    # 5. Prepare model kwargs
    model_kwargs = dict(
        chunk_width=self.chunk_width,
        fwd_extra_1st_chunk=False,
        num_steps=transport_input.num_steps
    )
    if hasattr(self, "debug"):
        model_kwargs["debug"] = self.debug
    model_kwargs.update({
        "denoise_step_per_stage": denoise_step_per_stage,
        "denoise_stage": denoise_stage,
        "denoise_idx": denoise_idx,
        "chunk_num": transport_input.chunk_num
    })

    if hasattr(self, 'compress_kv_cache') and self.compress_kv_cache:
        model_kwargs.update({
            "compress_kv": True,
            "total_cache_len": total_cache_len
        })
    else:
        model_kwargs["save_kvcache_every_forward"] = True
        
    if chunk_offset > 0 and cur_denoise_step == 0:
        self.extract_prefix_video_feature(
            infer_idx, transport_input.prefix_video, transport_input.y, chunk_offset, model_kwargs
        )

    # 6. Prepare inputs
    x_chunk = x[:, :, chunk_start * self.chunk_width : chunk_end * self.chunk_width].clone()
    y_chunk = transport_input.y[:, chunk_start:chunk_end]
    mask_chunk = transport_input.emb_masks[:, chunk_start:chunk_end]
    model_kwargs.update({
        "slice_point": chunk_start,
        "range_num": chunk_end,
        "denoising_range_num": chunk_end - chunk_start
    })
    model_kwargs["chunk_token_nums"] = chunk_token_nums

    # 7. Prepare timesteps
    denoise_step_of_each_chunk = self.get_denoise_step_of_each_chunk(
        infer_idx, denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=False
    )
    t = self.get_timestep(
        self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=False
    )
    t = t.unsqueeze(0).repeat(x_chunk.size(0), 1)

    # 8. Generate KV range
    kv_range = self.generate_kvrange_for_denoising_video(
        infer_idx=infer_idx,
        slice_point=model_kwargs["slice_point"],
        denoising_range_num=model_kwargs["denoising_range_num"],
        denoise_step_of_each_chunk=denoise_step_of_each_chunk,
    )

    # 9. Pad prefix video if needed
    if transport_input.prefix_video is not None:
        x_chunk, t = self.try_pad_prefix_video(
            infer_idx, x_chunk, t, prefix_video_start=model_kwargs["slice_point"] * self.chunk_width
        )

    # 10. Model forward
    forward_fn = find_dit_model(self.model).forward_dispatcher
    nearly_clean_chunk_t = t[0, int(model_kwargs["fwd_extra_1st_chunk"])].item()
    model_kwargs["distill_nearly_clean_chunk"] = (
        nearly_clean_chunk_t > self.engine_config.distill_nearly_clean_chunk_threshold
    )
    model_kwargs["distill_interval"] = self.time_interval[infer_idx][denoise_idx]
    model_kwargs["total_num_steps"] = self.total_forward_step(infer_idx)

    # Initialize step counter
    cache.set_total_steps(model_kwargs["total_num_steps"])

    # Setup monkey-patched model forward
    model = find_dit_model(self.model)
    model.forward = MethodType(_create_motioncache_model_forward_fn(cache, self, infer_idx), model)
    model.get_embedding_and_meta = MethodType(_new_get_embedding_and_meta, model)

    velocity = forward_fn(
        x=x_chunk,
        timestep=t,
        y=y_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1),
        mask=mask_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1),
        kv_range=kv_range,
        inference_params=self.inference_params[infer_idx],
        **model_kwargs,
    )

    self.x_chunks[infer_idx] = x_chunk
    self.velocities[infer_idx] = velocity
    return velocity


def _create_motioncache_model_forward_fn(cache: MotionWiseCache, transport, infer_idx: int):
    """
    Create a model forward function with MotionCache chunk/token reuse logic.
    """
    @torch.no_grad()
    def model_forward(
        model_self,
        x,
        t,
        y,
        caption_dropout_mask=None,
        xattn_mask=None,
        kv_range=None,
        inference_params=None,
        **kwargs,
    ) -> dict:
        raw_x = x.clone()

        # 1. Compute feature metrics per chunk
        # Following source code: compute metric_x first, handle slicing, then split
        metric_chunks, num_chunks = cache.compute_feature_metric(
            x=x,
            x_embedder=model_self.x_embedder,
            x_rescale_factor=model_self.model_config.x_rescale_factor,
            half_channel_vae=model_self.model_config.half_channel_vae,
            chunk_token_nums=kwargs["chunk_token_nums"],
            params_dtype=model_self.model_config.params_dtype,
            offset=kwargs['slice_point'],
            fwd_extra_1st_chunk=kwargs.get("fwd_extra_1st_chunk", False),
            distill_nearly_clean_chunk=kwargs.get("distill_nearly_clean_chunk", False)
        )

        # 2. Update kwargs
        cache.total_num_steps = kwargs['total_num_steps']
        denoise_step_per_stage = kwargs['denoise_step_per_stage']
        kwargs['cur_denoise_step'] = cache.cnt
        model_self.cur_denoise_step = cache.cnt

        # 3. Split x into chunks (using num_chunks from metric_x, matching source code)
        chunk_width = kwargs["chunk_width"]
        offset = kwargs['slice_point']
        x_chunks = {}
        # Artifact chunks in x are not included - following source code comment
        for i in range(num_chunks):
            start_idx = i * chunk_width
            end_idx = start_idx + chunk_width
            x_chunks[offset + i] = x[:, :, start_idx:end_idx]

        # 4. Handle nearly clean chunk (artifact chunk) - add separately AFTER normal chunks
        # Following source code logic
        model_self.discard_nearly_clean_chunk = cache.discard_nearly_clean_chunk
        near_clean_chunk_idx = -1
        if not cache.discard_nearly_clean_chunk and kwargs.get("distill_nearly_clean_chunk", False):
            # Add artifact chunk - following source code comment
            near_clean_chunk_idx = max(x_chunks.keys()) + 1
            model_self.near_clean_chunk_idx = near_clean_chunk_idx
            x_chunks[near_clean_chunk_idx] = x[:, :, -chunk_width:]

        # 5. Determine which chunks to reuse (Phase 1: chunk-wise; Phase 2: token-wise)
        chunk_offset = getattr(transport, "current_chunk_offset", 0)
        chunk_denoise_count = transport.chunk_denoise_count[infer_idx]
        if cache.cnt != 0 and cache.cnt != cache.num_steps - 1:
            current_num_chunks = len(metric_chunks)
            previous_num_chunks = len(cache.prev_metric_chunks)
            common_keys = set(metric_chunks.keys()) & set(cache.prev_metric_chunks.keys())

            for i in sorted(common_keys):
                if cache.in_phase1(i, chunk_denoise_count):
                    should_reuse = cache.should_reuse(
                        chunk_id=i,
                        step=cache.cnt,
                        current_features=metric_chunks,
                        chunk_denoise_count=transport.chunk_denoise_count[infer_idx],
                        current_num_chunks=current_num_chunks,
                        previous_num_chunks=previous_num_chunks,
                        infer_idx=infer_idx,
                        cur_denoise_step=cache.cnt,
                        denoise_stage=kwargs.get("denoise_stage"),
                        denoise_idx=kwargs.get("denoise_idx"),
                        chunk_offset=chunk_offset,
                        chunk_denoise_count_value=transport.chunk_denoise_count[infer_idx][i],
                    )
                    cache.chunk_reuse_flags[i] = should_reuse
                else:
                    token_mask = cache.update_token_policy(
                        chunk_id=i,
                        x_chunk=x_chunks[i],
                        current_features=metric_chunks[i],
                        chunk_offset=chunk_offset,
                        chunk_denoise_count=chunk_denoise_count,
                    )
                    skip_forward = not token_mask.any()
                    cache.chunk_reuse_flags[i] = skip_forward
                    cache.chunk_sparse_flags[i] = (
                        not skip_forward and not token_mask.all()
                    )
                    if cache.log:
                        active_ratio = token_mask.float().mean().item()
                        phase = "phase1" if cache.in_phase1(i, chunk_denoise_count) else "phase2"
                        print(
                            f"MotionCache {phase} step {cache.cnt} chunk {i} "
                            f"(denoise={chunk_denoise_count[i]}): "
                            f"active_ratio={active_ratio:.2%}, skip_forward={skip_forward}"
                        )

        for i in sorted(x_chunks.keys()):
            cache.store_latent_chunk(i, x_chunks[i])

        # 6. Remove nearly clean chunk if first chunk can be reused
        if cache.chunk_reuse_flags.get(kwargs["slice_point"], False) and near_clean_chunk_idx != -1:
            x_chunks.pop(near_clean_chunk_idx, None)

        # 7. Store previous features
        cache.store_previous_features(metric_chunks)

        # 8. Forward chunks that are not reused
        current_infer_outputs = {}

        for i in sorted(x_chunks.keys()):
            if i in cache.chunk_reuse_flags and cache.chunk_reuse_flags[i]:
                continue

            x_i = x_chunks[i]
            # Handle near_clean_chunk_idx: use last chunk of t, y, xattn_mask
            if i == near_clean_chunk_idx:
                t_i = t[:, -1:]
                y_i = y[-1:]
                xattn_mask_i = xattn_mask[-1:]
            else:
                t_i = t[:, i - offset:i - offset + 1]
                y_i = y[i - offset:i - offset + 1]
                xattn_mask_i = xattn_mask[i - offset:i - offset + 1]

            kwargs["start_chunk_id"] = i
            kwargs["end_chunk_id"] = i + 1
            kwargs["denoising_range_num"] = 1

            if i == near_clean_chunk_idx:
                kwargs["distill_nearly_clean_chunk"] = True
            else:
                kwargs["distill_nearly_clean_chunk"] = False

            # Update KV range if compressed
            if hasattr(transport, 'compress_kv_cache') and transport.compress_kv_cache:
                if inference_params.kv_compressed:
                    kv_range = generate_dynamic_kv_range(
                        tracker=inference_params.kv_chunk_tracker,
                        current_chunk_id=i,
                        x_chunks_keys=list(x_chunks.keys()),
                        chunk_token_nums=kwargs["chunk_token_nums"],
                        near_clean_chunk_idx=near_clean_chunk_idx
                    )

            kwargs["near_clean_chunk_idx"] = near_clean_chunk_idx
            (processed_x, condition, condition_map, y_xattn_flat, rope, meta_args) = \
                model_self.forward_pre_process(
                    x_i, t_i, y_i, caption_dropout_mask, xattn_mask_i, kv_range, **kwargs
                )

            if not model_self.pre_process:
                from inference.pipeline.parallelism import pp_scheduler
                processed_x = pp_scheduler().recv_prev_data(processed_x.shape, processed_x.dtype)
                model_self.videodit_blocks.set_input_tensor(processed_x)
            else:
                processed_x = processed_x.clone()

            use_sparse = cache.chunk_sparse_flags.get(i, False)
            token_mask_i = cache.get_token_mask(i, chunk_denoise_count)
            embed_hidden = processed_x

            try:
                if use_sparse and token_mask_i is not None:
                    patch_mask = latent_mask_to_patch_mask(
                        token_mask_i,
                        patch_size=model_self.model_config.patch_size,
                    )
                    active_indices = patch_mask_to_flat_indices(patch_mask[0])
                    if active_indices.numel() == 0:
                        raise RuntimeError(f"Sparse flag set but no active tokens for chunk {i}")

                    sparse_meta = build_sparse_meta_args(
                        meta_args,
                        active_indices=active_indices,
                        total_tokens=processed_x.size(0),
                    )
                    hidden_active, cond_map_active, rope_active = sparse_gather_sequence(
                        processed_x, condition_map, rope, active_indices
                    )
                    out_active = model_self.videodit_blocks.forward(
                        hidden_states=hidden_active,
                        condition=condition,
                        condition_map=cond_map_active,
                        y_xattn_flat=y_xattn_flat,
                        rotary_pos_emb=rope_active,
                        inference_params=inference_params,
                        meta_args=sparse_meta,
                    )
                    out = sparse_scatter_sequence(embed_hidden, out_active, active_indices)
                else:
                    out = model_self.videodit_blocks.forward(
                        hidden_states=processed_x,
                        condition=condition,
                        condition_map=condition_map,
                        y_xattn_flat=y_xattn_flat,
                        rotary_pos_emb=rope,
                        inference_params=inference_params,
                        meta_args=meta_args,
                    )
            except Exception:
                raise

            # Store query states for compression
            if hasattr(transport, 'compress_kv_cache') and transport.compress_kv_cache:
                for layer in model_self.videodit_blocks.layers:
                    layer_num = layer.self_attention.layer_number
                    if hasattr(layer.self_attention, '_last_query'):
                        transport.chunk_query_states[layer_num] = layer.self_attention._last_query

            if not model_self.post_process:
                from inference.pipeline.parallelism import pp_scheduler
                pp_scheduler().isend_next(out)

            out = model_self.forward_post_process(out, meta_args)
            cache.previous_velocity[i] = out.clone().detach()
            current_infer_outputs[i] = out.clone().detach()

        return current_infer_outputs

    return model_forward


@torch.no_grad()
def _new_get_embedding_and_meta(model_self, x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs):
    """Monkey-patched version of get_embedding_and_meta with chunk info."""
    return get_embedding_and_meta_with_chunk_info(
        model_self, x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs
    )


def motioncache_integrate_velocity(self, infer_idx: int, cur_denoise_step: int):
    """
    Integrate velocity with per-chunk cache residual handling and KV compression.

    Args:
        self: SampleTransport instance
        infer_idx: Inference index
        cur_denoise_step: Current denoising step
    """
    # Get cache from class attribute
    cache = SampleTransport.cache_reuse_manager
    chunk_denoise_count = self.chunk_denoise_count[infer_idx]

    transport_input = self.transport_inputs[infer_idx]
    x_chunk = self.x_chunks[infer_idx]
    velocity = self.velocities[infer_idx]

    (denoise_step_per_stage, denoise_stage, denoise_idx), (
        chunk_offset,
        chunk_start,
        chunk_end,
        t_start,
        t_end,
    ) = self.generate_denoise_status_and_sequences(infer_idx, cur_denoise_step)

    chunk_num = x_chunk.shape[2] // self.chunk_width
    offset = chunk_start
    ori_x_chunk = x_chunk.clone()
    t = self.get_timestep(
        self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=False
    )
    next_t = self.get_timestep(
        self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx + 1, has_clean_t=False
    )
    x_embedder_before = None
    x_embedder_after = None
    x_embedder_chunk_width = None
    if self.l1_rel_change_tracker.enabled and self.l1_rel_change_tracker.is_writer_rank():
        x_embedder_before, x_embedder_chunk_width = self.embed_x_for_l1_rel_stats(ori_x_chunk)

    # Split into chunks
    x_chunks = {}
    for i in range(chunk_num):
        start_idx = i * self.chunk_width
        end_idx = start_idx + self.chunk_width
        x_chunks[offset + i] = x_chunk[:, :, start_idx:end_idx]

    # Integrate per chunk
    for i in range(chunk_num):
        chunk_id = offset + i
        reused = cache.chunk_reuse_flags.get(chunk_id, False)
        token_mask = cache.get_token_mask(chunk_id, chunk_denoise_count)
        active_ratio = None
        if token_mask is not None:
            active_ratio = token_mask.float().mean().item()

        cache.record_motion_decision(
            chunk_id=chunk_id,
            reused=reused,
            active_ratio=active_ratio,
            infer_idx=infer_idx,
            cur_denoise_step=cur_denoise_step,
            denoise_stage=denoise_stage,
            denoise_idx=denoise_idx,
            chunk_offset=chunk_offset,
            chunk_denoise_count=chunk_denoise_count,
            chunk_denoise_count_value=chunk_denoise_count[chunk_id],
        )
        cache.record_actual_execution(
            chunk_id=chunk_id,
            reused=reused,
            infer_idx=infer_idx,
            cur_denoise_step=cur_denoise_step,
            denoise_stage=denoise_stage,
            denoise_idx=denoise_idx,
            chunk_offset=chunk_offset,
        )

        slice_start = i * self.chunk_width
        slice_end = (i + 1) * self.chunk_width
        ori_slice = ori_x_chunk[:, :, slice_start:slice_end]

        if reused:
            x_chunk[:, :, slice_start:slice_end] += cache.previous_residual[chunk_id]
        elif token_mask is not None and cache.previous_residual.get(chunk_id) is not None:
            assert chunk_id in velocity, f"Chunk {chunk_id} not in velocity outputs"
            integrated = self.integrate(
                x_chunks[chunk_id], velocity[chunk_id], self.ts[infer_idx],
                denoise_step_per_stage, t_start, t_end, denoise_idx, i,
            )
            prev_residual = cache.previous_residual[chunk_id]
            mask = token_mask.unsqueeze(1).to(dtype=ori_slice.dtype)
            updated = ori_slice + mask * (integrated - ori_slice) + (1.0 - mask) * prev_residual
            x_chunk[:, :, slice_start:slice_end] = updated
            new_residual = updated - ori_slice
            cache.previous_residual[chunk_id] = (
                mask * new_residual + (1.0 - mask) * prev_residual
            )
            cache.reset_token_accumulator(chunk_id, token_mask)
        else:
            assert chunk_id in velocity, f"Chunk {chunk_id} not in velocity outputs"
            x_chunk[:, :, slice_start:slice_end] = \
                self.integrate(x_chunks[chunk_id], velocity[chunk_id], self.ts[infer_idx],
                              denoise_step_per_stage, t_start, t_end, denoise_idx, i)
            cache.previous_residual[chunk_id] = \
                x_chunk[:, :, slice_start:slice_end] - ori_slice
            if token_mask is not None:
                cache.reset_token_accumulator(chunk_id, token_mask)

    applied_residual = x_chunk - ori_x_chunk
    self.residual_diff_tracker.update_residuals(
        infer_idx=infer_idx,
        cur_denoise_step=cur_denoise_step,
        denoise_stage=denoise_stage,
        denoise_idx=denoise_idx,
        chunk_offset=chunk_offset,
        chunk_start=chunk_start,
        residual=applied_residual,
        timesteps=t,
        chunk_width=self.chunk_width,
    )
    if self.l1_rel_change_tracker.enabled and self.l1_rel_change_tracker.is_writer_rank():
        x_embedder_after, _ = self.embed_x_for_l1_rel_stats(x_chunk)
    self.l1_rel_change_tracker.update(
        infer_idx=infer_idx,
        cur_denoise_step=cur_denoise_step,
        denoise_stage=denoise_stage,
        denoise_idx=denoise_idx,
        chunk_offset=chunk_offset,
        chunk_start=chunk_start,
        x_before=ori_x_chunk,
        x_after=x_chunk,
        timesteps=t,
        next_timesteps=next_t,
        chunk_width=self.chunk_width,
        x_embedder_before=x_embedder_before,
        x_embedder_after=x_embedder_after,
        x_embedder_chunk_width=x_embedder_chunk_width,
    )

    # Increment step counter
    cache.increment_step()

    # Update chunk denoise count
    for chunk_index in range(chunk_start, chunk_end):
        chunk_denoise_count[chunk_index] += 1

    self.xs[infer_idx][:, :, chunk_start * self.chunk_width : chunk_end * self.chunk_width] = x_chunk
    self.chunk_denoise_count[infer_idx] = chunk_denoise_count

    # Check if KV compression is needed
    if hasattr(self, 'compress_kv_cache') and self.compress_kv_cache:
        _check_and_compress_kv(self, infer_idx, chunk_start, transport_input)

    # Return clean chunk if ready
    if chunk_denoise_count[chunk_start] == transport_input.num_steps:
        return _return_clean_chunk(self, infer_idx, transport_input, chunk_start, chunk_end, chunk_offset)

    return None, None


def _check_and_compress_kv(self, infer_idx: int, chunk_start: int, transport_input):
    """Check and perform KV cache compression if needed."""
    inference_params = self.inference_params[infer_idx]
    tracker = inference_params.kv_chunk_tracker

    total_cache_len = self.total_cache_chunk_nums * (
        self.chunk_width *
        (transport_input.latent_size[3] // self.model_config.patch_size) *
        (transport_input.latent_size[4] // self.model_config.patch_size)
    )

    # Get or create compressor from class attribute
    compressor = SampleTransport.kv_compress_manager
    if compressor is None:
        chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx)[1]
        compressor = KVCacheCompressor(
            total_cache_len=total_cache_len,
            tokens_per_chunk=chunk_token_nums,
            budget_chunk_nums=self.total_cache_chunk_nums - 1,
            window_size=self.window_size
        )
        SampleTransport.kv_compress_manager = compressor

    # Check if compression needed
    if compressor.should_compress(
        tracker=tracker,
        chunk_num=transport_input.chunk_num,
        chunk_start=chunk_start,
        transport_input=transport_input,
        chunk_denoise_count=self.chunk_denoise_count[infer_idx]
    ):
        compressor.compress(
            model=find_dit_model(self.model),
            inference_params=inference_params,
            tracker=tracker,
            transport_input=transport_input,
            chunk_start=chunk_start,
            chunk_denoise_count=self.chunk_denoise_count[infer_idx],
            query_states_dict=self.chunk_query_states
        )


def _return_clean_chunk(self, infer_idx, transport_input, chunk_start, chunk_end, chunk_offset):
    """Return the clean chunk if denoising is complete."""
    if transport_input.prefix_video is not None:
        prefix_video_length = transport_input.prefix_video.size(2)
        if (chunk_start + 1) * self.chunk_width <= prefix_video_length:
            return None, None

        real_start = max(chunk_start * self.chunk_width, prefix_video_length)

        if chunk_start == 0 and prefix_video_length == 1:
            real_start = 0

        clean_chunk, _ = self.xs[infer_idx][:, :, real_start:(chunk_start + 1) * self.chunk_width].chunk(2, dim=0)
        return clean_chunk, chunk_start - chunk_offset
    else:
        clean_chunk, _ = self.xs[infer_idx][
            :, :, chunk_start * self.chunk_width:(chunk_start + 1) * self.chunk_width
        ].chunk(2, dim=0)
        return clean_chunk, chunk_start - chunk_offset


def load_config(config_path: str) -> dict:
    """Load configuration from JSON or YAML file."""
    _, ext = os.path.splitext(config_path)
    with open(config_path, 'r') as f:
        if ext == '.json':
            import json
            return json.load(f)
        elif ext in ['.yaml', '.yml']:
            import yaml
            return yaml.safe_load(f)
        else:
            raise ValueError(f"Unsupported config file extension: {ext}")


def parse_arguments():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(description="Run MagiPipeline with MotionCache.")
    parser.add_argument('--config_file', type=str, help='Path to the configuration file.')
    parser.add_argument(
        '--mode', type=str, choices=['t2v', 'i2v', 'v2v'],
        required=True, help='Mode to run: t2v, i2v, or v2v.'
    )
    parser.add_argument('--prompt', type=str, required=True, help='Prompt for the pipeline.')
    parser.add_argument('--image_path', type=str, help='Path to the image file (for i2v mode).')
    parser.add_argument('--prefix_video_path', type=str, help='Path to the prefix video file (for v2v mode).')
    parser.add_argument('--output_path', type=str, required=True, help='Path to save the output video.')
    parser.add_argument('--additional_config', type=str, help='Path to additional config file.')
    parser.add_argument(
        '--residual_stats_path',
        type=str,
        help='Optional path to save per-chunk residual-difference norm stats as .json, .pt, or .pth.',
    )
    parser.add_argument(
        '--l1_rel_stats_path',
        type=str,
        help='Optional path to save per-chunk relative L1 change stats as .json, .pt, or .pth.',
    )
    parser.add_argument(
        '--motioncache_metric_stats_path',
        type=str,
        help='Optional path to save MotionCache reuse metric stats as .json, .pt, or .pth.',
    )
    parser.add_argument('--print_peak_memory', action='store_true', help='Print peak memory usage.')

    return parser.parse_args()


def main():
    """Main entry point."""
    args = parse_arguments()

    # Load additional config
    if args.additional_config:
        additional_config = load_config(args.additional_config)
        print(f"Loading additional config: {additional_config}")

        for key, value in additional_config.items():
            setattr(args, key, value)
            print(f"Added to args: {key} = {value}")

        # Handle parameter name compatibility
        if hasattr(args, 'no_reuse_first_n_steps') and not hasattr(args, 'warmup_steps'):
            args.warmup_steps = args.no_reuse_first_n_steps
        if hasattr(args, 'no_reuse_mode'):
            # no_reuse_mode is deprecated, ignore it
            pass
    else:
        print("No additional config provided.")

    if args.print_peak_memory:
        if torch.cuda.is_available():
            torch.cuda.reset_peak_memory_stats()
            device = torch.cuda.current_device()
            print(f"Running on GPU: {torch.cuda.get_device_name(device)}")
            print(f"GPU Memory before pipeline: {torch.cuda.memory_allocated(device) / 1024**3:.2f} GB")
        else:
            print("CUDA not available, running on CPU")

    # Setup MotionCache
    setup_motioncache(
        rel_l1_thresh=args.rel_l1_thresh,
        warmup_steps=args.warmup_steps,
        phase1_steps=getattr(args, 'phase1_steps', 9),
        alpha=getattr(args, 'alpha', 0.5),
        discard_nearly_clean_chunk=args.discard_nearly_clean_chunk,
        log=args.log,
        total_cache_chunk_nums=args.total_cache_chunk_nums,
        compress_kv_cache=args.compress_kv_cache,
        metric_stats_path=args.motioncache_metric_stats_path,
    )

    # Setup KV compression in model
    compression_config = {
        "method_config": {
            "compress_strategy": getattr(args, 'compress_strategy', 'token'),
            "mix_lambda": getattr(args, 'mix_lambda', 0.07),
            "query_granularity": getattr(args, 'query_granularity', 'chunk'),
            "score_weighting_method": getattr(args, 'score_weighting_method', None) or 'no_weight',
            "power": getattr(args, 'power', 3),
        },
    }
    replace_magi(compression_config)

    # Run pipeline
    pipeline = MagiPipeline(
        args.config_file,
        residual_stats_path=args.residual_stats_path,
        l1_rel_stats_path=args.l1_rel_stats_path,
    )

    if args.mode == 't2v':
        pipeline.run_text_to_video(prompt=args.prompt, output_path=args.output_path)
    elif args.mode == 'i2v':
        if not args.image_path:
            print("Error: --image_path is required for i2v mode.")
            sys.exit(1)
        pipeline.run_image_to_video(prompt=args.prompt, image_path=args.image_path, output_path=args.output_path)
    elif args.mode == 'v2v':
        if not args.prefix_video_path:
            print("Error: --prefix_video_path is required for v2v mode.")
            sys.exit(1)
        pipeline.run_video_to_video(
            prompt=args.prompt, prefix_video_path=args.prefix_video_path, output_path=args.output_path
        )

    if args.print_peak_memory:
        if torch.cuda.is_available():
            peak_memory = torch.cuda.max_memory_allocated(device) / 1024**3
            current_memory = torch.cuda.memory_allocated(device) / 1024**3
            cached_memory = torch.cuda.memory_reserved(device) / 1024**3
            total_memory = torch.cuda.get_device_properties(device).total_memory / 1024**3

            print("\n" + "=" * 50)
            print("GPU Memory Usage Summary:")
            print(f"Peak memory allocated: {peak_memory:.2f} GB")
            print(f"Current memory allocated: {current_memory:.2f} GB")
            print(f"Cached memory reserved: {cached_memory:.2f} GB")
            print(f"Total GPU memory: {total_memory:.2f} GB")
            print(f"Peak memory usage: {(peak_memory/total_memory)*100:.1f}%")
            print("=" * 50)

            gc.collect()
            torch.cuda.empty_cache()
            final_memory = torch.cuda.memory_allocated(device) / 1024**3
            print(f"Memory after cache cleanup: {final_memory:.2f} GB")


if __name__ == "__main__":
    main()