[SIGGRAPH Asia 2026] 4DAnyone: Create Anyone in 4D from a Casual Monocular Video
Reduce inference memory through explicit tensor lifetimes (#47)
Yudong Jin0606491deaf3
diff --git a/fdanyone/model/conditioning.py b/fdanyone/model/conditioning.pyindex 0f7ec81..3be9615 100644--- a/fdanyone/model/conditioning.py+++ b/fdanyone/model/conditioning.py@@ -185,9 +185,6 @@ class PoseFeatureBank:for output_index, feature_index in enumerate(indices):destination[output_index].copy_(self.features[feature_index])- def null_on(self, device: str) -> Tensor:- return self.null_features.to(device=device)-@dataclass(frozen=True)class PoseFeatureCache:@@ -205,7 +202,6 @@ class _PoseEncodingJob:skeletons: tuple[SkeletonVideo, ...]batch_size: intpacked_views: int- channels_last: boolbuilder: _PoseFeatureBuilder@@ -256,7 +252,6 @@ def _pose_jobs(skeletons: tuple[SkeletonVideo, ...],group_size: int,packed_views: int,- channels_last: bool,) -> tuple[tuple[_PoseEncodingJob, ...], _PoseFeatureBuilder]:"""Plan complete fixed-shape calls and their canonical output owner."""@@ -272,7 +267,6 @@ def _pose_jobs(skeletons=tuple(skeletons[index] for index in indices),batch_size=plan.batch_size,packed_views=packed_views,- channels_last=channels_last,builder=builder,)for indices in plan.feature_groups@@ -293,7 +287,7 @@ def _execute_pose_job(video_shape = Nonebatch = None- memory_format = torch.channels_last_3d if job.channels_last else torch.contiguous_format+ prefix = pose_encoder.temporal_prefixfor batch_index, skeleton in enumerate(job.skeletons):LOGGER.info("Loading skeleton conditioning from %s", skeleton.path.name)decoded = conditioning.load_skeleton_tensor([skeleton]).to(dtype=torch.bfloat16, device="cpu").contiguous()@@ -303,16 +297,18 @@ def _execute_pose_job(if video_shape is None:video_shape = current_shapebatch = torch.empty(- (job.batch_size, *video_shape),+ (job.batch_size, video_shape[0], video_shape[1] + prefix, *video_shape[2:]),dtype=torch.bfloat16,device=device,- memory_format=memory_format,).fill_(-1)elif current_shape != video_shape:raise FourDAnyoneError(f"Skeleton {skeleton.path} has shape {tuple(decoded.shape)}, expected {(1, *video_shape)}.")- batch[batch_index].copy_(decoded[0])+ # Construct the exact contiguous input previously produced by cat in+ # PoseEncoder. Null slots remain -1, including their temporal prefix.+ batch[batch_index, :, :prefix].copy_(decoded[0, :, :1])+ batch[batch_index, :, prefix:].copy_(decoded[0])del decodedencoded = _encode_pose_batch(pose_encoder, batch)@@ -350,13 +346,11 @@ def build_pose_feature_cache(skeletons=conditioning.rcp_skeletons,group_size=VIEWS_PER_GROUP,packed_views=1,- channels_last=True,)target_jobs, target_builder = _pose_jobs(skeletons=conditioning.target_skeletons,group_size=VIEWS_PER_GROUP,packed_views=2 if view_plan.enable_rcp else 1,- channels_last=False,)jobs = (*rcp_jobs, *target_jobs)worker_count = min(len(jobs), len(devices))diff --git a/fdanyone/model/distributed.py b/fdanyone/model/distributed.pyindex 85b27e8..5ba7b14 100644--- a/fdanyone/model/distributed.py+++ b/fdanyone/model/distributed.py@@ -245,7 +245,7 @@ def _load_worker_state(rank: int, request: DistributedDenoiseRequest, denoiser:device_index=int(device.removeprefix("cuda:")),source=payload["source"].to(dtype=denoiser.dtype, device=device),context=payload["context"].to(dtype=denoiser.dtype, device=device),- null_pose_feature=payload["null_pose_feature"].to(dtype=denoiser.dtype, device=device),+ null_pose_feature=payload["null_pose_feature"],pose_features=pose_features,latents=payload["initial_latents"].to(dtype=denoiser.dtype, copy=True) if rank == 0 else None,pose_feature_batch=torch.empty(diff --git a/fdanyone/model/inference.py b/fdanyone/model/inference.pyindex 07c9398..4cf8a86 100644--- a/fdanyone/model/inference.py+++ b/fdanyone/model/inference.py@@ -10,8 +10,6 @@ from __future__ import annotationsimport gcimport loggingimport math-from collections.abc import Iterator-from contextlib import contextmanagerfrom dataclasses import dataclassfrom fractions import Fractionfrom pathlib import Path@@ -101,19 +99,6 @@ def _empty_cuda_cache() -> None:torch.cuda.empty_cache()-@contextmanager-def _denoiser_on_device(denoiser: Denoiser, device: str) -> Iterator[None]:- """Keep one denoiser resident and Turbo-fused for one safe stage."""-- try:- denoiser.prepare_on_device(device)- _empty_cuda_cache()- yield- finally:- denoiser.model.to("cpu")- _empty_cuda_cache()--def _bf16_autocast():"""Match Lightning's ``bf16-mixed`` inference context without Lightning."""@@ -185,7 +170,7 @@ def _denoise_rcp(# before the transformer blocks reach their peak allocation.pose_feature_batch = pose_features.allocate_group(len(camera_ids), "cpu")pose_features.copy_group(tuple(range(len(camera_ids))), pose_feature_batch)- null_pose_feature = pose_features.null_on(device)+ null_pose_feature = pose_features.null_featureswith torch.inference_mode(), _bf16_autocast():for step_index, _ in enumerate(tqdm(denoiser.scheduler.timesteps, desc=f"RCP 1-to-{len(camera_ids)}")):@@ -233,7 +218,7 @@ def _denoise_targets_single(latents = initial_latentssource = src_latents.to(dtype=denoiser.dtype, device=device)context = context.to(dtype=denoiser.dtype, device=device)- null_pose_feature = pose_features.null_on(device)+ null_pose_feature = pose_features.null_featuresgroup_size = len(routes[0][0])pose_feature_batch = pose_features.allocate_group(group_size, "cpu")@@ -394,20 +379,22 @@ def generate_views(target_pose_features = pose_cache.targetdel pose_cache- with metrics.stage("model_load"):- denoiser = (- load_denoiser(- checkpoint_path=checkpoint_path,- turbo_lora_path=turbo_lora_path,- profile=denoising_profile,- attention_backend=attention_backend,+ denoiser = None+ vae = None+ try:+ with metrics.stage("model_load"):+ denoiser = (+ load_denoiser(+ checkpoint_path=checkpoint_path,+ turbo_lora_path=turbo_lora_path,+ profile=denoising_profile,+ attention_backend=attention_backend,+ )+ if plan.needs_primary_denoiser+ else None)- if plan.needs_primary_denoiser- else None- )- vae = VaeExecutor.load(assets.vae, plan.candidate_devices)+ vae = VaeExecutor.load(assets.vae, plan.candidate_devices)- try:with metrics.stage("source_encode"):source_video = _channels_last_source_layout(conditioning.load_source_tensor())source_latents = vae.encode(source_video)@@ -418,7 +405,9 @@ def generate_views(if plan.view_plan.enable_rcp:if denoiser is None or rcp_pose_features is None:raise RuntimeError("RCP requires a primary denoiser and proposal pose features.")- with metrics.stage("rcp_denoise"), _denoiser_on_device(denoiser, plan.primary_device):+ with metrics.stage("rcp_denoise"):+ denoiser.prepare_on_device(plan.primary_device)+ _empty_cuda_cache()rcp_latents = _denoise_rcp(denoiser=denoiser,vae=vae,@@ -430,8 +419,11 @@ def generate_views(device=plan.primary_device,)# Target references use null pose features, not the RCP bank.- # Drop its sole owner before the DiT returns to host memory.del rcp_pose_features+ # Only single-GPU target generation reuses the parent's DiT.+ if plan.distributed:+ denoiser = None+ _empty_cuda_cache()with metrics.stage("rcp_latent_handoff"):target_sources = torch.cat([source_latents, rcp_latents[:4]], dim=0)del rcp_latents@@ -451,8 +443,6 @@ def generate_views(device="cpu",)if plan.distributed:- denoiser = None- _empty_cuda_cache()target_latents, parallelism = _denoise_targets_multi_gpu(checkpoint_path=checkpoint_path,turbo_lora_path=turbo_lora_path,@@ -469,17 +459,20 @@ def generate_views(else:if denoiser is None:raise RuntimeError("Single-GPU target generation requires a primary-process denoiser.")- with _denoiser_on_device(denoiser, plan.primary_device):- target_latents = _denoise_targets_single(- denoiser=denoiser,- src_latents=target_sources,- context=context,- pose_features=target_pose_features,- initial_latents=initial_latents,- routes=routes,- device=plan.primary_device,- )+ if not plan.view_plan.enable_rcp:+ denoiser.prepare_on_device(plan.primary_device)+ _empty_cuda_cache()+ target_latents = _denoise_targets_single(+ denoiser=denoiser,+ src_latents=target_sources,+ context=context,+ pose_features=target_pose_features,+ initial_latents=initial_latents,+ routes=routes,+ device=plan.primary_device,+ )denoiser = None+ _empty_cuda_cache()del initial_latentsif parallelism is not None:@@ -513,7 +506,9 @@ def generate_views(parallelism=parallelism,)finally:- vae.close()+ denoiser = None+ if vae is not None:+ vae.close()_empty_cuda_cache()return resultdiff --git a/fdanyone/vendor/diffsynth/UPSTREAM.md b/fdanyone/vendor/diffsynth/UPSTREAM.mdindex 02ffd09..ef058ca 100644--- a/fdanyone/vendor/diffsynth/UPSTREAM.md+++ b/fdanyone/vendor/diffsynth/UPSTREAM.md@@ -13,6 +13,8 @@ The research fork revision was not anonymously reachable when the release contraThe reader inference path bounds the temporary FP64 RoPE workspace and reuses PoseEncoder/FFN activation storage when gradients are disabled. These release-specific memory-lifetime changes preserve checkpoint parameter keys and the full-group attention and FFN matrix-multiplication shapes. The offline UMT5 conversion implementation used to generate the frozen prompt asset is development-only and not part of the reader distribution; it retains this license and provenance.+The conditioning builder prepares PoseEncoder's contiguous temporal-prefix input directly. Inference DiT blocks own and update one residual stream; target and null pose banks are consumed before those blocks. VAE causal convolutions centralize compact temporal caches at the autocast input boundary, while completed branch outputs and expanded layouts reuse storage. These changes retain normalization/activation precision and the original temporal chunk boundaries.+To reproduce the retained research sources before pruning:```bashdiff --git a/fdanyone/vendor/diffsynth/models/wan_video_dit.py b/fdanyone/vendor/diffsynth/models/wan_video_dit.pyindex dba175b..6284d2f 100644--- a/fdanyone/vendor/diffsynth/models/wan_video_dit.py+++ b/fdanyone/vendor/diffsynth/models/wan_video_dit.py@@ -310,6 +310,21 @@ class DiTBlock(nn.Module):hidden = gelu_tanh(hidden)return self.ffn[2](hidden)+ @staticmethod+ def _add_residual(x: torch.Tensor, branch: torch.Tensor, gate: torch.Tensor | None = None) -> torch.Tensor:+ """Update the inference-owned token stream after a branch has consumed it.++ Keep multiplication and addition separate, including their BF16 rounding.+ Reusing the stream also prevents the caller from retaining an obsolete+ block input while the FFN creates its much larger hidden activation.+ """++ if torch.is_grad_enabled():+ return x + (branch if gate is None else gate * branch)+ if gate is not None:+ branch.mul_(gate)+ return x.add_(branch)+def _multiview_attention(self,x: torch.Tensor,@@ -350,27 +365,26 @@ class DiTBlock(nn.Module):self.modulation.to(dtype=time_modulation.dtype, device=time_modulation.device) + time_modulation).chunk(6, dim=1)- x = x + gate_msa * self.self_attn(- normalized_modulation(self.norm1, x, shift_msa, scale_msa),- spatial_freqs,+ x = self._add_residual(+ x,+ self.self_attn(normalized_modulation(self.norm1, x, shift_msa, scale_msa), spatial_freqs),+ gate_msa,)shift_mvs, scale_mvs, gate_mvs = (self.modulation_mvs.to(dtype=time_modulation.dtype, device=time_modulation.device)+ time_modulation[:, :3, :]).chunk(3, dim=1)- x = x + gate_mvs * self._multiview_attention(+ x = self._add_residual(x,- shift_mvs,- scale_mvs,- multiview_freqs,- shape,+ self._multiview_attention(x, shift_mvs, scale_mvs, multiview_freqs, shape),+ gate_mvs,)- x = x + self.cross_attn(self.norm3(x), repeat(context, "1 l c -> v l c", v=x.shape[0]))+ x = self._add_residual(x, self.cross_attn(self.norm3(x), repeat(context, "1 l c -> v l c", v=x.shape[0])))residual = self._feed_forward(normalized_modulation(self.norm2, x, shift_mlp, scale_mlp))- return x + gate_mlp * residual+ return self._add_residual(x, residual, gate_mlp)class Head(nn.Module):@@ -543,21 +557,23 @@ class FourDAnyoneDiT(nn.Module):return x, packed_views@staticmethod- def _add_target_pose_features_streamed(+ def _add_pose_bank(x: torch.Tensor,pose_features: torch.Tensor,- target_views: int,- grid_size: tuple[int, int, int],) -> None:- """Stage one CPU pose feature at a time into patch-token storage."""+ """Consume a pose bank without keeping it on the GPU during the blocks."""- frames, height, width = grid_size+ if pose_features.device == x.device:+ x.add_(rearrange(pose_features, "v c f h w -> v (f h w) c"))+ return+ if pose_features.device.type != "cpu":+ raise ValueError(f"Inference pose features must be on CPU or {x.device}, got {pose_features.device}.")staging = torch.empty(- (MODEL_DIM, frames, height, width),+ pose_features.shape[1:],dtype=x.dtype,device=x.device,)- for view_index in range(target_views):+ for view_index in range(pose_features.shape[0]):staging.copy_(pose_features[view_index])pose_tokens = rearrange(staging, "c f h w -> (f h w) c")x[view_index].add_(pose_tokens)@@ -578,25 +594,14 @@ class FourDAnyoneDiT(nn.Module):raise ValueError(f"Expected pose features {expected_pose}, got {tuple(pose_features.shape)}.")if tuple(null_pose_feature.shape) != expected_null:raise ValueError(f"Expected null pose features {expected_null}, got {tuple(null_pose_feature.shape)}.")- null_tokens = rearrange(null_pose_feature, "v c f h w -> v (f h w) c")if torch.is_grad_enabled():- if pose_features.device != x.device:+ if pose_features.device != x.device or null_pose_feature.device != x.device:raise ValueError("Training requires pose features on the same device as patch tokens.")pose_tokens = rearrange(pose_features, "v c f h w -> v (f h w) c")+ null_tokens = rearrange(null_pose_feature, "v c f h w -> v (f h w) c")return torch.cat([x[:target_views] + pose_tokens, x[target_views:] + null_tokens], dim=0)- if pose_features.device == x.device:- pose_tokens = rearrange(pose_features, "v c f h w -> v (f h w) c")- x[:target_views].add_(pose_tokens)- else:- if pose_features.device.type != "cpu":- raise ValueError(f"Inference pose features must be on CPU or {x.device}, got {pose_features.device}.")- FourDAnyoneDiT._add_target_pose_features_streamed(- x,- pose_features,- target_views,- grid_size,- )- x[target_views:].add_(null_tokens)+ FourDAnyoneDiT._add_pose_bank(x[:target_views], pose_features)+ FourDAnyoneDiT._add_pose_bank(x[target_views:], null_pose_feature)return xdef forward(diff --git a/fdanyone/vendor/diffsynth/models/wan_video_pose_encoder.py b/fdanyone/vendor/diffsynth/models/wan_video_pose_encoder.pyindex b2bb516..8d3cd2e 100644--- a/fdanyone/vendor/diffsynth/models/wan_video_pose_encoder.py+++ b/fdanyone/vendor/diffsynth/models/wan_video_pose_encoder.py@@ -9,6 +9,8 @@ from torch.nn import initclass PoseEncoder(nn.Module):+ temporal_prefix = 3+def __init__(self, out_dim=5120, in_channels=3):super().__init__()@@ -71,12 +73,11 @@ class PoseEncoder(nn.Module):def forward(self, x: torch.Tensor) -> torch.Tensor:"""- x: (B, C, F, H, W) -> latent grid matching the DiT patch tokens.+ x: contiguous (B, C, F + 3, H, W), with three copies of the first+ frame prepended by the conditioning input builder. Preparing this+ final layout directly avoids retaining a second full video batch.Wan2.1 uses F/4, H/16, W/16; Wan2.2-TI2V-5B uses F/4, H/32, W/32."""- # Wan pattern: 1 -> 4 -> 4 -> ...- x = torch.cat([x[:, :, :1].repeat(1, 1, 3, 1, 1), x], dim=2)-x = self.conv_layers(x)x = self.final_proj(x)return x * self.scalediff --git a/fdanyone/vendor/diffsynth/models/wan_video_vae.py b/fdanyone/vendor/diffsynth/models/wan_video_vae.pyindex 9569c2d..939246e 100644--- a/fdanyone/vendor/diffsynth/models/wan_video_vae.py+++ b/fdanyone/vendor/diffsynth/models/wan_video_vae.py@@ -41,6 +41,10 @@ class CausalConv3d(nn.Conv3d):self.padding = (0, 0, 0)def forward(self, x, cache_x=None):+ return self._forward_prepared(self.prepare_input(x), cache_x)++ def _forward_prepared(self, x, cache_x):+ """Convolve an input already converted to the consumer's precision."""padding = list(self._padding)if cache_x is not None and self._padding[4] > 0:cache_x = cache_x.to(x.device)@@ -50,6 +54,37 @@ class CausalConv3d(nn.Conv3d):return super().forward(x)+ @staticmethod+ def prepare_input(x):+ """Cast at the convolution boundary, before pure copies and padding.++ Normalization and activation retain their original precision. Cached+ inference inputs need only the precision consumed by the convolution.+ """+ if not torch.is_grad_enabled() and torch.is_autocast_enabled(x.device.type):+ return x.to(dtype=torch.get_autocast_dtype(x.device.type))+ return x++ def forward_cached(self, x, feat_cache, feat_idx):+ """Consume the previous temporal context and retain a compact successor."""+ x = self.prepare_input(x)+ idx = feat_idx[0]+ previous = feat_cache[idx]+ tail = x[:, :, -CACHE_T:].clone()+ if tail.shape[2] < CACHE_T and previous is not None:+ tail = torch.cat([previous[:, :, -1:].to(x.device), tail], dim=2)+ output = self._forward_prepared(x, previous)+ feat_cache[idx] = tail+ feat_idx[0] += 1+ return output+++def add_residual(x, shortcut):+ """Reuse a completed branch output without changing its shortcut input."""+ if torch.is_grad_enabled():+ return x + shortcut+ return x.add_(shortcut)+class RMS_norm(nn.Module):@@ -283,21 +318,10 @@ class ResidualBlock(nn.Module):h = self.shortcut(x)for layer in self.residual:if check_is_instance(layer, CausalConv3d) and feat_cache is not None:- idx = feat_idx[0]- cache_x = x[:, :, -CACHE_T:, :, :].clone()- if cache_x.shape[2] < 2 and feat_cache[idx] is not None:- # cache last frame of last two chunk- cache_x = torch.cat([- feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(- cache_x.device), cache_x- ],- dim=2)- x = layer(x, feat_cache[idx])- feat_cache[idx] = cache_x- feat_idx[0] += 1+ x = layer.forward_cached(x, feat_cache, feat_idx)else:x = layer(x)- return x + h+ return add_residual(x, h)class AttentionBlock(nn.Module):@@ -338,7 +362,7 @@ class AttentionBlock(nn.Module):# outputx = self.proj(x)x = rearrange(x, '(b t) c h w-> b c t h w', t=t)- return x + identity+ return add_residual(x, identity)class AvgDown3D(nn.Module):@@ -414,8 +438,9 @@ class DupUp3D(nn.Module):self.repeats = out_channels * self.factor // in_channelsdef forward(self, x: torch.Tensor, first_chunk=False) -> torch.Tensor:- x = x.repeat_interleave(self.repeats, dim=1)- x = x.view(+ # Broadcast channel repetitions as a view. Materialize only the final+ # temporal/spatial layout, rather than a repeated intermediate too.+ x = x.unsqueeze(2).expand(-1, -1, self.repeats, -1, -1, -1).reshape(x.size(0),self.out_channels,self.factor_t,@@ -466,11 +491,11 @@ class Down_ResidualBlock(nn.Module):self.downsamples = nn.Sequential(*downsamples)def forward(self, x, feat_cache=None, feat_idx=[0]):- x_copy = x.clone()+ shortcut_input = xfor module in self.downsamples:x = module(x, feat_cache, feat_idx)- return x + self.avg_shortcut(x_copy)+ return add_residual(x, self.avg_shortcut(shortcut_input))class Up_ResidualBlock(nn.Module):@@ -503,12 +528,12 @@ class Up_ResidualBlock(nn.Module):self.upsamples = nn.Sequential(*upsamples)def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False):- x_main = x.clone()+ x_main = xfor module in self.upsamples:x_main = module(x_main, feat_cache, feat_idx)if self.avg_shortcut is not None:x_shortcut = self.avg_shortcut(x, first_chunk)- return x_main + x_shortcut+ return add_residual(x_main, x_shortcut)else:return x_main@@ -567,18 +592,7 @@ class Encoder3d(nn.Module):def forward(self, x, feat_cache=None, feat_idx=[0]):if feat_cache is not None:- idx = feat_idx[0]- cache_x = x[:, :, -CACHE_T:, :, :].clone()- if cache_x.shape[2] < 2 and feat_cache[idx] is not None:- # cache last frame of last two chunk- cache_x = torch.cat([- feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(- cache_x.device), cache_x- ],- dim=2)- x = self.conv1(x, feat_cache[idx])- feat_cache[idx] = cache_x- feat_idx[0] += 1+ x = self.conv1.forward_cached(x, feat_cache, feat_idx)else:x = self.conv1(x)@@ -599,18 +613,7 @@ class Encoder3d(nn.Module):## headfor layer in self.head:if check_is_instance(layer, CausalConv3d) and feat_cache is not None:- idx = feat_idx[0]- cache_x = x[:, :, -CACHE_T:, :, :].clone()- if cache_x.shape[2] < 2 and feat_cache[idx] is not None:- # cache last frame of last two chunk- cache_x = torch.cat([- feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(- cache_x.device), cache_x- ],- dim=2)- x = layer(x, feat_cache[idx])- feat_cache[idx] = cache_x- feat_idx[0] += 1+ x = layer.forward_cached(x, feat_cache, feat_idx)else:x = layer(x)return x@@ -678,19 +681,7 @@ class Encoder3d_38(nn.Module):def forward(self, x, feat_cache=None, feat_idx=[0]):if feat_cache is not None:- idx = feat_idx[0]- cache_x = x[:, :, -CACHE_T:, :, :].clone()- if cache_x.shape[2] < 2 and feat_cache[idx] is not None:- cache_x = torch.cat(- [- feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device),- cache_x,- ],- dim=2,- )- x = self.conv1(x, feat_cache[idx])- feat_cache[idx] = cache_x- feat_idx[0] += 1+ x = self.conv1.forward_cached(x, feat_cache, feat_idx)else:x = self.conv1(x)@@ -710,22 +701,8 @@ class Encoder3d_38(nn.Module):## headfor layer in self.head:- if isinstance(layer, CausalConv3d) and feat_cache is not None:- idx = feat_idx[0]- cache_x = x[:, :, -CACHE_T:, :, :].clone()- if cache_x.shape[2] < 2 and feat_cache[idx] is not None:- cache_x = torch.cat(- [- feat_cache[idx][:, :, -1, :, :]- .unsqueeze(2)- .to(cache_x.device),- cache_x,- ],- dim=2,- )- x = layer(x, feat_cache[idx])- feat_cache[idx] = cache_x- feat_idx[0] += 1+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:+ x = layer.forward_cached(x, feat_cache, feat_idx)else:x = layer(x)@@ -788,18 +765,7 @@ class Decoder3d(nn.Module):def forward(self, x, feat_cache=None, feat_idx=[0]):## conv1if feat_cache is not None:- idx = feat_idx[0]- cache_x = x[:, :, -CACHE_T:, :, :].clone()- if cache_x.shape[2] < 2 and feat_cache[idx] is not None:- # cache last frame of last two chunk- cache_x = torch.cat([- feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(- cache_x.device), cache_x- ],- dim=2)- x = self.conv1(x, feat_cache[idx])- feat_cache[idx] = cache_x- feat_idx[0] += 1+ x = self.conv1.forward_cached(x, feat_cache, feat_idx)else:x = self.conv1(x)@@ -820,18 +786,7 @@ class Decoder3d(nn.Module):## headfor layer in self.head:if check_is_instance(layer, CausalConv3d) and feat_cache is not None:- idx = feat_idx[0]- cache_x = x[:, :, -CACHE_T:, :, :].clone()- if cache_x.shape[2] < 2 and feat_cache[idx] is not None:- # cache last frame of last two chunk- cache_x = torch.cat([- feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(- cache_x.device), cache_x- ],- dim=2)- x = layer(x, feat_cache[idx])- feat_cache[idx] = cache_x- feat_idx[0] += 1+ x = layer.forward_cached(x, feat_cache, feat_idx)else:x = layer(x)return x@@ -887,19 +842,7 @@ class Decoder3d_38(nn.Module):def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False):if feat_cache is not None:- idx = feat_idx[0]- cache_x = x[:, :, -CACHE_T:, :, :].clone()- if cache_x.shape[2] < 2 and feat_cache[idx] is not None:- cache_x = torch.cat(- [- feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device),- cache_x,- ],- dim=2,- )- x = self.conv1(x, feat_cache[idx])- feat_cache[idx] = cache_x- feat_idx[0] += 1+ x = self.conv1.forward_cached(x, feat_cache, feat_idx)else:x = self.conv1(x)@@ -919,21 +862,7 @@ class Decoder3d_38(nn.Module):## headfor layer in self.head:if check_is_instance(layer, CausalConv3d) and feat_cache is not None:- idx = feat_idx[0]- cache_x = x[:, :, -CACHE_T:, :, :].clone()- if cache_x.shape[2] < 2 and feat_cache[idx] is not None:- cache_x = torch.cat(- [- feat_cache[idx][:, :, -1, :, :]- .unsqueeze(2)- .to(cache_x.device),- cache_x,- ],- dim=2,- )- x = layer(x, feat_cache[idx])- feat_cache[idx] = cache_x- feat_idx[0] += 1+ x = layer.forward_cached(x, feat_cache, feat_idx)else:x = layer(x)return x