"""Bounded native H3 audio convolutions with one causal posterior history. The encoder's finite convolution context fits inside 32 latent frames on each side. Chunk boundaries align to its 800-sample hop; only interior features are retained. The posterior attention runs once over all features, so importing a long file never resets its causal history at arbitrary ten-second boundaries. """ import torch def encode(vae, read_waveform, sample_count): import comfy.model_management as mm from comfy.ldm.minimax.audio_vae import MiniMaxH3AudioVAE model = getattr(vae, 'first_stage_model', None) if sample_count < 800 or sample_count % 800: raise ValueError('Source audio must lie on the native 800-sample grid') if not isinstance(model, MiniMaxH3AudioVAE): # Contract-compatible VAEs may manage their own encoding internals. return vae.encode(read_waveform(0, sample_count)).detach().cpu().contiguous() hop, block, context = 800, 320000, 25600 memory = vae.memory_used_encode((1, 2, min(sample_count, block + 2*context)), vae.vae_dtype) mm.load_models_gpu([vae.patcher], memory_required=memory, force_full_load=vae.disable_offload) features = [] with mm.cuda_device_context(vae.device), torch.inference_mode(): for start in range(0, sample_count, block): mm.throw_exception_if_processing_interrupted() end = min(sample_count, start + block) left, right = max(0, start - context), min(sample_count, end + context) waveform = read_waveform(left, right).movedim(-1, 1).to(device=vae.device, dtype=vae.vae_dtype) encoded = model.encoder(waveform.reshape(2, 1, -1)) first, last = (start-left)//hop, (end-left)//hop features.append(encoded[..., first:last].detach().cpu()) del waveform, encoded x = torch.cat(features, -1).to(device=vae.device, dtype=vae.vae_dtype) del features mm.throw_exception_if_processing_interrupted() x = model.pre_block(x.transpose(1, 2)).transpose(1, 2) z = model.mean_proj(x) mean = model.latents_mean.view(1, -1, 1).to(z) std = model.latents_std.view(1, -1, 1).to(z) z = (z - mean) / std return z.reshape(1, 2, 32, sample_count//hop).permute(0, 2, 1, 3).detach().cpu().contiguous()