File size: 11,275 Bytes
9294bc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from functools import partial
from typing import Literal
from einops import rearrange
from torch import Tensor
from torch.nn import ConvTranspose2d, ConvTranspose3d

from flow_grpo.inflated_lib import (
    MemoryState,
    extend_head,
    inflate_bias,
    inflate_distribution_bias,
    inflate_distribution_weight,
    inflate_weight,
    modify_state_dict,
)
from flow_grpo.conv_gradfix import GradFixConv2d, GradFixConv3d

VERBOSE = False

_inflation_mode_t = (Literal["none", "flatten", "partial_flatten", "pad", "tile"],)
_direction_t = Literal["", "out", "in"]


class InflatedCausalConv3d(GradFixConv3d):
    """
    Note:
        To align the behavior of pretrained 2D models,
        if you compose a video clip from a single image by:
            - duplicating:      set shape_norm = True
            - padding zeros:    set shape_norm = False
        to avoid gaps in the beginning of training process.
    """

    def __init__(
        self, *args, inflation_mode: _inflation_mode_t, shape_norm: bool = True, **kwargs
    ):
        self.shape_norm = shape_norm
        self.inflation_mode = inflation_mode
        self.padding_bank = None
        super().__init__(*args, **kwargs)
        self.temporal_padding = self.padding[0]
        self.padding = (0, *self.padding[1:])  # Remove temporal pad to keep causal.

    def forward(self, input: Tensor, memory_state: MemoryState = MemoryState.DISABLED) -> Tensor:
        bank_size = self.stride[0] - self.kernel_size[0]
        padding_bank = (
            input[:, :, bank_size:].detach()
            if (bank_size != 0 and memory_state != MemoryState.DISABLED)
            else None
        )
        if (self.padding_bank is not None) and (memory_state == MemoryState.ACTIVE):
            input = extend_head(input, memory=self.padding_bank)
        else:
            input = extend_head(input, times=self.temporal_padding * 2)
        if memory_state != MemoryState.DISABLED and not self.training:
            self.padding_bank = padding_bank
        return super().forward(input)

    def _load_from_state_dict(
        self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
    ):
        if self.inflation_mode == "none":
            super()._load_from_state_dict(
                state_dict,
                prefix,
                local_metadata,
                strict,
                missing_keys,
                unexpected_keys,
                error_msgs,
            )
        else:
            # NOTE: need to switch off strict
            super()._load_from_state_dict(
                modify_state_dict(
                    self,
                    state_dict,
                    prefix,
                    verbose=VERBOSE,
                    inflate_weight_fn=partial(inflate_weight, position="tail"),
                    inflate_bias_fn=partial(inflate_bias, position="tail"),
                ),
                prefix,
                local_metadata,
                False,
                missing_keys,
                unexpected_keys,
                error_msgs,
            )


class InflatedDistributionCausalConv3d(GradFixConv3d):
    """
    Note:
        Direction:
            - out: this layer generates mean/std of some distribution;
            - in:  this layer takes tensors sampled from output of `out` layer as input.
    """

    def __init__(
        self,
        *args,
        direction: _direction_t,
        inflation_mode: _inflation_mode_t,
        shape_norm: bool = True,
        **kwargs,
    ):
        self.shape_norm = shape_norm
        self.inflation_mode = inflation_mode
        self.direction = direction
        self.padding_bank = None
        super().__init__(*args, **kwargs)
        self.temporal_padding = self.padding[0]
        self.padding = (0, *self.padding[1:])  # Remove temporal pad to keep causal.

    def forward(self, input: Tensor, memory_state: MemoryState = MemoryState.DISABLED) -> Tensor:
        bank_size = self.stride[0] - self.kernel_size[0]
        padding_bank = (
            input[:, :, bank_size:].detach()
            if (bank_size != 0 and memory_state != MemoryState.DISABLED)
            else None
        )
        if (self.padding_bank is not None) and (memory_state == MemoryState.ACTIVE):
            input = extend_head(input, memory=self.padding_bank)
        else:
            input = extend_head(input, times=self.temporal_padding * 2)
        if memory_state != MemoryState.DISABLED and not self.training:
            self.padding_bank = padding_bank
        return super().forward(input)

    def _load_from_state_dict(
        self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
    ):
        if self.inflation_mode == "none":
            super()._load_from_state_dict(
                state_dict,
                prefix,
                local_metadata,
                strict,
                missing_keys,
                unexpected_keys,
                error_msgs,
            )
        else:
            super()._load_from_state_dict(
                modify_state_dict(
                    self,
                    state_dict,
                    prefix,
                    verbose=VERBOSE,
                    inflate_weight_fn=partial(
                        inflate_distribution_weight, direction=self.direction, position="tail"
                    ),
                    inflate_bias_fn=partial(
                        inflate_distribution_bias, direction=self.direction, position="tail"
                    ),
                ),
                prefix,
                local_metadata,
                False,
                missing_keys,
                unexpected_keys,
                error_msgs,
            )


