File size: 3,895 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
# 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.

"""Sparse token gather/scatter utilities for MotionCache Phase 2."""

from dataclasses import replace
from typing import Optional, Tuple

import torch
import torch.nn.functional as F

from inference.common import ModelMetaArgs, PackedCoreAttnParams, PackedCrossAttnParams


def latent_mask_to_patch_mask(
    token_mask: torch.Tensor,
    patch_size: int = 2,
) -> torch.Tensor:
    """
    Downsample latent-space mask [N, T, H, W] to patch token mask [N, T, Hp, Wp].

    A patch is active if any latent pixel inside the patch is active.
    """
    n, t, h, w = token_mask.shape
    flat = token_mask.reshape(n * t, 1, h, w).float()
    pooled = F.max_pool2d(flat, kernel_size=patch_size, stride=patch_size)
    hp, wp = pooled.shape[-2], pooled.shape[-1]
    return pooled.reshape(n, t, hp, wp).bool()


def patch_mask_to_flat_indices(
    patch_mask: torch.Tensor,
) -> torch.Tensor:
    """Return flat token indices [num_active] in (T*Hp*Wp) row-major order."""
    flat = patch_mask.reshape(-1)
    return torch.nonzero(flat, as_tuple=False).squeeze(-1)


def build_sparse_meta_args(
    meta_args: ModelMetaArgs,
    active_indices: torch.Tensor,
    total_tokens: int,
) -> ModelMetaArgs:
    """Rebuild attention params for sparse query length (active tokens only)."""
    num_active = int(active_indices.numel())
    device = active_indices.device

    q_range = torch.tensor([[0, num_active]], dtype=torch.int32, device=device)
    core_attn_params = PackedCoreAttnParams(
        q_range=q_range,
        k_range=meta_args.core_attn_params.k_range,
        np_q_range=q_range.cpu().numpy(),
        np_k_range=meta_args.core_attn_params.np_k_range,
        max_seqlen_q=num_active,
        max_seqlen_k=meta_args.core_attn_params.max_seqlen_k,
    )

    cu_seqlens_q = torch.tensor([0, num_active], dtype=torch.int32, device=device)
    cross_attn_params = PackedCrossAttnParams(
        q_ranges=torch.tensor([[0, num_active]], dtype=torch.int32, device=device),
        kv_ranges=meta_args.cross_attn_params.kv_ranges,
        cu_seqlens_q=cu_seqlens_q,
        cu_seqlens_kv=meta_args.cross_attn_params.cu_seqlens_kv,
        max_seqlen_q=num_active,
        max_seqlen_kv=meta_args.cross_attn_params.max_seqlen_kv,
    )

    return replace(
        meta_args,
        core_attn_params=core_attn_params,
        cross_attn_params=cross_attn_params,
        sparse_active_indices=active_indices,
        sparse_total_tokens=total_tokens,
    )


def sparse_gather_sequence(
    hidden_states: torch.Tensor,
    condition_map: torch.Tensor,
    rotary_pos_emb: torch.Tensor,
    active_indices: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    """Gather [S,...] tensors along the sequence dimension."""
    return (
        hidden_states.index_select(0, active_indices),
        condition_map.index_select(0, active_indices),
        rotary_pos_emb.index_select(0, active_indices),
    )


def sparse_scatter_sequence(
    full_hidden: torch.Tensor,
    active_hidden: torch.Tensor,
    active_indices: torch.Tensor,
) -> torch.Tensor:
    """Scatter active transformer outputs back into the full [S,N,D] buffer."""
    scattered = full_hidden.clone()
    scattered.index_copy_(0, active_indices, active_hidden.to(dtype=scattered.dtype))
    return scattered