File size: 12,849 Bytes
bc50ea0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""CPU regression for exact master-audio latent masking."""

import os
import sys
import types

import torch


TESTS = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, TESTS)

import _masked_prefix_unit_test as harness  # noqa: E402


def main():
    harness._install_comfy_stubs()
    package = types.ModuleType(harness.PACKAGE)
    package.__path__ = [harness.ROOT]
    sys.modules[harness.PACKAGE] = package
    harness._load("patch_layout")
    harness._load("patch_payload")
    nodes = harness._load("nodes")
    harness._load("masked_context")
    audio_context = harness._load("master_audio_context")
    audio_context.require_h3_mask_support = lambda _operation: True

    target_frames = 141
    video_steps = 42
    audio_steps = 235
    assert nodes._pixel_frames(video_steps) == target_frames
    target_video = torch.zeros((1, 16, video_steps, 2, 4))
    target_audio = torch.zeros((1, 32, 2, audio_steps))
    latent = {
        "samples": harness.NestedTensor((target_video, target_audio)),
    }

    previous_frames = torch.rand((120, 32, 64, 3))
    master_audio = {
        "waveform": torch.rand((1, 2, 32_000 * 30)),
        "sample_rate": 32_000,
    }

    class VideoVAE:
        def encode(self, frames):
            count = int(frames.shape[0])
            steps = max(1, (count - 5) // 17 * 5 + 2)
            return torch.full((1, 16, steps, 2, 4), 0.25)

    class AudioVAE:
        audio_sample_rate = 32_000

        def encode(self, waveform):
            steps = round(int(waveform.shape[1]) / 32_000 * 40)
            return torch.full((1, 32, 2, steps), 0.5)

    output, prefix, clip_audio = (
        audio_context.MiniMaxH3ContexMasterAudioMaskedAV().prepare(
            latent,
            AudioVAE(),
            master_audio,
            clip_start_seconds=3.25,
            context_length=39,
            source_fps=24.0,
            crop="disabled",
            vae=VideoVAE(),
            source_frames=previous_frames,
        ))
    video, audio = output["samples"].unbind()
    video_mask, audio_mask = output["noise_mask"].unbind()
    assert prefix == 39
    assert torch.allclose(
        video[:, :, :12], torch.full_like(video[:, :, :12], 0.25))
    assert not torch.count_nonzero(video[:, :, 12:])
    assert torch.allclose(audio, torch.full_like(audio, 0.5))
    assert not torch.count_nonzero(video_mask[:, :, :12])
    assert torch.all(video_mask[:, :, 12:] == 1.0)
    assert not torch.count_nonzero(audio_mask)
    assert clip_audio["sample_rate"] == 32_000
    assert int(clip_audio["waveform"].shape[-1]) == round(
        target_frames / 24 * 32_000)

    # Preferred live chaining copies the sampled H3 video tail directly. The
    # source latent's audio stream must not replace the authoritative master.
    source_video = torch.arange(
        video_steps, dtype=torch.float32).reshape(
            1, 1, video_steps, 1, 1).expand_as(target_video).clone()
    source_audio = torch.full_like(target_audio, 0.9)
    source_latent = {
        "samples": harness.NestedTensor((source_video, source_audio)),
    }
    live, live_prefix, _ = (
        audio_context.MiniMaxH3ContexMasterAudioMaskedAV().prepare(
            latent,
            AudioVAE(),
            master_audio,
            clip_start_seconds=3.25,
            context_length=39,
            source_latent=source_latent,
        ))
    live_video, live_audio = live["samples"].unbind()
    live_video_mask, live_audio_mask = live["noise_mask"].unbind()
    assert live_prefix == 39
    assert torch.equal(live_video[:, :, :12], source_video[:, :, -12:])
    assert not torch.count_nonzero(live_video[:, :, 12:])
    assert torch.allclose(live_audio, torch.full_like(live_audio, 0.5))
    assert not torch.count_nonzero(live_video_mask[:, :, :12])
    assert torch.all(live_video_mask[:, :, 12:] == 1.0)
    assert not torch.count_nonzero(live_audio_mask)

    try:
        audio_context.MiniMaxH3ContexMasterAudioMaskedAV().prepare(
            latent,
            AudioVAE(),
            master_audio,
            context_length=39,
            vae=VideoVAE(),
            source_frames=previous_frames,
            source_latent=source_latent,
        )
    except ValueError as exc:
        assert "either source_latent or source_frames" in str(exc)
    else:
        raise AssertionError("both master-audio video sources were accepted")

    assert "source_latent" in (
        audio_context.MiniMaxH3ContexMasterAudioMaskedAV.INPUT_TYPES()[
            "optional"])
    assert "voice" in (
        audio_context.MiniMaxH3ContexMasterAudioMaskedAV.INPUT_TYPES()[
            "optional"])
    assert audio_context.MiniMaxH3ContexMasterAudioMaskedAV.INPUT_TYPES()[
        "required"]["preroll_seconds"][1]["default"] == 0.0

    # Chain Context may already own the protected visual prefix. Replacing
    # the audio target must retain that video mask while making the complete
    # current master-audio stream protected.
    existing_video_mask = torch.ones((1, 1, video_steps, 2, 4))
    existing_video_mask[:, :, :7] = 0.0
    existing_audio_mask = torch.ones((1, 1, 2, audio_steps))
    chained_latent = {
        "samples": harness.NestedTensor((target_video, target_audio)),
        "noise_mask": harness.NestedTensor((
            existing_video_mask, existing_audio_mask)),
    }
    chained, chained_prefix, _ = (
        audio_context.MiniMaxH3ContexMasterAudioMaskedAV().prepare(
            chained_latent,
            AudioVAE(),
            master_audio,
            clip_start_seconds=3.25,
            context_length=0,
        ))
    chained_video_mask, chained_audio_mask = chained["noise_mask"].unbind()
    assert chained_prefix == 0
    assert not torch.count_nonzero(chained_video_mask[:, :, :7])
    assert torch.all(chained_video_mask[:, :, 7:] == 1.0)
    assert not torch.count_nonzero(chained_audio_mask)

    first, first_prefix, _ = (
        audio_context.MiniMaxH3ContexMasterAudioMaskedAV().prepare(
            latent,
            AudioVAE(),
            master_audio,
            clip_start_seconds=0.0,
            context_length=0,
        ))
    first_video_mask, first_audio_mask = first["noise_mask"].unbind()
    assert first_prefix == 0
    assert torch.all(first_video_mask == 1.0)
    assert not torch.count_nonzero(first_audio_mask)

    class FloorAudioVAE:
        """Simulate an audio encoder that floors its temporal output."""

        audio_sample_rate = 32_000

        def __init__(self):
            self.encoded_samples = []

        def encode(self, waveform):
            samples = int(waveform.shape[1])
            self.encoded_samples.append(samples)
            steps = int(samples / self.audio_sample_rate * 40)
            return torch.full((1, 32, 2, steps), 0.75)

    rounding_frames = 124
    rounding_video_steps = 37
    rounding_audio_steps = 207
    assert nodes._pixel_frames(rounding_video_steps) == rounding_frames
    rounding_latent = {
        "samples": harness.NestedTensor((
            torch.zeros((1, 16, rounding_video_steps, 2, 4)),
            torch.zeros((1, 32, 2, rounding_audio_steps)),
        )),
    }
    floor_vae = FloorAudioVAE()
    rounded, rounded_prefix, rounded_clip_audio = (
        audio_context.MiniMaxH3ContexMasterAudioMaskedAV().prepare(
            rounding_latent,
            floor_vae,
            master_audio,
            clip_start_seconds=1.0,
            context_length=0,
        ))
    _, rounded_audio = rounded["samples"].unbind()
    _, rounded_audio_mask = rounded["noise_mask"].unbind()
    picture_samples = round(rounding_frames / 24 * 32_000)
    grid_samples = int(rounding_audio_steps / 40 * 32_000)
    assert floor_vae.encoded_samples == [grid_samples]
    assert grid_samples > picture_samples
    assert int(rounded_audio.shape[-1]) == rounding_audio_steps
    assert torch.allclose(
        rounded_audio, torch.full_like(rounded_audio, 0.75))
    assert not torch.count_nonzero(rounded_audio_mask)
    assert rounded_prefix == 0
    assert int(rounded_clip_audio["waveform"].shape[-1]) == picture_samples

    # Absolute endpoints avoid the occasional one-sample error caused by
    # rounding a relative duration and adding it to an already-rounded start.
    awkward_start = 0.3 / 32_000.0
    absolute_start = round(awkward_start * 32_000)
    absolute_end = round(
        (awkward_start + rounding_frames / 24.0) * 32_000)
    _, _, absolute_clip_audio = (
        audio_context.MiniMaxH3ContexMasterAudioMaskedAV().prepare(
            rounding_latent,
            FloorAudioVAE(),
            master_audio,
            clip_start_seconds=awkward_start,
            context_length=0,
        ))
    assert int(absolute_clip_audio["waveform"].shape[-1]) == (
        absolute_end - absolute_start)

    class ShortFirstAudioVAE(FloorAudioVAE):
        def encode(self, waveform):
            encoded = super().encode(waveform)
            if len(self.encoded_samples) == 1:
                return encoded[..., :-1]
            return encoded

    retry_vae = ShortFirstAudioVAE()
    retried, _, _ = (
        audio_context.MiniMaxH3ContexMasterAudioMaskedAV().prepare(
            rounding_latent,
            retry_vae,
            master_audio,
            clip_start_seconds=1.0,
            context_length=0,
        ))
    _, retried_audio = retried["samples"].unbind()
    assert len(retry_vae.encoded_samples) == 2
    assert retry_vae.encoded_samples[0] == grid_samples
    assert retry_vae.encoded_samples[1] > grid_samples
    assert int(retried_audio.shape[-1]) == rounding_audio_steps
    assert torch.allclose(
        retried_audio, torch.full_like(retried_audio, 0.75))

    class IndexedAudioVAE:
        audio_sample_rate = 32_000

        def __init__(self):
            self.encoded_samples = []

        def encode(self, waveform):
            samples = int(waveform.shape[1])
            self.encoded_samples.append(samples)
            steps = round(samples / self.audio_sample_rate * 40)
            ticks = torch.arange(steps, dtype=torch.float32).reshape(
                1, 1, 1, steps)
            return ticks.expand(1, 32, 2, steps).clone()

    indexed_vae = IndexedAudioVAE()
    contextual, _, contextual_clip = (
        audio_context.MiniMaxH3ContexMasterAudioMaskedAV().prepare(
            rounding_latent,
            indexed_vae,
            master_audio,
            clip_start_seconds=2.0,
            context_length=0,
            preroll_seconds=1.0,
            lookahead_seconds=0.2,
        ))
    _, contextual_audio = contextual["samples"].unbind()
    _, contextual_mask = contextual["noise_mask"].unbind()
    expected_context_steps = 40 + rounding_audio_steps + 8
    assert indexed_vae.encoded_samples == [
        int(expected_context_steps / 40 * 32_000)]
    assert torch.equal(
        contextual_audio[0, 0, 0],
        torch.arange(40, 40 + rounding_audio_steps, dtype=torch.float32))
    assert not torch.count_nonzero(contextual_mask)
    assert int(contextual_clip["waveform"].shape[-1]) == picture_samples

    voice = {
        "waveform": torch.zeros((1, 1, 32_000 * 30)),
        "sample_rate": 32_000,
    }
    voice["waveform"][..., 32_000:64_000] = 1.0
    gated, _, _ = (
        audio_context.MiniMaxH3ContexMasterAudioMaskedAV().prepare(
            latent,
            AudioVAE(),
            master_audio,
            clip_start_seconds=0.0,
            context_length=0,
            audio_denoise=0.0,
            gap_denoise=0.3,
            gate_hold_seconds=0.0,
            voice=voice,
        ))
    _, gated_mask = gated["noise_mask"].unbind()
    assert torch.all(gated_mask[..., 10] == 0.3)
    assert not torch.count_nonzero(gated_mask[..., 50])
    assert torch.all(gated_mask[..., 100] == 0.3)

    softened, _, _ = (
        audio_context.MiniMaxH3ContexMasterAudioMaskedAV().prepare(
            latent,
            AudioVAE(),
            master_audio,
            clip_start_seconds=0.0,
            context_length=0,
            audio_denoise=0.25,
        ))
    _, softened_mask = softened["noise_mask"].unbind()
    assert torch.all(softened_mask == 0.25)

    assert (
        "MiniMaxH3ContexMasterAudioMaskedAV"
        in audio_context.NODE_CLASS_MAPPINGS)
    assert (
        "MiniMaxH3ContexSongMaskedAVContext"
        not in audio_context.NODE_CLASS_MAPPINGS)
    assert (
        "MiniMaxH3SongMaskedAVContext"
        not in audio_context.NODE_CLASS_MAPPINGS)
    print(
        "master-audio masking: absolute-endpoint timeline slice, complete protected audio, "
        "40 Hz target-grid lookahead, contextual tick crop, vocal gate, "
        "fractional song denoise, decoded and direct-latent 39-frame "
        "protected video continuation, "
        "and clip-1 video generation pass")


if __name__ == "__main__":
    main()