class InflatedConvTranspose3d(ConvTranspose3d):
    # Note: It's not a causal one.
    def __init__(
        self, *args, inflation_mode: _inflation_mode_t, shape_norm: bool = True, **kwargs
    ):
        self.shape_norm = shape_norm
        self.inflation_mode = inflation_mode
        super().__init__(*args, **kwargs)

    def _load_from_state_dict(
        self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
    ):
        if self.inflation_mode == "none":
            super()._load_from_state_dict(
                state_dict,
                prefix,
                local_metadata,
                strict,
                missing_keys,
                unexpected_keys,
                error_msgs,
            )
        else:
            # NOTE: need to switch off strict
            super()._load_from_state_dict(
                modify_state_dict(
                    self,
                    state_dict,
                    prefix,
                    verbose=VERBOSE,
                    inflate_weight_fn=partial(inflate_weight, position="center"),
                    inflate_bias_fn=partial(inflate_bias, position="center"),
                ),
                prefix,
                local_metadata,
                False,
                missing_keys,
                unexpected_keys,
                error_msgs,
            )


class FlattenedConvTranspose3d(ConvTranspose2d):
    def forward(self, input: Tensor, **kwargs) -> Tensor:
        output = rearrange(input, "b c f h w -> (b f) c h w")
        output = super().forward(output)
        output = rearrange(output, "(b f) c h w -> b c f h w", f=input.size(2))
        return output


class FlattenedConv3d(GradFixConv2d):
    def forward(self, input: Tensor, **kwargs) -> Tensor:
        output = rearrange(input, "b c f h w -> (b f) c h w")
        output = super().forward(output)
        output = rearrange(output, "(b f) c h w -> b c f h w", f=input.size(2))
        return output


def init_causal_conv3d(
    *args,
    inflation_mode: _inflation_mode_t,
    direction: _direction_t = "",
    partial_switch: bool = False,
    **kwargs,
):
    """
    Initialize a Causal-3D convolution layer.
    Parameters:
        inflation_mode: Listed as below. It's compatible with all the 3D-VAE checkpoints we have.
            - none: No inflation will be conducted.
                    The loading logic of state dict will fall back to default.
            - flatten:  It will produce a `fake` 3D layer,
                        which simply squeeze the axis of batch size and depth together,
                        and then conduct 2D convolution.
            - partial_flatten:
                - layers with `partial_switch` on:  using `none` mode.
                - layers with `partial_switch` off: using `flatten` mode.
            - pad / tile: Refer to the definition of `InflatedCausalConv3d`.
        direction:
            - empty string: Ordinary causal convolution layer.
            - out / in: Refer to the definition of `InflatedDistributionCausalConv3d`.
        partial_switch: Only works when `inflation_mode` is `partial_flatten`.
    """
    stride = kwargs.get("stride", args[3] if len(args) > 3 else None)
    padding = kwargs.get("padding", args[4] if len(args) > 4 else None)
    if "flatten" in inflation_mode:
        if (
            (
                (not stride)
                or isinstance(stride, int)
                or (isinstance(stride, list or tuple) and len(stride) < 3)
            )  # if the config of stride can be used for 2D conv
            and (
                (not padding)
                or isinstance(padding, int)
                or (isinstance(padding, list or tuple) and len(padding) < 3)
            )  # if the config of padding can be used for 2D conv
            and (("partial" not in inflation_mode) or (not partial_switch))
            # if it's fully-flatten mode, or with `partial_switch` off
        ):
            return FlattenedConv3d(*args, **kwargs)
        else:
            return InflatedCausalConv3d(*args, inflation_mode="none", **kwargs)
            # Force-override
    else:
        if direction:
            return InflatedDistributionCausalConv3d(
                *args, direction=direction, inflation_mode=inflation_mode, **kwargs
            )
        else:
            return InflatedCausalConv3d(*args, inflation_mode=inflation_mode, **kwargs)


def init_transposed_conv3d(
    *args, inflation_mode: _inflation_mode_t, partial_switch: bool = False, **kwargs
):
    stride = kwargs.get("stride", args[3] if len(args) > 3 else None)
    padding = kwargs.get("padding", args[4] if len(args) > 4 else None)
    if "flatten" in inflation_mode:
        if (
            (
                (not stride)
                or isinstance(stride, int)
                or (isinstance(stride, list or tuple) and len(stride) < 3)
            )
            and (
                (not padding)
                or isinstance(padding, int)
                or (isinstance(padding, list or tuple) and len(padding) < 3)
            )
            or (("partial" in inflation_mode) and not partial_switch)
        ):
            return FlattenedConvTranspose3d(*args, **kwargs)
        else:
            return InflatedConvTranspose3d(
                *args, inflation_mode="none", **kwargs
            )  # Force-override
    else:
        return InflatedConvTranspose3d(*args, inflation_mode=inflation_mode, **kwargs)