Python
added scail support
DeepBeepMeep2f5319e9931a
diff --git a/models/flux/model.py b/models/flux/model.pyindex c83b709..79ba5ee 100644--- a/models/flux/model.py+++ b/models/flux/model.py@@ -206,9 +206,18 @@ class Flux(nn.Module):shift, scale = weight.chunk(2, dim=0)new_weight = torch.cat([scale, shift], dim=0)return new_weight+ lora_unet = False+ diffusers = False+ for k in sd.keys():+ if "lora_unet_" in k:+ lora_unet = True+ break+ elif "single_transformer_blocks" in k or "transformer_blocks" in k:+ diffusers = True+ breakfirst_key= next(iter(sd))- if first_key.startswith("lora_unet_"):+ if lora_unet:new_sd = {}print("Converting Lora Safetensors format to Lora Diffusers format")repl_list = ["linear1", "linear2", "modulation", "img_attn", "txt_attn", "img_mlp", "txt_mlp", "img_mod", "txt_mod"]@@ -231,40 +240,44 @@ class Flux(nn.Module):new_sd[k] = v- elif first_key.startswith("transformer."):+ elif diffusers:root_src = ["time_text_embed.timestep_embedder.linear_1", "time_text_embed.timestep_embedder.linear_2", "time_text_embed.text_embedder.linear_1", "time_text_embed.text_embedder.linear_2","time_text_embed.guidance_embedder.linear_1", "time_text_embed.guidance_embedder.linear_2",- "x_embedder", "context_embedder", "proj_out" ]+ "x_embedder", "context_embedder", "proj_out", "time_guidance_embed.timestep_embedder.linear_1", "time_guidance_embed.timestep_embedder.linear_2" ]root_tgt = ["time_in.in_layer", "time_in.out_layer", "vector_in.in_layer", "vector_in.out_layer","guidance_in.in_layer", "guidance_in.out_layer",- "img_in", "txt_in", "final_layer.linear" ]+ "img_in", "txt_in", "final_layer.linear", "time_in.in_layer", "time_in.out_layer" ]- double_src = ["norm1.linear", "norm1_context.linear", "attn.norm_q", "attn.norm_k", "ff.net.0.proj", "ff.net.2", "ff_context.net.0.proj", "ff_context.net.2", "attn.to_out.0" ,"attn.to_add_out", "attn.to_out", ".attn.to_", ".attn.add_q_proj.", ".attn.add_k_proj.", ".attn.add_v_proj.", ]- double_tgt = ["img_mod.lin", "txt_mod.lin", "img_attn.norm.query_norm", "img_attn.norm.key_norm", "img_mlp.0", "img_mlp.2", "txt_mlp.0", "txt_mlp.2", "img_attn.proj", "txt_attn.proj", "img_attn.proj", ".img_attn.", ".txt_attn.q.", ".txt_attn.k.", ".txt_attn.v."]+ double_src = ["norm1.linear", "norm1_context.linear", "attn.norm_q", "attn.norm_k", "ff.net.0.proj", "ff.net.2", "ff_context.net.0.proj", "ff_context.net.2", "attn.to_out.0" ,"attn.to_add_out", "attn.to_out", ".attn.to_", ".attn.add_q_proj.", ".attn.add_k_proj.", ".attn.add_v_proj.", ".ff_context.linear_out.", ".ff_context.linear_in.", ".ff.linear_out.", ".ff.linear_in." ]+ double_tgt = ["img_mod.lin", "txt_mod.lin", "img_attn.norm.query_norm", "img_attn.norm.key_norm", "img_mlp.0", "img_mlp.2", "txt_mlp.0", "txt_mlp.2", "img_attn.proj", "txt_attn.proj", "img_attn.proj", ".img_attn.", ".txt_attn.q.", ".txt_attn.k.", ".txt_attn.v.", ".txt_mlp.0.", ".txt_mlp.2.", ".img_mlp.0.", ".img_mlp.2." ]- single_src = ["norm.linear", "attn.norm_q", "attn.norm_k", "proj_out",".attn.to_q.", ".attn.to_k.", ".attn.to_v.", ".proj_mlp."]- single_tgt = ["modulation.lin","norm.query_norm", "norm.key_norm", "linear2", ".linear1_attn_q.", ".linear1_attn_k.", ".linear1_attn_v.", ".linear1_mlp."]+ single_src = ["norm.linear", "attn.norm_q", "attn.norm_k", "proj_out",".attn.to_q.", ".attn.to_k.", ".attn.to_v.", ".proj_mlp.", ".attn.to_out."]+ single_tgt = ["modulation.lin","norm.query_norm", "norm.key_norm", "linear2", ".linear1_attn_q.", ".linear1_attn_k.", ".linear1_attn_v.", ".linear1_mlp.", ".linear2."]for k,v in sd.items():- if k.startswith("transformer.single_transformer_blocks"):- k = k.replace("transformer.single_transformer_blocks", "diffusion_model.single_blocks")+ if k.startswith("transformer."):+ k = k.replace("transformer.", "")+ if k.startswith("single_transformer_blocks"):+ k = k.replace("single_transformer_blocks", "single_blocks")for src, tgt in zip(single_src, single_tgt):k = k.replace(src, tgt)- elif k.startswith("transformer.transformer_blocks"):- k = k.replace("transformer.transformer_blocks", "diffusion_model.double_blocks")+ elif k.startswith("transformer_blocks"):+ k = k.replace("transformer_blocks", "double_blocks")for src, tgt in zip(double_src, double_tgt):k = k.replace(src, tgt)else:- k = k.replace("transformer.", "diffusion_model.")for src, tgt in zip(root_src, root_tgt):k = k.replace(src, tgt)if "norm_out.linear" in k:if "lora_B" in k:v = swap_scale_shift(v)- k = k.replace("norm_out.linear", "final_layer.adaLN_modulation.1")+ k = k.replace("norm_out.linear", "final_layer.adaLN_modulation.1")+ if not k.startswith("diffusion_model."):+ k = "diffusion_model." + k+new_sd[k] = v# elif not first_key.startswith("diffusion_model.") and not first_key.startswith("transformer."):# for k,v in sd.items():diff --git a/models/wan/any2video.py b/models/wan/any2video.pyindex e81303e..6b53603 100644--- a/models/wan/any2video.py+++ b/models/wan/any2video.py@@ -529,22 +529,25 @@ class WanAny2V:lucy_edit= model_type in ["lucy_edit"]animate= model_type in ["animate"]chrono_edit = model_type in ["chrono_edit"]- mocha = model_type in ["mocha"]- steadydancer = model_type in ["steadydancer"]- wanmove = model_type in ["wanmove"]+ mocha = model_type in ["mocha"]+ steadydancer = model_type in ["steadydancer"]+ wanmove = model_type in ["wanmove"]+ scail = model_type in ["scail"]start_step_no = 0ref_images_count = inner_latent_frames = 0trim_frames = 0last_latent_preview = Falseextended_overlapped_latents = clip_image_start = clip_image_end = image_mask_latents = latent_slice = freqs = None- no_noise_latents_injection = infinitetalk+ # SCAIL uses a fixed ref latent frame that should not be noised.+ no_noise_latents_injection = infinitetalk or scailtimestep_injection = False+ ps_t, ps_h, ps_w = self.model.patch_sizelat_frames = int((frame_num - 1) // self.vae_stride[0]) + 1extended_input_dim = 0ref_images_before = False# image2video- if model_def.get("i2v_class", False) and not animate:+ if model_def.get("i2v_class", False) and not (animate or scail):any_end_frame = Falseif infinitetalk:new_shot = "0" in video_prompt_type@@ -716,7 +719,59 @@ class WanAny2V:ref_images_before = Trueref_images_count = 1lat_frames = int((input_frames.shape[1] - 1) // self.vae_stride[0]) + 1-++ # SCAIL - 3D pose-guided character animation+ if scail:+ pose_pixels = input_frames+ image_ref = input_ref_images[0].to(self.device) if input_ref_images is not None else convert_image_to_tensor(pre_video_frame).unsqueeze(1).to(self.device)+ insert_start_frames = window_start_frame_no + prefix_frames_count > 1+ if insert_start_frames:+ ref_latents = self.vae.encode([image_ref], VAE_tile_size)[0].unsqueeze(0)+ start_frames = input_video.to(self.device)+ color_reference_frame = input_video[:, :1].to(self.device)+ start_latents = self.vae.encode([start_frames], VAE_tile_size)[0].unsqueeze(0)+ extended_overlapped_latents = torch.cat([ref_latents, start_latents], dim=2)+ start_latents = None+ else:+ # sigma = torch.exp(torch.normal(mean=-2.5, std=0.5, size=(1,), device=self.device)).to(image_ref.dtype)+ sigma = torch.exp(torch.normal(mean=-5.0, std=0.5, size=(1,), device=self.device)).to(image_ref.dtype)+ noisy_ref = image_ref + torch.randn_like(image_ref) * sigma+ ref_latents = self.vae.encode([noisy_ref], VAE_tile_size)[0].unsqueeze(0)+ extended_overlapped_latents = ref_latents++ lat_h, lat_w = height // self.vae_stride[1], width // self.vae_stride[2]+ pose_frames = pose_pixels.shape[1]+ lat_t = int((pose_frames - 1) // self.vae_stride[0]) + 1+ msk_ref = self.get_i2v_mask(lat_h, lat_w, nb_frames_unchanged=1, lat_t=1, device=self.device)+ msk_control = self.get_i2v_mask(lat_h, lat_w, nb_frames_unchanged=prefix_frames_count if insert_start_frames else 0, lat_t=lat_t, device=self.device)+ y = torch.concat([msk_ref, msk_control], dim=1)+ # Downsample pose video by 0.5x before VAE encoding (matches `smpl_downsample` in upstream configs)+ pose_pixels_ds = pose_pixels.permute(1, 0, 2, 3)+ toto = [pose_pixels]+ pose_pixels_ds = F.interpolate( pose_pixels_ds, size=(max(1, pose_pixels.shape[-2] // 2), max(1, pose_pixels.shape[-1] // 2)), mode="bilinear", align_corners=False, ).permute(1, 0, 2, 3)+ pose_latents = self.vae.encode([pose_pixels_ds], VAE_tile_size)[0].unsqueeze(0)++ clip_image_start = image_ref.squeeze(1)+ kwargs.update({"y": y, "scail_pose_latents": pose_latents, "ref_images_count": 1})++ pose_grid_t = pose_latents.shape[2] // ps_t+ pose_rope_h = lat_h // ps_h+ pose_rope_w = lat_w // ps_w+ pose_freqs_cos, pose_freqs_sin = get_nd_rotary_pos_embed( (ref_images_count, 0, 120), (ref_images_count + pose_grid_t, pose_rope_h, 120 + pose_rope_w), (pose_grid_t, pose_rope_h, pose_rope_w), L_test = lat_t, enable_riflex = enable_RIFLEx)++ head_dim = pose_freqs_cos.shape[1]+ pose_freqs_cos = pose_freqs_cos.view(pose_grid_t, pose_rope_h, pose_rope_w, head_dim).permute(0, 3, 1, 2)+ pose_freqs_sin = pose_freqs_sin.view(pose_grid_t, pose_rope_h, pose_rope_w, head_dim).permute(0, 3, 1, 2)++ pose_freqs_cos = F.avg_pool2d(pose_freqs_cos, kernel_size=2, stride=2).permute(0, 2, 3, 1).reshape(-1, head_dim)+ pose_freqs_sin = F.avg_pool2d(pose_freqs_sin, kernel_size=2, stride=2).permute(0, 2, 3, 1).reshape(-1, head_dim)+ post_freqs = (pose_freqs_cos, pose_freqs_sin)++ pose_pixels = pose_pixels_ds = pose_freqs_cos_full = None+ ref_images_before = True+ ref_images_count = 1+ lat_frames = lat_t+# Clip imageif hasattr(self, "clip") and clip_image_start is not None:clip_image_size = self.clip.model.image_size@@ -926,6 +981,9 @@ class WanAny2V:else:freqs = get_rotary_pos_embed( (target_shape[1]+ inner_latent_frames ,) + target_shape[2:] , enable_RIFLEx= enable_RIFLEx)+ if post_freqs is not None:+ freqs = ( torch.cat([freqs[0], post_freqs[0]]), torch.cat([freqs[1], post_freqs[1]]) )+kwargs["freqs"] = freqs@@ -1230,6 +1288,8 @@ class WanAny2V:clear()if timestep_injection:latents[:, :, :source_latents.shape[2]] = source_latents+ if extended_overlapped_latents != None:+ latents[:, :, :extended_overlapped_latents.shape[2]] = extended_overlapped_latentsif ref_images_before and ref_images_count > 0: latents = latents[:, :, ref_images_count:]if trim_frames > 0: latents= latents[:, :,:-trim_frames]@@ -1297,4 +1357,3 @@ class WanAny2V:if len(preloadURLs) > model_mode:return [fl.locate_file(os.path.basename(preloadURLs[model_mode]))] , [1]return [], []-diff --git a/models/wan/modules/model.py b/models/wan/modules/model.pyindex ba81dce..5d302d4 100644--- a/models/wan/modules/model.py+++ b/models/wan/modules/model.py@@ -19,6 +19,7 @@ from ..multitalk.multitalk_utils import get_attn_map_with_targetfrom ..animate.motion_encoder import Generatorfrom ..animate.face_blocks import FaceAdapter, FaceEncoderfrom ..animate.model_animate import after_patch_embedding+from ..scail.model_scail import build_scail_pose_tokensfrom ..steadydancer.small_archs import FactorConv3d, PoseRefNetNoBNV3from ..steadydancer.mobilenetv2_dcd import DYModule@@ -916,13 +917,17 @@ class WanModel(ModelMixin, ConfigMixin):if not k.startswith("vae."):new_sd[k] = vreturn new_sd- def preprocess_loras(self, model_type, sd):+ def preprocess_loras(self, base_model_type, sd):first = next(iter(sd), None)if first == None:return sd-+ if base_model_type in ["scail"]:+ sd.pop("diffusion_model.patch_embedding.diff", None)+ sd.pop("diffusion_model.patch_embedding.diff_b", None)+ return sd+new_sd = {}for k,v in sd.items():if k.endswith("modulation.diff"):@@ -978,7 +983,7 @@ class WanModel(ModelMixin, ConfigMixin):sd = new_sdfrom wgp import test_class_i2v- if not test_class_i2v(model_type) or model_type in ["i2v_2_2"]:+ if not test_class_i2v(base_model_type) or base_model_type in ["i2v_2_2"]:new_sd = {}# convert loras for i2v to t2vfor k,v in sd.items():@@ -1031,6 +1036,7 @@ class WanModel(ModelMixin, ConfigMixin):motion_encoder_dim=0,lynx=None,steadydancer = False,+ scail = False,):super().__init__()@@ -1063,7 +1069,8 @@ class WanModel(ModelMixin, ConfigMixin):multitalk = multitalk_output_dim > 0self.multitalk = multitalk- self.steadydancer = steadydancer+ self.steadydancer = steadydancer+ self.scail = scailanimate = motion_encoder_dim > 0# embeddings@@ -1185,6 +1192,13 @@ class WanModel(ModelMixin, ConfigMixin):num_heads=4,)+ if scail:+ # SCAIL only needs pose embedding (no motion_encoder/face_adapter)+ # pose_latents (16 ch) + mask (4 ch) = 20 channels = in_dim+ self.pose_patch_embedding = nn.Conv3d(+ in_dim, dim, kernel_size=patch_size, stride=patch_size+ )+if steadydancer:self.in_dim_c = 16@@ -1449,6 +1463,7 @@ class WanModel(ModelMixin, ConfigMixin):steadydancer_ref_x = None,steadydancer_ref_c = None,steadydancer_clip_fea_c = None,+ scail_pose_latents = None,):# patch_dtype = self.patch_embedding.weight.dtypemodulation_dtype = self.time_projection[1].weight.dtype@@ -1515,9 +1530,13 @@ class WanModel(ModelMixin, ConfigMixin):x_noise_clone = x = Nonemotion_vec_list = []+ pose_tokens = None+ if scail_pose_latents is not None:+ pose_tokens = build_scail_pose_tokens(self, scail_pose_latents, modulation_dtype)+if face_pixel_values is None: face_pixel_values = [None] * len(x_list)for i, (x, one_face_pixel_values) in enumerate(zip(x_list, face_pixel_values)):- # animate embeddings+ # animate/scail embeddingsmotion_vec = Noneif pose_latents is not None:x, motion_vec = after_patch_embedding(self, x, pose_latents, torch.zeros_like(face_pixel_values[0]) if one_face_pixel_values is None else one_face_pixel_values)@@ -1528,6 +1547,11 @@ class WanModel(ModelMixin, ConfigMixin):x = voxel_chunk_no_padding(x, voxel_shape).squeeze(-1).transpose(1, 2)else:x = x.flatten(2).transpose(1, 2)++ if scail_pose_latents is not None:+ if pose_tokens.shape[0] != x.shape[0]: pose_tokens = pose_tokens.repeat(x.shape[0], 1, 1)+ x = torch.cat([x, pose_tokens], dim=1)+x_list[i] = xx = None@@ -1843,5 +1867,4 @@ class WanModel(ModelMixin, ConfigMixin):nn.init.normal_(m.weight, std=.02)# init output layer- nn.init.zeros_(self.head.head.weight)-+ nn.init.zeros_(self.head.head.weight)\ No newline at end of filediff --git a/models/wan/scail/__init__.py b/models/wan/scail/__init__.pynew file mode 100644index 0000000..ac6b329--- /dev/null+++ b/models/wan/scail/__init__.py@@ -0,0 +1,414 @@+from __future__ import annotations++__all__ = ["ScailPoseProcessor"]++import numpy as np+import torch+from PIL import Image, ImageOps++from shared.utils import files_locator as fl+from .nlf import load_multiperson_nlf_eager++from .scail_pose_align3d import solve_new_camera_params_central, solve_new_camera_params_down+from .scail_pose_dwpose import DWposeDetector+from .scail_pose_nlf import (+ collect_smpl_poses,+ intrinsic_matrix_from_field_of_view,+ process_data_to_COCO_format,+ process_video_multi_nlf,+ process_video_nlf,+ recollect_dwposes,+ recollect_nlf,+ render_multi_nlf_as_images,+ render_nlf_as_images,+ scale_faces,+ shift_dwpose_according_to_nlf,+)+from .scail_pose_multi import change_poses_to_limit_num, get_largest_bbox_indices+++def _pil_resample(name: str):+ try:+ return getattr(Image.Resampling, name)+ except AttributeError: # Pillow<9+ return getattr(Image, name)+++_RESAMPLE_LANCZOS = _pil_resample("LANCZOS")+_RESAMPLE_NEAREST = _pil_resample("NEAREST")+++def _tensor_frame_to_uint8_rgb(frame_chw: torch.Tensor) -> np.ndarray:+ frame = frame_chw.detach()+ if frame.dim() != 3:+ raise ValueError(f"Expected CHW tensor, got shape {tuple(frame.shape)}")++ if frame.shape[0] == 1:+ frame = frame.expand(3, -1, -1)+ if frame.shape[0] >= 4:+ frame = frame[:3]++ frame = frame.to(dtype=torch.float32)+ if frame.numel() == 0:+ return np.zeros((0, 0, 3), dtype=np.uint8)++ if float(frame.min()) < 0.0:+ frame = (frame + 1.0) * 127.5+ elif float(frame.max()) <= 1.0:+ frame = frame * 255.0++ frame = frame.clamp(0, 255).to(torch.uint8)+ return frame.permute(1, 2, 0).cpu().numpy()+++def _tensor_mask_to_pil(mask: torch.Tensor) -> Image.Image:+ m = mask.detach()+ if m.dim() == 3:+ m = m[0]+ if m.dim() != 2:+ raise ValueError(f"Expected HW (or 1HW) mask tensor, got shape {tuple(mask.shape)}")++ m = m.to(dtype=torch.float32)+ if m.numel() == 0:+ return Image.fromarray(np.zeros((0, 0), dtype=np.uint8), mode="L")++ if float(m.min()) < 0.0:+ m = (m + 1.0) * 0.5+ elif float(m.max()) > 1.0:+ m = m / 255.0++ m = m.clamp(0.0, 1.0)+ m8 = (m * 255.0).to(torch.uint8).cpu().numpy()+ return Image.fromarray(m8, mode="L")+++class ScailPoseProcessor:+ """+ WanGP wrapper around the official SCAIL-Pose preprocessing pipeline:+ - DWpose (YOLOX+RTMPose) for 2D keypoints + bbox.+ - NLFPose for 3D pose.+ - Taichi cylinder renderer + 2D overlay.+ """++ def __init__(self, gpu_id: int = 0, *, multi_person: bool = False, max_people: int = 2):+ if not torch.cuda.is_available():+ raise RuntimeError("SCAIL pose preprocessing requires CUDA (GPU-only).")++ self.gpu_id = int(gpu_id)+ self.multi_person = bool(multi_person)+ self.max_people = max(1, int(max_people))++ # Some upstream helpers use bare `.cuda()` / default device semantics.+ torch.cuda.set_device(self.gpu_id)+ self.detector = DWposeDetector(use_batch=False).to(self.gpu_id)++ eager_ckpt = fl.locate_file("pose/nlf_l_multi_0.3.2.eager.safetensors")+ yolox_onnx = fl.locate_file("pose/yolox_l.onnx")+ self.model_nlf = load_multiperson_nlf_eager(+ checkpoint_path=eager_ckpt,+ yolox_onnx_path=yolox_onnx,+ device=f'cuda:{self.gpu_id}'+ )++ # Lazy-loaded for multi-person mode.+ self._sam_segmenter = None+ self._matanyone_model = None++ def unload(self):+ """Release NLF model from memory (RAM and VRAM)."""+ import gc++ if hasattr(self, 'model_nlf') and self.model_nlf is not None:+ # Move model to CPU first to free VRAM+ self.model_nlf.to('cpu')+ # Delete the model+ del self.model_nlf+ self.model_nlf = None++ if hasattr(self, 'detector') and self.detector is not None:+ self.detector.to('cpu')+ del self.detector+ self.detector = None++ if getattr(self, "_sam_segmenter", None) is not None:+ try:+ self._sam_segmenter.model.to("cpu")+ except Exception:+ pass+ self._sam_segmenter = None++ if getattr(self, "_matanyone_model", None) is not None:+ try:+ self._matanyone_model.to("cpu")+ except Exception:+ pass+ self._matanyone_model = None++ # Force garbage collection and empty CUDA cache+ gc.collect()+ torch.cuda.empty_cache()++ def _ensure_sam_loaded(self) -> None:+ if self._sam_segmenter is not None:+ return+ from preprocessing.matanyone.tools.base_segmenter import BaseSegmenter++ # `BaseSegmenter` loads weights from `ckpts/mask/*safetensors` via `files_locator`.+ self._sam_segmenter = BaseSegmenter(SAM_checkpoint=None, model_type="vit_h", device=f"cuda:{self.gpu_id}")++ def _ensure_matanyone_loaded(self) -> None:+ if self._matanyone_model is not None:+ return+ from preprocessing.matanyone.matanyone.model.matanyone import MatAnyone++ self._matanyone_model = MatAnyone.from_pretrained(fl.locate_folder("mask")).eval()+ self._matanyone_model.to(f"cuda:{self.gpu_id}")++ def _extract_and_render_multi(+ self,+ vr_frames_np: list[np.ndarray],+ poses_list,+ det_results_list,+ ) -> torch.Tensor:+ if not vr_frames_np:+ return torch.empty((0,), dtype=torch.float32)++ first_bboxes = det_results_list[0] if det_results_list else None+ if not first_bboxes:+ return torch.empty((0,), dtype=torch.float32)++ indices = get_largest_bbox_indices(first_bboxes, self.max_people)+ if not indices:+ return torch.empty((0,), dtype=torch.float32)++ height, width = vr_frames_np[0].shape[:2]+ pose0 = poses_list[0]++ # 1) Build SAM prompts from DWpose (bbox + a few stable keypoints).+ considered_points = {0, 1, 14, 15}+ box_list_px: list[np.ndarray] = []+ points_list_px: list[np.ndarray] = []+ for idx in indices:+ x1, y1, x2, y2 = first_bboxes[idx]+ box_px = np.array([x1 * width, y1 * height, x2 * width, y2 * height], dtype=np.float32)++ candidate = np.asarray(pose0["bodies"]["candidate"][idx], dtype=np.float32)+ subset = np.asarray(pose0["bodies"]["subset"][idx])+ subset_mod = subset.copy()+ for k in range(len(subset_mod)):+ if k not in considered_points:+ subset_mod[k] = -1++ pts = candidate[subset_mod != -1]+ pts = np.asarray(pts, dtype=np.float32).reshape(-1, 2)+ pts = pts[(pts[:, 0] >= 0.0) & (pts[:, 1] >= 0.0)]+ if pts.shape[0] == 0:+ pts = np.array([[(x1 + x2) * 0.5, (y1 + y2) * 0.5]], dtype=np.float32)++ pts_px = pts.copy()+ pts_px[:, 0] *= width+ pts_px[:, 1] *= height++ box_list_px.append(box_px)+ points_list_px.append(pts_px)++ # 2) Initial per-person masks on the first frame (SAM).+ self._ensure_sam_loaded()+ self._sam_segmenter.reset_image()+ self._sam_segmenter.set_image(vr_frames_np[0])++ init_masks: list[np.ndarray] = []+ for box_px, pts_px in zip(box_list_px, points_list_px):+ labels = np.ones((pts_px.shape[0],), dtype=np.int32)+ masks, scores, _logits = self._sam_segmenter.predictor.predict(+ point_coords=pts_px,+ point_labels=labels,+ box=box_px,+ multimask_output=True,+ )+ if masks is None or len(masks) == 0:+ init_masks.append(np.zeros((height, width), dtype=np.uint8))+ continue+ best = int(np.argmax(scores)) if scores is not None and len(scores) > 0 else 0+ init_masks.append(masks[best].astype(np.uint8) * 255)++ # Unload SAM to free VRAM before MatAnyone+ if self._sam_segmenter is not None:+ self._sam_segmenter.reset_image()+ self._sam_segmenter.model.to("cpu")+ del self._sam_segmenter+ self._sam_segmenter = None+ torch.cuda.empty_cache()++ # 3) Track/segment each person across the video (MatAnyone).+ self._ensure_matanyone_loaded()+ from preprocessing.matanyone.matanyone.inference.inference_core import InferenceCore+ from preprocessing.matanyone.matanyone_wrapper import matanyone as matanyone_run++ vr_frames_list = []+ for mask0 in init_masks:+ processor = InferenceCore(self._matanyone_model, cfg=self._matanyone_model.cfg)+ masked_frames, _alpha = matanyone_run(processor, vr_frames_np, mask0)+ vr_frames_list.append(torch.from_numpy(np.stack(masked_frames, axis=0)))+ del processor++ # Unload MatAnyone to free VRAM before NLF+ if self._matanyone_model is not None:+ self._matanyone_model.to("cpu")+ del self._matanyone_model+ self._matanyone_model = None+ torch.cuda.empty_cache()++ # 4) Run NLF per segmented person-video.+ nlf_results = process_video_multi_nlf(self.model_nlf, vr_frames_list)++ # 5) Limit DWpose overlays to the same number of persons for visualization.+ poses_vis, det_vis = change_poses_to_limit_num(list(poses_list), list(det_results_list), num_bboxes=len(indices))+ frames_np_rgba = render_multi_nlf_as_images(nlf_results, poses_vis, reshape_pool=None, intrinsic_matrix=None)++ frames_rgb = np.stack([f[:, :, :3] for f in frames_np_rgba], axis=0).astype(np.float32)+ frames_t = torch.from_numpy(frames_rgb).permute(0, 3, 1, 2) # T,C,H,W+ frames_t = frames_t / 127.5 - 1.0+ return frames_t.permute(1, 0, 2, 3).contiguous()++ def extract_and_render(+ self,+ video_frames: torch.Tensor,+ ref_image: Image.Image,+ mask_frames: torch.Tensor | None = None,+ align_pose: bool = True,+ ) -> torch.Tensor:+ torch.cuda.set_device(self.gpu_id)++ if video_frames is None or not isinstance(video_frames, torch.Tensor):+ raise TypeError("video_frames must be a torch.Tensor")+ if video_frames.dim() != 4:+ raise ValueError(f"Expected video tensor (C,T,H,W), got {tuple(video_frames.shape)}")++ if ref_image is None or not isinstance(ref_image, Image.Image):+ raise TypeError("ref_image must be a PIL.Image")++ out_w, out_h = ref_image.size+ target_size = (int(out_w), int(out_h))++ c, t, h, w = video_frames.shape+ if t == 0:+ return torch.empty((0,), dtype=torch.float32)++ pil_frames: list[Image.Image] = []+ vr_frames_np: list[np.ndarray] = []++ for frame_idx in range(t):+ frame_np = _tensor_frame_to_uint8_rgb(video_frames[:, frame_idx])+ frame_pil = Image.fromarray(frame_np, mode="RGB")++ # Output dimensions must match the ref image; also ensures internal pose extraction+ # resolution is <= output resolution.+ frame_pil = ImageOps.fit(frame_pil, target_size, method=_RESAMPLE_LANCZOS, centering=(0.5, 0.5))++ if mask_frames is not None:+ mask_pil = _tensor_mask_to_pil(mask_frames[:, frame_idx] if mask_frames.dim() == 4 else mask_frames[frame_idx])+ mask_pil = ImageOps.fit(mask_pil, target_size, method=_RESAMPLE_NEAREST, centering=(0.5, 0.5))+ mask_arr = np.array(mask_pil, dtype=np.float32) / 255.0+ rgb_arr = np.array(frame_pil, dtype=np.float32)+ rgb_arr = (rgb_arr * mask_arr[:, :, None]).clip(0, 255).astype(np.uint8)+ frame_pil = Image.fromarray(rgb_arr, mode="RGB")++ pil_frames.append(frame_pil)+ vr_frames_np.append(np.array(frame_pil, dtype=np.uint8))++ detector_return_list = [self.detector(pil_frame) for pil_frame in pil_frames]+ poses, _scores, det_results = zip(*detector_return_list)++ if self.multi_person:+ return self._extract_and_render_multi(vr_frames_np, list(poses), list(det_results))++ vr_frames = torch.from_numpy(np.stack(vr_frames_np, axis=0)) # (T,H,W,3) uint8+ nlf_results = process_video_nlf(self.model_nlf, vr_frames, det_results)++ # If nothing was detected across the whole clip, return empty tensor (caller handles it).+ first_pose_idx = None+ for i, item in enumerate(nlf_results):+ if len(item.get("nlfpose", [])) == 0:+ continue+ first = item["nlfpose"][0]+ if first is None:+ continue+ try:+ has_any = len(first) > 0+ except TypeError:+ has_any = False+ if has_any:+ first_pose_idx = i+ break+ if first_pose_idx is None:+ return torch.empty((0,), dtype=torch.float32)++ target_H, target_W = out_h, out_w+ ori_camera_pose = intrinsic_matrix_from_field_of_view([target_H, target_W])+ ori_focal = ori_camera_pose[0, 0]++ if align_pose:+ # Reference image pose + NLF (single frame)+ ref_rgb = ref_image.convert("RGB")+ ref_rgb = ImageOps.fit(ref_rgb, target_size, method=_RESAMPLE_LANCZOS, centering=(0.5, 0.5))+ pose_ref, _score_ref, det_result_ref = self.detector(ref_rgb)+ if det_result_ref is None or len(det_result_ref) == 0:+ align_pose = False+ else:+ vr_ref = torch.from_numpy(np.array(ref_rgb, dtype=np.uint8)).unsqueeze(0)+ nlf_results_ref = process_video_nlf(self.model_nlf, vr_ref, [det_result_ref])++ pose_3d_first_driving_frame = nlf_results[first_pose_idx]["nlfpose"][0][0].cpu().numpy()+ pose_3d_coco_first_driving_frame = process_data_to_COCO_format(pose_3d_first_driving_frame)++ poses_2d_ref = pose_ref["bodies"]["candidate"][0][:14]+ poses_2d_ref[:, 0] = poses_2d_ref[:, 0] * target_W+ poses_2d_ref[:, 1] = poses_2d_ref[:, 1] * target_H++ poses_2d_subset = pose_ref["bodies"]["subset"][0][:14]+ pose_3d_coco_first_driving_frame = pose_3d_coco_first_driving_frame[:14]++ valid_upper_indices = []+ valid_lower_indices = []+ upper_body_indices = [0, 2, 3, 5, 6]+ lower_body_indices = [9, 10, 12, 13]+ for j in range(len(poses_2d_subset)):+ if poses_2d_subset[j] != -1.0 and np.sum(pose_3d_coco_first_driving_frame[j]) != 0:+ if j in upper_body_indices:+ valid_upper_indices.append(j)+ if j in lower_body_indices:+ valid_lower_indices.append(j)++ if len(valid_lower_indices) >= 4:+ valid_indices = [1] + valid_lower_indices+ new_camera_intrinsics, scale_m = solve_new_camera_params_down(+ pose_3d_coco_first_driving_frame[valid_indices], ori_focal, [target_H, target_W], poses_2d_ref[valid_indices]+ )+ else:+ valid_indices = [1] + valid_upper_indices+ new_camera_intrinsics, scale_m = solve_new_camera_params_central(+ pose_3d_coco_first_driving_frame[valid_indices], ori_focal, [target_H, target_W], poses_2d_ref[valid_indices]+ )++ poses_list = list(poses)+ _ = scale_faces(poses_list, [pose_ref])+ nlf_results = recollect_nlf(nlf_results)+ poses_list = recollect_dwposes(poses_list)+ shift_dwpose_according_to_nlf(+ collect_smpl_poses(nlf_results), poses_list, ori_camera_pose, new_camera_intrinsics, target_H, target_W+ )+ frames_np_rgba = render_nlf_as_images(nlf_results, poses_list, reshape_pool=None, intrinsic_matrix=new_camera_intrinsics)++ frames_rgb = np.stack([f[:, :, :3] for f in frames_np_rgba], axis=0).astype(np.float32)+ frames_t = torch.from_numpy(frames_rgb).permute(0, 3, 1, 2) # T,C,H,W+ frames_t = frames_t / 127.5 - 1.0+ return frames_t.permute(1, 0, 2, 3).contiguous()++ # Non-aligned path (official fallback)+ nlf_results = recollect_nlf(nlf_results)+ frames_np_rgba = render_nlf_as_images(nlf_results, list(poses), reshape_pool=None, intrinsic_matrix=ori_camera_pose)+ frames_rgb = np.stack([f[:, :, :3] for f in frames_np_rgba], axis=0).astype(np.float32)+ frames_t = torch.from_numpy(frames_rgb).permute(0, 3, 1, 2)+ frames_t = frames_t / 127.5 - 1.0+ return frames_t.permute(1, 0, 2, 3).contiguous()diff --git a/models/wan/scail/convert_scail.py b/models/wan/scail/convert_scail.pynew file mode 100644index 0000000..7d71981--- /dev/null+++ b/models/wan/scail/convert_scail.py@@ -0,0 +1,352 @@+"""+SCAIL checkpoint converter: SAT/DeepSpeed format → WanGP diffusers format.++SCAIL checkpoints use:+1. DeepSpeed format (weights in sd['module'])+2. SAT (SwissArmyTransformer) key naming with fused QKV++This converts to WanGP canonical format.+"""++import os+import re+import torch+from typing import Dict, Optional+from safetensors.torch import save_file+++def convert_sat_to_wangp(sd: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:+ """+ Convert SAT-format state dict to WanGP diffusers format.++ Key mappings:+ SAT format → WanGP format+ - model.diffusion_model.mixins.patch_embed.proj → patch_embedding+ - model.diffusion_model.mixins.patch_embed.proj_pose → pose_patch_embedding+ - model.diffusion_model.mixins.adaln_layer.adaLN_modulations.{i} → blocks.{i}.modulation+ - model.diffusion_model.mixins.adaln_layer.query_layernorm_list.{i} → blocks.{i}.self_attn.norm_q+ - model.diffusion_model.mixins.adaln_layer.key_layernorm_list.{i} → blocks.{i}.self_attn.norm_k+ - model.diffusion_model.transformer.layers.{i}.attention.query_key_value → split to q/k/v+ - model.diffusion_model.transformer.layers.{i}.attention.dense → blocks.{i}.self_attn.o+ - model.diffusion_model.transformer.layers.{i}.mlp.dense_h_to_4h → blocks.{i}.ffn.0+ - model.diffusion_model.transformer.layers.{i}.mlp.dense_4h_to_h → blocks.{i}.ffn.2+ - model.diffusion_model.time_embed → time_embedding+ - model.diffusion_model.adaln_projection.1 → time_projection.1+ - model.diffusion_model.text_embedding → text_embedding+ - model.diffusion_model.clip_proj.proj → img_emb.proj+ """+ new_sd = {}++ # Process each key+ for k, v in sd.items():+ # Strip common prefix+ key = k+ if key.startswith("model.diffusion_model."):+ key = key[len("model.diffusion_model."):]++ # Patch embeddings+ if key == "mixins.patch_embed.proj.weight":+ new_sd["patch_embedding.weight"] = v+ continue+ if key == "mixins.patch_embed.proj.bias":+ new_sd["patch_embedding.bias"] = v+ continue+ if key == "mixins.patch_embed.proj_pose.weight":+ new_sd["pose_patch_embedding.weight"] = v+ continue+ if key == "mixins.patch_embed.proj_pose.bias":+ new_sd["pose_patch_embedding.bias"] = v+ continue++ # AdaLN modulations -> block modulation+ m = re.match(r"mixins\.adaln_layer\.adaLN_modulations\.(\d+)", key)+ if m:+ block_idx = m.group(1)+ new_sd[f"blocks.{block_idx}.modulation"] = v+ continue++ # Query/Key layernorms+ m = re.match(r"mixins\.adaln_layer\.query_layernorm_list\.(\d+)\.weight", key)+ if m:+ block_idx = m.group(1)+ new_sd[f"blocks.{block_idx}.self_attn.norm_q.weight"] = v+ continue+ m = re.match(r"mixins\.adaln_layer\.key_layernorm_list\.(\d+)\.weight", key)+ if m:+ block_idx = m.group(1)+ new_sd[f"blocks.{block_idx}.self_attn.norm_k.weight"] = v+ continue++ # Cross-attention layernorms+ m = re.match(r"mixins\.adaln_layer\.cross_query_layernorm_list\.(\d+)\.weight", key)+ if m:+ block_idx = m.group(1)+ new_sd[f"blocks.{block_idx}.cross_attn.norm_q.weight"] = v+ continue+ m = re.match(r"mixins\.adaln_layer\.cross_key_layernorm_list\.(\d+)\.weight", key)+ if m:+ block_idx = m.group(1)+ new_sd[f"blocks.{block_idx}.cross_attn.norm_k.weight"] = v+ continue++ # CLIP feature projections -> k_img/v_img+ m = re.match(r"mixins\.adaln_layer\.clip_feature_key_layernorm_list\.(\d+)\.weight", key)+ if m:+ block_idx = m.group(1)+ new_sd[f"blocks.{block_idx}.cross_attn.norm_k_img.weight"] = v+ continue+ m = re.match(r"mixins\.adaln_layer\.clip_feature_key_value_list\.(\d+)\.(weight|bias)", key)+ if m:+ block_idx = m.group(1)+ suffix = m.group(2)+ # Split fused KV for image features+ if suffix == "weight":+ k_img, v_img = v.chunk(2, dim=0)+ new_sd[f"blocks.{block_idx}.cross_attn.k_img.{suffix}"] = k_img+ new_sd[f"blocks.{block_idx}.cross_attn.v_img.{suffix}"] = v_img+ else:+ k_img, v_img = v.chunk(2, dim=0)+ new_sd[f"blocks.{block_idx}.cross_attn.k_img.{suffix}"] = k_img+ new_sd[f"blocks.{block_idx}.cross_attn.v_img.{suffix}"] = v_img+ continue++ # Transformer layers - attention+ m = re.match(r"transformer\.layers\.(\d+)\.attention\.query_key_value\.(weight|bias)", key)+ if m:+ block_idx = m.group(1)+ suffix = m.group(2)+ # Split fused QKV into separate Q, K, V+ # QKV is typically [3*hidden, hidden] for weight, [3*hidden] for bias+ if suffix == "weight":+ hidden_size = v.shape[1]+ q, k, vv = v.chunk(3, dim=0)+ new_sd[f"blocks.{block_idx}.self_attn.q.{suffix}"] = q+ new_sd[f"blocks.{block_idx}.self_attn.k.{suffix}"] = k+ new_sd[f"blocks.{block_idx}.self_attn.v.{suffix}"] = vv+ else: # bias+ q, k, vv = v.chunk(3, dim=0)+ new_sd[f"blocks.{block_idx}.self_attn.q.{suffix}"] = q+ new_sd[f"blocks.{block_idx}.self_attn.k.{suffix}"] = k+ new_sd[f"blocks.{block_idx}.self_attn.v.{suffix}"] = vv+ continue++ m = re.match(r"transformer\.layers\.(\d+)\.attention\.dense\.(weight|bias)", key)+ if m:+ block_idx = m.group(1)+ suffix = m.group(2)+ new_sd[f"blocks.{block_idx}.self_attn.o.{suffix}"] = v+ continue++ # Cross-attention - separate query+ m = re.match(r"transformer\.layers\.(\d+)\.cross_attention\.query\.(weight|bias)", key)+ if m:+ block_idx = m.group(1)+ suffix = m.group(2)+ new_sd[f"blocks.{block_idx}.cross_attn.q.{suffix}"] = v+ continue++ # Cross-attention - fused key_value (split into k and v)+ m = re.match(r"transformer\.layers\.(\d+)\.cross_attention\.key_value\.(weight|bias)", key)+ if m:+ block_idx = m.group(1)+ suffix = m.group(2)+ # Split fused KV into separate K and V+ k, vv = v.chunk(2, dim=0)+ new_sd[f"blocks.{block_idx}.cross_attn.k.{suffix}"] = k+ new_sd[f"blocks.{block_idx}.cross_attn.v.{suffix}"] = vv+ continue++ # Cross-attention - separate k/v (fallback)+ m = re.match(r"transformer\.layers\.(\d+)\.cross_attention\.key\.(weight|bias)", key)+ if m:+ block_idx = m.group(1)+ suffix = m.group(2)+ new_sd[f"blocks.{block_idx}.cross_attn.k.{suffix}"] = v+ continue+ m = re.match(r"transformer\.layers\.(\d+)\.cross_attention\.value\.(weight|bias)", key)+ if m:+ block_idx = m.group(1)+ suffix = m.group(2)+ new_sd[f"blocks.{block_idx}.cross_attn.v.{suffix}"] = v+ continue++ # Cross-attention output+ m = re.match(r"transformer\.layers\.(\d+)\.cross_attention\.dense\.(weight|bias)", key)+ if m:+ block_idx = m.group(1)+ suffix = m.group(2)+ new_sd[f"blocks.{block_idx}.cross_attn.o.{suffix}"] = v+ continue++ # Post cross-attention layer norm -> norm3+ m = re.match(r"transformer\.layers\.(\d+)\.post_cross_attention_layernorm\.(weight|bias)", key)+ if m:+ block_idx = m.group(1)+ suffix = m.group(2)+ new_sd[f"blocks.{block_idx}.norm3.{suffix}"] = v+ continue++ # MLP / FFN+ m = re.match(r"transformer\.layers\.(\d+)\.mlp\.dense_h_to_4h\.(weight|bias)", key)+ if m:+ block_idx = m.group(1)+ suffix = m.group(2)+ new_sd[f"blocks.{block_idx}.ffn.0.{suffix}"] = v+ continue+ m = re.match(r"transformer\.layers\.(\d+)\.mlp\.dense_4h_to_h\.(weight|bias)", key)+ if m:+ block_idx = m.group(1)+ suffix = m.group(2)+ new_sd[f"blocks.{block_idx}.ffn.2.{suffix}"] = v+ continue++ # Post-attention layer norm (norm3 in WanGP)+ m = re.match(r"transformer\.layers\.(\d+)\.post_attention_layernorm\.(weight|bias)", key)+ if m:+ block_idx = m.group(1)+ suffix = m.group(2)+ new_sd[f"blocks.{block_idx}.norm3.{suffix}"] = v+ continue++ # Time embedding+ m = re.match(r"time_embed\.(\d+)\.(weight|bias)", key)+ if m:+ idx = m.group(1)+ suffix = m.group(2)+ new_sd[f"time_embedding.{idx}.{suffix}"] = v+ continue++ # AdaLN projection (time projection)+ m = re.match(r"adaln_projection\.(\d+)\.(weight|bias)", key)+ if m:+ idx = m.group(1)+ suffix = m.group(2)+ new_sd[f"time_projection.{idx}.{suffix}"] = v+ continue++ # Text embedding+ m = re.match(r"text_embedding\.(\d+)\.(weight|bias)", key)+ if m:+ idx = m.group(1)+ suffix = m.group(2)+ new_sd[f"text_embedding.{idx}.{suffix}"] = v+ continue++ # CLIP projection (img_emb)+ m = re.match(r"clip_proj\.proj\.(\d+)\.(weight|bias)", key)+ if m:+ idx = m.group(1)+ suffix = m.group(2)+ new_sd[f"img_emb.proj.{idx}.{suffix}"] = v+ continue++ # Final projection / head+ if key == "mixins.final_layer.adaLN_modulation":+ new_sd["head.modulation"] = v+ continue+ m = re.match(r"mixins\.final_layer\.linear\.(weight|bias)", key)+ if m:+ suffix = m.group(1)+ new_sd[f"head.head.{suffix}"] = v+ continue++ # Cross-attention image projections (k_img, v_img, norm_k_img)+ m = re.match(r"transformer\.layers\.(\d+)\.cross_attention\.k_img\.(weight|bias)", key)+ if m:+ block_idx = m.group(1)+ suffix = m.group(2)+ new_sd[f"blocks.{block_idx}.cross_attn.k_img.{suffix}"] = v+ continue+ m = re.match(r"transformer\.layers\.(\d+)\.cross_attention\.v_img\.(weight|bias)", key)+ if m:+ block_idx = m.group(1)+ suffix = m.group(2)+ new_sd[f"blocks.{block_idx}.cross_attn.v_img.{suffix}"] = v+ continue+ m = re.match(r"transformer\.layers\.(\d+)\.cross_attention\.norm_k_img\.weight", key)+ if m:+ block_idx = m.group(1)+ new_sd[f"blocks.{block_idx}.cross_attn.norm_k_img.weight"] = v+ continue++ # If no match, keep with warning+ print(f"[WARN] Unmapped key: {k}")+ # Still include it with stripped prefix+ new_sd[key] = v++ return new_sd+++def load_deepspeed_checkpoint(path: str) -> Dict[str, torch.Tensor]:+ """Load DeepSpeed checkpoint and extract model weights."""+ print(f"Loading checkpoint: {path}")+ ckpt = torch.load(path, map_location="cpu", weights_only=False)++ if isinstance(ckpt, dict) and "module" in ckpt:+ print("DeepSpeed format detected, extracting from 'module' key")+ return ckpt["module"]+ elif isinstance(ckpt, dict):+ # Regular state dict+ return ckpt+ else:+ raise ValueError(f"Unexpected checkpoint format: {type(ckpt)}")+++def convert_scail_checkpoint(+ input_path: str,+ output_path: str,+ cast_dtype: Optional[str] = "bf16"+) -> None:+ """+ Convert SCAIL checkpoint to WanGP format.++ Args:+ input_path: Path to SCAIL .pt checkpoint+ output_path: Path to output .safetensors file+ cast_dtype: Target dtype (bf16, fp16, fp32)+ """+ # Load checkpoint+ sd = load_deepspeed_checkpoint(input_path)++ # Convert keys+ print("Converting SAT keys to WanGP format...")+ new_sd = convert_sat_to_wangp(sd)++ # Cast dtype+ if cast_dtype:+ dtype_map = {+ "bf16": torch.bfloat16,+ "bfloat16": torch.bfloat16,+ "fp16": torch.float16,+ "float16": torch.float16,+ "fp32": torch.float32,+ "float32": torch.float32,+ }+ target_dtype = dtype_map.get(cast_dtype.lower())+ if target_dtype:+ print(f"Casting to {target_dtype}")+ new_sd = {k: v.to(target_dtype) for k, v in new_sd.items()}++ # Save+ os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)+ print(f"Saving to: {output_path}")+ save_file(new_sd, output_path, metadata={+ "format": "wangp_scail",+ "converted_from": "scail_sat_deepspeed",+ })++ print(f"Done! Converted {len(new_sd)} keys")+++if __name__ == "__main__":+ import sys++ if len(sys.argv) < 2:+ print("Usage: python convert_scail.py <input.pt> [output.safetensors]")+ print("Example: python convert_scail.py c:/temp/scail.pt c:/temp/scail_wangp.safetensors")+ sys.exit(1)++ input_path = sys.argv[1]+ output_path = sys.argv[2] if len(sys.argv) > 2 else input_path.replace(".pt", "_wangp.safetensors")++ convert_scail_checkpoint(input_path, output_path)diff --git a/models/wan/scail/cylinder_renderer.py b/models/wan/scail/cylinder_renderer.pynew file mode 100644index 0000000..e4ccee6--- /dev/null+++ b/models/wan/scail/cylinder_renderer.py@@ -0,0 +1,391 @@+"""+SCAIL Cylinder Renderer - Render 3D skeleton as cylindrical bones.+Uses Taichi for GPU-accelerated rendering with proper occlusion handling.+"""++import numpy as np+import cv2+from typing import List, Tuple, Optional++# Lazy import to avoid printing version message at app startup+ti = None+TAICHI_AVAILABLE = None # Will be set on first use+++def _ensure_taichi_imported():+ global ti, TAICHI_AVAILABLE+ if TAICHI_AVAILABLE is not None:+ return TAICHI_AVAILABLE+ try:+ import taichi as _ti+ ti = _ti+ TAICHI_AVAILABLE = True+ except ImportError:+ TAICHI_AVAILABLE = False+ print("[SCAIL] Taichi not available, using CPU rendering (slower)")+ return TAICHI_AVAILABLE+++# Skeleton topology - pairs of keypoint indices that form bones+# Based on COCO 18-keypoint format+SKELETON_CONNECTIONS = [+ # Head+ (0, 1), # Nose -> Neck+ (0, 14), # Nose -> R_Eye+ (0, 15), # Nose -> L_Eye+ (14, 16), # R_Eye -> R_Ear+ (15, 17), # L_Eye -> L_Ear++ # Torso+ (1, 2), # Neck -> R_Shoulder+ (1, 5), # Neck -> L_Shoulder+ (2, 8), # R_Shoulder -> R_Hip+ (5, 11), # L_Shoulder -> L_Hip+ (8, 11), # R_Hip -> L_Hip++ # Right arm+ (2, 3), # R_Shoulder -> R_Elbow+ (3, 4), # R_Elbow -> R_Wrist++ # Left arm+ (5, 6), # L_Shoulder -> L_Elbow+ (6, 7), # L_Elbow -> L_Wrist++ # Right leg+ (8, 9), # R_Hip -> R_Knee+ (9, 10), # R_Knee -> R_Ankle++ # Left leg+ (11, 12), # L_Hip -> L_Knee+ (12, 13), # L_Knee -> L_Ankle+]++# Colors for different body parts (RGB, 0-1 range)+BONE_COLORS = {+ # Head - yellow/orange+ (0, 1): (1.0, 0.8, 0.2),+ (0, 14): (1.0, 0.7, 0.3),+ (0, 15): (1.0, 0.7, 0.3),+ (14, 16): (1.0, 0.6, 0.3),+ (15, 17): (1.0, 0.6, 0.3),++ # Torso - blue+ (1, 2): (0.2, 0.6, 1.0),+ (1, 5): (0.2, 0.6, 1.0),+ (2, 8): (0.3, 0.5, 0.9),+ (5, 11): (0.3, 0.5, 0.9),+ (8, 11): (0.4, 0.4, 0.8),++ # Right arm - green+ (2, 3): (0.2, 0.9, 0.3),+ (3, 4): (0.3, 0.8, 0.4),++ # Left arm - cyan+ (5, 6): (0.2, 0.9, 0.8),+ (6, 7): (0.3, 0.8, 0.7),++ # Right leg - red+ (8, 9): (0.9, 0.3, 0.2),+ (9, 10): (0.8, 0.4, 0.3),++ # Left leg - magenta+ (11, 12): (0.9, 0.2, 0.7),+ (12, 13): (0.8, 0.3, 0.6),+}+++class CylinderRendererCPU:+ """CPU-based cylinder renderer fallback."""++ def __init__(self, resolution: Tuple[int, int] = (512, 896)):+ self.width, self.height = resolution++ def render_skeleton(+ self,+ keypoints_3d: np.ndarray,+ canvas_size: Optional[Tuple[int, int]] = None,+ cylinder_radius: float = 0.015+ ) -> np.ndarray:+ """+ Render 3D skeleton as colored cylinders.++ Args:+ keypoints_3d: 3D keypoints, shape (num_joints, 3) in normalized coords+ canvas_size: Output image size (width, height)+ cylinder_radius: Radius of cylinder bones (normalized)++ Returns:+ RGB image as numpy array, shape (H, W, 3), uint8+ """+ if canvas_size is None:+ canvas_size = (self.width, self.height)++ width, height = canvas_size+ canvas = np.zeros((height, width, 3), dtype=np.float32)+ depth_buffer = np.full((height, width), np.inf, dtype=np.float32)++ # Render each bone+ for (i, j) in SKELETON_CONNECTIONS:+ if keypoints_3d[i, 0] < 0 or keypoints_3d[j, 0] < 0:+ continue # Skip invalid keypoints++ p1 = keypoints_3d[i]+ p2 = keypoints_3d[j]+ color = np.array(BONE_COLORS.get((i, j), (0.5, 0.5, 0.5)))++ self._render_cylinder(canvas, depth_buffer, p1, p2, color, cylinder_radius, width, height)++ # Convert to uint8+ canvas = (np.clip(canvas, 0, 1) * 255).astype(np.uint8)+ return canvas++ def _render_cylinder(+ self,+ canvas: np.ndarray,+ depth_buffer: np.ndarray,+ p1: np.ndarray,+ p2: np.ndarray,+ color: np.ndarray,+ radius: float,+ width: int,+ height: int+ ):+ """Render a single cylinder between two 3D points."""+ # Project to 2D+ x1, y1, z1 = p1[0] * width, p1[1] * height, p1[2]+ x2, y2, z2 = p2[0] * width, p2[1] * height, p2[2]++ # Draw thick line with depth-based shading+ num_steps = int(max(abs(x2 - x1), abs(y2 - y1), 1) * 2)+ pixel_radius = int(radius * min(width, height))++ for t in np.linspace(0, 1, num_steps):+ x = int(x1 + t * (x2 - x1))+ y = int(y1 + t * (y2 - y1))+ z = z1 + t * (z2 - z1)++ # Draw cylinder cross-section (circle)+ for dy in range(-pixel_radius, pixel_radius + 1):+ for dx in range(-pixel_radius, pixel_radius + 1):+ dist_sq = dx * dx + dy * dy+ if dist_sq > pixel_radius * pixel_radius:+ continue++ px, py = x + dx, y + dy+ if 0 <= px < width and 0 <= py < height:+ # Adjust depth based on position in cylinder+ dist = np.sqrt(dist_sq)+ z_offset = np.sqrt(max(0, pixel_radius * pixel_radius - dist_sq)) / (pixel_radius + 1)+ local_z = z - z_offset * 0.1++ if local_z < depth_buffer[py, px]:+ depth_buffer[py, px] = local_z++ # Shading based on distance from center+ shade = 0.5 + 0.5 * (1 - dist / pixel_radius)+ canvas[py, px] = color * shade+++# Lazy-defined Taichi renderer class (defined after ti is imported)+_CylinderRendererTaichi = None+++def _get_taichi_renderer_class():+ """Get or create the Taichi renderer class (lazy definition)."""+ global _CylinderRendererTaichi+ if _CylinderRendererTaichi is not None:+ return _CylinderRendererTaichi++ @ti.data_oriented+ class CylinderRendererTaichi:+ """GPU-accelerated cylinder renderer using Taichi."""++ def __init__(self, resolution: Tuple[int, int] = (512, 896)):+ self.width, self.height = resolution++ # Initialize Taichi (silent mode, only show errors)+ ti.init(arch=ti.gpu, offline_cache=True, log_level=ti.ERROR)++ # Allocate fields+ self.canvas = ti.Vector.field(3, dtype=ti.f32, shape=(self.height, self.width))+ self.depth_buffer = ti.field(dtype=ti.f32, shape=(self.height, self.width))++ # Pre-compute skeleton connections and colors+ self.num_bones = len(SKELETON_CONNECTIONS)+ self.bone_indices = ti.Vector.field(2, dtype=ti.i32, shape=self.num_bones)+ self.bone_colors = ti.Vector.field(3, dtype=ti.f32, shape=self.num_bones)++ for idx, (i, j) in enumerate(SKELETON_CONNECTIONS):+ self.bone_indices[idx] = [i, j]+ color = BONE_COLORS.get((i, j), (0.5, 0.5, 0.5))+ self.bone_colors[idx] = list(color)++ # Keypoints field (max 18 keypoints)+ self.keypoints = ti.Vector.field(3, dtype=ti.f32, shape=18)++ @ti.kernel+ def _clear_buffers(self):+ """Clear canvas and depth buffer."""+ for i, j in self.canvas:+ self.canvas[i, j] = ti.Vector([0.0, 0.0, 0.0])+ self.depth_buffer[i, j] = 1e10++ @ti.kernel+ def _render_bones(self, radius: ti.f32):+ """Render all bones as cylinders."""+ for bone_idx in range(self.num_bones):+ i = self.bone_indices[bone_idx][0]+ j = self.bone_indices[bone_idx][1]++ # Skip invalid keypoints+ if self.keypoints[i][0] < 0 or self.keypoints[j][0] < 0:+ continue++ p1 = self.keypoints[i]+ p2 = self.keypoints[j]+ color = self.bone_colors[bone_idx]++ # Project to 2D+ x1, y1, z1 = p1[0] * self.width, p1[1] * self.height, p1[2]+ x2, y2, z2 = p2[0] * self.width, p2[1] * self.height, p2[2]++ # Rasterize cylinder+ pixel_radius = ti.cast(radius * ti.min(self.width, self.height), ti.i32)+ length = ti.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)+ num_steps = ti.cast(ti.max(length * 2, 1.0), ti.i32)++ for step in range(num_steps):+ t = step / ti.max(num_steps - 1.0, 1.0)+ cx = ti.cast(x1 + t * (x2 - x1), ti.i32)+ cy = ti.cast(y1 + t * (y2 - y1), ti.i32)+ cz = z1 + t * (z2 - z1)++ # Draw cylinder cross-section+ for dy in range(-pixel_radius, pixel_radius + 1):+ for dx in range(-pixel_radius, pixel_radius + 1):+ dist_sq = dx * dx + dy * dy+ if dist_sq <= pixel_radius * pixel_radius:+ px = cx + dx+ py = cy + dy++ if 0 <= px < self.width and 0 <= py < self.height:+ dist = ti.sqrt(ti.cast(dist_sq, ti.f32))+ z_offset = ti.sqrt(ti.max(0.0, pixel_radius ** 2 - dist_sq)) / (pixel_radius + 1)+ local_z = cz - z_offset * 0.1++ if local_z < self.depth_buffer[py, px]:+ self.depth_buffer[py, px] = local_z+ shade = 0.5 + 0.5 * (1 - dist / pixel_radius)+ self.canvas[py, px] = color * shade++ def render_skeleton(+ self,+ keypoints_3d: np.ndarray,+ canvas_size: Optional[Tuple[int, int]] = None,+ cylinder_radius: float = 0.015+ ) -> np.ndarray:+ """+ Render 3D skeleton as colored cylinders.++ Args:+ keypoints_3d: 3D keypoints, shape (num_joints, 3) in normalized coords+ canvas_size: Output image size (ignored, uses init resolution)+ cylinder_radius: Radius of cylinder bones (normalized)++ Returns:+ RGB image as numpy array, shape (H, W, 3), uint8+ """+ # Copy keypoints to Taichi field+ for i in range(min(len(keypoints_3d), 18)):+ self.keypoints[i] = keypoints_3d[i].tolist()++ # Clear and render+ self._clear_buffers()+ self._render_bones(cylinder_radius)++ # Copy result+ canvas = self.canvas.to_numpy()+ canvas = (np.clip(canvas, 0, 1) * 255).astype(np.uint8)+ return canvas++ _CylinderRendererTaichi = CylinderRendererTaichi+ return _CylinderRendererTaichi+++class CylinderRenderer:+ """+ Main cylinder renderer class.+ Automatically selects GPU (Taichi) or CPU implementation.+ """++ def __init__(self, resolution: Tuple[int, int] = (512, 896)):+ """+ Initialize renderer.++ Args:+ resolution: Output resolution as (width, height)+ """+ self.resolution = resolution++ if _ensure_taichi_imported():+ try:+ TaichiRenderer = _get_taichi_renderer_class()+ self._renderer = TaichiRenderer(resolution)+ self._use_gpu = True+ except Exception as e:+ print(f"[SCAIL] Failed to initialize Taichi renderer: {e}")+ self._renderer = CylinderRendererCPU(resolution)+ self._use_gpu = False+ else:+ self._renderer = CylinderRendererCPU(resolution)+ self._use_gpu = False++ def render_skeleton(+ self,+ keypoints_3d: np.ndarray,+ canvas_size: Optional[Tuple[int, int]] = None,+ cylinder_radius: float = 0.015+ ) -> np.ndarray:+ """+ Render 3D skeleton as colored cylinders.++ Args:+ keypoints_3d: 3D keypoints, shape (num_joints, 3) in normalized [0,1] coords+ canvas_size: Output image size (width, height), or None for default+ cylinder_radius: Radius of cylinder bones (normalized)++ Returns:+ RGB image as numpy array, shape (H, W, 3), uint8+ """+ result = self._renderer.render_skeleton(keypoints_3d, canvas_size, cylinder_radius)++ # Resize if canvas_size differs from rendered size (Taichi renderer uses fixed resolution)+ if canvas_size is not None:+ target_w, target_h = canvas_size+ current_h, current_w = result.shape[:2]+ if current_h != target_h or current_w != target_w:+ result = cv2.resize(result, (target_w, target_h), interpolation=cv2.INTER_LANCZOS4)++ return result++ def render_sequence(+ self,+ keypoints_sequence: List[np.ndarray],+ canvas_size: Optional[Tuple[int, int]] = None,+ cylinder_radius: float = 0.015+ ) -> List[np.ndarray]:+ """+ Render a sequence of skeletons.++ Args:+ keypoints_sequence: List of 3D keypoints arrays+ canvas_size: Output image size (width, height)+ cylinder_radius: Radius of cylinder bones++ Returns:+ List of rendered RGB images+ """+ return [+ self.render_skeleton(kp, canvas_size, cylinder_radius)+ for kp in keypoints_sequence+ ]diff --git a/models/wan/scail/model_scail.py b/models/wan/scail/model_scail.pynew file mode 100644index 0000000..f15e32d--- /dev/null+++ b/models/wan/scail/model_scail.py@@ -0,0 +1,81 @@+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.+# SCAIL model integration for WanGP++import torch+from typing import Optional+++def build_scail_pose_tokens(model, pose_latents: torch.Tensor, target_dtype: Optional[torch.dtype] = None) -> torch.Tensor:+ """+ Build SCAIL pose tokens to be concatenated after image tokens.++ Upstream SCAIL treats pose as an additional token sequence (typically at half spatial resolution),+ embedded by a dedicated Conv3d (`pose_patch_embedding`) and concatenated to the main token stream.++ Args:+ model: WanModel instance with `pose_patch_embedding` (Conv3d).+ pose_latents: VAE-encoded pose video (B, 16, T, H, W).+ target_dtype: Optional dtype to cast pose_latents before embedding.++ Returns:+ Pose tokens tensor (B, S_pose, dim).+ """+ if target_dtype is not None and pose_latents.dtype != target_dtype:+ pose_latents = pose_latents.to(dtype=target_dtype)++ # Upstream uses an all-ones pose mask concatenated to pose latents (16 + 4 = 20 channels).+ pose_mask = torch.ones(+ pose_latents.shape[0],+ 4,+ *pose_latents.shape[2:],+ device=pose_latents.device,+ dtype=pose_latents.dtype,+ )+ pose_input = torch.cat([pose_latents, pose_mask], dim=1)+ pose_embed = model.pose_patch_embedding(pose_input) # (B, dim, T', H', W')+ return pose_embed.flatten(2).transpose(1, 2)+++def after_patch_embedding_scail(+ model,+ x: torch.Tensor,+ pose_latents: torch.Tensor,+ mask: Optional[torch.Tensor] = None+):+ """+ SCAIL-specific pose embedding injection.++ Unlike Animate, SCAIL doesn't need motion_encoder or face_encoder.+ It concatenates the mask with pose_latents (16 + 4 = 20 channels)+ and adds the pose embeddings to the latent representation.++ Args:+ model: WanModel instance with pose_patch_embedding+ x: Main latent tensor after patch embedding (B, seq_len, dim)+ pose_latents: VAE-encoded pose video (B, 16, T, H, W)+ mask: Conditioning mask (B, 4, T, H, W) to concatenate with pose_latents++ Returns:+ Modified x tensor with pose conditioning+ """+ # Concatenate pose_latents with mask to match in_dim=20+ if mask is not None:+ # pose_latents: (B, 16, T, H, W), mask: (B, 4, T, H, W) -> (B, 20, T, H, W)+ pose_input = torch.cat([pose_latents, mask], dim=1)+ else:+ # Fallback: pad with zeros if no mask available+ pad = torch.zeros(+ pose_latents.shape[0], 4, *pose_latents.shape[2:],+ device=pose_latents.device, dtype=pose_latents.dtype+ )+ pose_input = torch.cat([pose_latents, pad], dim=1)++ # Embed pose latents through Conv3d+ # Output shape: (B, dim, T', H', W') - same as x+ pose_embed = model.pose_patch_embedding(pose_input)++ # Add pose embeddings to x (both have shape B, dim, T', H', W')+ # SCAIL doesn't have a reference frame in the latent input, so add to all positions+ x = x + pose_embed++ return xdiff --git a/models/wan/scail/nlf/__init__.py b/models/wan/scail/nlf/__init__.pynew file mode 100644index 0000000..15bfabf--- /dev/null+++ b/models/wan/scail/nlf/__init__.py@@ -0,0 +1,4 @@+"""NLF (Neural Localizer Fields) - local copy for SCAIL pose processing."""+from .eager import load_multiperson_nlf_eager++__all__ = ["load_multiperson_nlf_eager"]diff --git a/models/wan/scail/nlf/eager.py b/models/wan/scail/nlf/eager.pynew file mode 100644index 0000000..2ebf33d--- /dev/null+++ b/models/wan/scail/nlf/eager.py@@ -0,0 +1,383 @@+"""Eager mode loader for NLF multiperson model by DeepBeepMeep - enable Forward Pytorch Compatibility."""+from __future__ import annotations++import json+from functools import partial+from pathlib import Path+from typing import Dict, Optional, Tuple++import numpy as np+import torch+import torch.nn as nn+import torchvision.models++from . import field as nlf_field+from .nlf_model import NLFModel, NLFModelConfig+from .multiperson_model import MultipersonNLF+from .person_detector import PersonDetectorONNX+++class MeanStdPreproc(nn.Module):+ def __init__(self, mean, std):+ super().__init__()+ self.mean = nn.Buffer(torch.tensor(mean, dtype=torch.float32), persistent=False)+ self.std = nn.Buffer(torch.tensor(std, dtype=torch.float32), persistent=False)++ def forward(self, inp: torch.Tensor) -> torch.Tensor:+ return (inp - self.mean.to(inp.dtype)) / self.std.to(inp.dtype)+++def _strip_prefix(state_dict: Dict[str, torch.Tensor], prefix: str) -> Dict[str, torch.Tensor]:+ return {k[len(prefix) :]: v for k, v in state_dict.items() if k.startswith(prefix)}+++def _apply_centered_stride_padding_fix(+ backbone: nn.Module, *, centered_stride: bool, backbone_name: str+) -> None:+ """Match NLF's EfficientNet stride alignment when `centered_stride=True`.++ Upstream NLF uses a modified EfficientNet that applies asymmetric padding on the+ deepest strided MBConv block. Using the vanilla torchvision EfficientNet can yield+ an almost-constant pixel translation in the reconstructed 2D projections.+ """++ if not centered_stride:+ return+ if not backbone_name.startswith("efficientnet"):+ return++ try:+ import torchvision.models.efficientnet as tv_effnet+ except Exception:+ return++ candidates: list[tuple[int, nn.Module]] = []+ for module in backbone.modules():+ if not isinstance(module, tv_effnet.MBConv):+ continue+ if not (hasattr(module, "block") and len(module.block) > 1):+ continue++ cna = module.block[1]+ if not (isinstance(cna, nn.Sequential) and len(cna) > 0 and isinstance(cna[0], nn.Conv2d)):+ continue+ conv = cna[0]+ if tuple(conv.stride) != (2, 2):+ continue+ candidates.append((int(conv.in_channels), module))++ if not candidates:+ return++ _in_ch, target = max(candidates, key=lambda x: x[0])+ cna = target.block[1]+ if not (isinstance(cna, nn.Sequential) and len(cna) > 0 and isinstance(cna[0], nn.Conv2d)):+ return++ conv = cna[0]+ kernel = int(conv.kernel_size[0])+ if kernel <= 1:+ return++ pad_total = kernel - 1+ pad_beg = pad_total // 2+ pad_end = pad_total - pad_beg++ # Apply `shifts=(1,1)` as in upstream `fixed_padding_layer(..., shifts=(1,1))`.+ left = pad_beg - 1+ right = pad_end + 1+ top = pad_beg - 1+ bottom = pad_end + 1+ if left < 0 or top < 0:+ return++ conv.padding = (0, 0)+ target.block[1] = nn.Sequential(nn.ZeroPad2d((left, right, top, bottom)), cna)+++def _build_effnet_backbone(backbone_name: str, *, bn_eps: float = 1e-3) -> nn.Module:+ if backbone_name == 'efficientnetv2-l':+ return torchvision.models.efficientnet_v2_l(weights=None).features+ if backbone_name == 'efficientnetv2-s':+ return torchvision.models.efficientnet_v2_s(weights=None).features+ raise ValueError(f'Unsupported backbone: {backbone_name}')+++def build_crop_model_from_state_dict(+ crop_state_dict: Dict[str, torch.Tensor], *, meta: Dict+) -> NLFModel:+ cm = meta['crop_model']+ config = NLFModelConfig(+ proc_side=int(cm['proc_side']),+ stride_test=int(cm['stride_test']),+ centered_stride=bool(cm['centered_stride']),+ backbone_link_dim=int(cm['backbone_link_dim']),+ depth=int(cm['depth']),+ box_size_m=float(cm['box_size_m']),+ uncert_bias=float(cm['uncert_bias']),+ uncert_bias2=float(cm['uncert_bias2']),+ fix_uncert_factor=bool(cm['fix_uncert_factor']),+ mix_3d_inside_fov=float(cm['mix_3d_inside_fov']),+ weak_perspective=bool(cm['weak_perspective']),+ )++ backbone_name = str(cm.get('backbone', 'efficientnetv2-l'))+ backbone_channels = int(crop_state_dict['heatmap_head.layer.0.weight'].shape[1])+ backbone = nn.Sequential(+ MeanStdPreproc(mean=0.5, std=0.5),+ _build_effnet_backbone(backbone_name),+ )++ pred_keys = [+ k+ for k in crop_state_dict.keys()+ if k.startswith('heatmap_head.weight_field.pred_mlp.') and k.endswith('.weight')+ ]+ pred_keys_sorted = sorted(pred_keys, key=lambda x: int(x.split('.')[3]))+ field_posenc_dim = int(crop_state_dict[pred_keys_sorted[0]].shape[1])+ layer_dims = [int(crop_state_dict[k].shape[0]) for k in pred_keys_sorted]++ gps_pos_enc_dim = int(+ crop_state_dict['heatmap_head.weight_field.gps_net.learnable_fourier.linear.weight'].shape[0]+ * 2+ )+ gps_hidden_dim = int(+ crop_state_dict['heatmap_head.weight_field.gps_net.mlp.0.weight'].shape[0]+ )+ gps_output_dim = int(+ crop_state_dict['heatmap_head.weight_field.gps_net.mlp.2.weight'].shape[0]+ )++ gps_net = nlf_field.GPSNet(+ pos_enc_dim=gps_pos_enc_dim,+ hidden_dim=gps_hidden_dim,+ output_dim=gps_output_dim,+ load_from_projdir=False,+ )+ weight_field = nlf_field.GPSField(+ gps_net,+ layer_dims=layer_dims,+ posenc_dim=field_posenc_dim,+ )++ normalizer = partial(nn.BatchNorm2d, eps=1e-3)++ n_left = int(crop_state_dict['canonical_lefts'].shape[0])+ n_center = int(crop_state_dict['canonical_centers'].shape[0])+ n_joints = int(crop_state_dict['inv_permutation'].shape[0])++ crop_model = NLFModel(+ backbone,+ weight_field,+ normalizer,+ backbone_channels=backbone_channels,+ config=config,+ n_joints=n_joints,+ n_left_joints=n_left,+ n_center_joints=n_center,+ )+ crop_model.load_state_dict(crop_state_dict, strict=False)+ with torch.no_grad():+ if 'inv_permutation' in crop_state_dict:+ crop_model.inv_permutation.copy_(crop_state_dict['inv_permutation'])+ if 'canonical_locs_init' in crop_state_dict:+ crop_model.canonical_locs_init.copy_(crop_state_dict['canonical_locs_init'])+ if 'canonical_delta_mask' in crop_state_dict:+ crop_model.canonical_delta_mask.copy_(crop_state_dict['canonical_delta_mask'])+ # Handle scalar vs tensor mismatch (safetensors doesn't preserve 0-dim tensors well)+ if 'backbone.0.mean' in crop_state_dict:+ mean_val = crop_state_dict['backbone.0.mean']+ if mean_val.dim() == 0:+ mean_val = mean_val.unsqueeze(0)+ crop_model.backbone[0].mean = nn.Buffer(mean_val.to(dtype=torch.float32), persistent=False)+ if 'backbone.0.std' in crop_state_dict:+ std_val = crop_state_dict['backbone.0.std']+ if std_val.dim() == 0:+ std_val = std_val.unsqueeze(0)+ crop_model.backbone[0].std = nn.Buffer(std_val.to(dtype=torch.float32), persistent=False)++ wf = crop_model.heatmap_head.weight_field+ if 'heatmap_head.weight_field.r_sqrt_eigva' in crop_state_dict:+ wf.r_sqrt_eigva.copy_(crop_state_dict['heatmap_head.weight_field.r_sqrt_eigva'])+ if 'heatmap_head.weight_field.gps_net.mini' in crop_state_dict:+ wf.gps_net.mini.copy_(crop_state_dict['heatmap_head.weight_field.gps_net.mini'])+ if 'heatmap_head.weight_field.gps_net.maxi' in crop_state_dict:+ wf.gps_net.maxi.copy_(crop_state_dict['heatmap_head.weight_field.gps_net.maxi'])+ if 'heatmap_head.weight_field.gps_net.center' in crop_state_dict:+ wf.gps_net.center.copy_(crop_state_dict['heatmap_head.weight_field.gps_net.center'])++ if isinstance(crop_model.backbone, nn.Sequential) and len(crop_model.backbone) > 1:+ _apply_centered_stride_padding_fix(+ crop_model.backbone[1],+ centered_stride=bool(cm.get('centered_stride', False)),+ backbone_name=backbone_name,+ )++ return crop_model+++def _body_model_from_tensors(+ *,+ model_name: str,+ gender: str,+ tensors: Dict[str, torch.Tensor],+) -> nn.Module:+ import smplfitter.pt++ BodyModel = smplfitter.pt.BodyModel+ model = BodyModel.__new__(BodyModel)+ nn.Module.__init__(model)+ model.gender = gender+ model.model_name = model_name++ model.v_template = nn.Buffer(tensors['v_template'].to(dtype=torch.float32), persistent=False)+ model.shapedirs = nn.Buffer(tensors['shapedirs'].to(dtype=torch.float32), persistent=False)+ model.posedirs = nn.Buffer(tensors['posedirs'].to(dtype=torch.float32), persistent=False)+ model.J_regressor_post_lbs = nn.Buffer(+ tensors['J_regressor_post_lbs'].to(dtype=torch.float32), persistent=False+ )+ model.J_template = nn.Buffer(tensors['J_template'].to(dtype=torch.float32), persistent=False)+ model.J_shapedirs = nn.Buffer(tensors['J_shapedirs'].to(dtype=torch.float32), persistent=False)+ model.kid_shapedir = nn.Buffer(+ tensors['kid_shapedir'].to(dtype=torch.float32), persistent=False+ )+ model.kid_J_shapedir = nn.Buffer(+ tensors['kid_J_shapedir'].to(dtype=torch.float32), persistent=False+ )+ model.weights = nn.Buffer(tensors['weights'].to(dtype=torch.float32), persistent=False)+ model.kintree_parents_tensor = nn.Buffer(+ tensors['kintree_parents_tensor'].to(dtype=torch.int64), persistent=False+ )++ model.kintree_parents = [int(x) for x in model.kintree_parents_tensor.cpu().tolist()]+ model.faces = np.zeros((0, 3), dtype=np.int64)+ model.num_joints = int(model.J_template.shape[0])+ model.num_vertices = int(model.v_template.shape[0])+ model.num_betas = int(model.shapedirs.shape[2])+ model.vertex_subset = np.arange(model.num_vertices)+ return model+++def _build_body_models_and_fitters(+ state_dict: Dict[str, torch.Tensor],+) -> Tuple[nn.ModuleDict, nn.ModuleDict]:+ import smplfitter.pt++ body_models = nn.ModuleDict()+ fitters = nn.ModuleDict()++ for model_name in ('smpl', 'smplx'):+ full_tensors = _strip_prefix(state_dict, f'body_models.{model_name}.')+ partial_tensors = _strip_prefix(state_dict, f'fitters.{model_name}.body_model.')+ if not full_tensors or not partial_tensors:+ raise KeyError(+ f'Missing {model_name} SMPL tensors in checkpoint state_dict (body_models / fitters).'+ )++ body_models[model_name] = _body_model_from_tensors(+ model_name=model_name, gender='neutral', tensors=full_tensors+ )+ partial_body = _body_model_from_tensors(+ model_name=model_name, gender='neutral', tensors=partial_tensors+ )+ fitters[model_name] = smplfitter.pt.BodyFitter(partial_body)++ return body_models, fitters+++def _load_safetensors_checkpoint(checkpoint_path: Path) -> Tuple[Dict[str, torch.Tensor], Dict]:+ """Load checkpoint from safetensors format with separate meta.json."""+ from safetensors.torch import load_file++ # Load tensors+ state_dict = load_file(str(checkpoint_path))++ # Load meta from JSON+ meta_path = checkpoint_path.with_suffix('.meta.json')+ if not meta_path.exists():+ raise FileNotFoundError(f"Meta file not found: {meta_path}")++ with open(meta_path, 'r') as f:+ meta_json = json.load(f)++ # Reconstruct cano_all from prefixed tensors+ cano_all = {}+ cano_all_keys = meta_json.get('cano_all_keys', [])+ for k in cano_all_keys:+ tensor_key = f'__meta_cano_all_{k}'+ if tensor_key in state_dict:+ cano_all[k] = state_dict.pop(tensor_key)++ # Reconstruct skeleton_infos from prefixed tensors and meta+ skeleton_infos = {}+ skeleton_meta = meta_json.get('skeleton_infos', {})+ for skel_name, skel_info in skeleton_meta.items():+ skeleton_infos[skel_name] = {'names': skel_info.get('names', [])}+ indices_key = f'__meta_skeleton_{skel_name}_indices'+ edges_key = f'__meta_skeleton_{skel_name}_edges'+ if indices_key in state_dict:+ skeleton_infos[skel_name]['indices'] = state_dict.pop(indices_key)+ if edges_key in state_dict:+ skeleton_infos[skel_name]['edges'] = state_dict.pop(edges_key)++ # Build full meta dict+ meta = {+ 'crop_model': meta_json.get('crop_model', {}),+ 'pad_white_pixels': meta_json.get('pad_white_pixels', True),+ 'cano_all': cano_all,+ 'skeleton_infos': skeleton_infos,+ }++ return state_dict, meta+++def load_multiperson_nlf_eager(+ *,+ checkpoint_path: str | Path,+ yolox_onnx_path: str | Path,+ device: str | torch.device = 'cuda',+) -> MultipersonNLF:+ checkpoint_path = Path(checkpoint_path)++ # Support both .pth and .safetensors formats+ if checkpoint_path.suffix == '.safetensors':+ state_dict, meta = _load_safetensors_checkpoint(checkpoint_path)+ elif checkpoint_path.suffix == '.pth':+ ckpt = torch.load(str(checkpoint_path), map_location='cpu', weights_only=False)+ if isinstance(ckpt, dict) and 'state_dict' in ckpt:+ state_dict = ckpt['state_dict']+ meta = ckpt.get('meta', {})+ else:+ raise ValueError(+ 'Unsupported checkpoint format. Expected dict with `state_dict` and `meta`.'+ )+ else:+ raise ValueError(f'Unsupported checkpoint format: {checkpoint_path.suffix}')++ crop_state_dict = _strip_prefix(state_dict, 'crop_model.')+ crop_model = build_crop_model_from_state_dict(crop_state_dict, meta=meta)++ crop_model.backbone.half()+ crop_model.heatmap_head.layer.half()++ body_models, fitters = _build_body_models_and_fitters(state_dict)++ detector = PersonDetectorONNX(str(yolox_onnx_path))++ skeleton_infos = meta['skeleton_infos']+ pad_white_pixels = bool(meta.get('pad_white_pixels', True))+ cano_all = meta['cano_all']++ model = MultipersonNLF(+ crop_model,+ detector,+ skeleton_infos,+ pad_white_pixels=pad_white_pixels,+ cano_all=cano_all,+ body_models=body_models,+ fitters=fitters,+ )+ model.load_state_dict(state_dict, strict=False)+ model = model.to(device).eval()+ model.cano_all = {k: v.to(device=device, dtype=torch.float32) for k, v in model.cano_all.items()}+ return modeldiff --git a/models/wan/scail/nlf/field.py b/models/wan/scail/nlf/field.pynew file mode 100644index 0000000..66c6f68--- /dev/null+++ b/models/wan/scail/nlf/field.py@@ -0,0 +1,88 @@+"""Weight field for NLF."""+from __future__ import annotations++import numpy as np+import torch+import torch.nn as nn+++class GPSField(nn.Module):+ def __init__(+ self,+ gps_net,+ layer_dims,+ *,+ posenc_dim: int,+ r_sqrt_eigva: torch.Tensor | None = None,+ ):+ super().__init__()+ self.posenc_dim = int(posenc_dim)+ self.gps_net = gps_net++ self.pred_mlp = nn.Sequential()+ self.pred_mlp.append(nn.Linear(self.posenc_dim, layer_dims[0]))+ self.pred_mlp.append(nn.GELU())+ for i in range(1, len(layer_dims) - 1):+ self.pred_mlp.append(nn.Linear(layer_dims[i - 1], layer_dims[i]))+ self.pred_mlp.append(nn.GELU())+ self.pred_mlp.append(nn.Linear(layer_dims[-2], layer_dims[-1]))+ if r_sqrt_eigva is None:+ r_sqrt_eigva = torch.ones((self.posenc_dim,), dtype=torch.float32)+ self.r_sqrt_eigva = nn.Buffer(r_sqrt_eigva.to(dtype=torch.float32), persistent=False)++ def forward(self, inp):+ lbo = self.gps_net(inp.reshape(-1, 3))[..., : self.posenc_dim]+ lbo = torch.reshape(lbo, inp.shape[:-1] + (self.posenc_dim,))+ lbo = lbo * self.r_sqrt_eigva[: self.posenc_dim] * 0.1+ return self.pred_mlp(lbo)+++class GPSNet(nn.Module):+ def __init__(+ self,+ pos_enc_dim=512,+ hidden_dim=2048,+ output_dim=1024,+ *,+ mini: torch.Tensor | None = None,+ maxi: torch.Tensor | None = None,+ center: torch.Tensor | None = None,+ load_from_projdir: bool = False,+ ):+ super().__init__()+ self.factor = 1 / np.sqrt(np.float32(pos_enc_dim))+ if mini is None or maxi is None or center is None:+ mini = torch.tensor([-1.0, -1.0, -1.0], dtype=torch.float32)+ maxi = torch.tensor([1.0, 1.0, 1.0], dtype=torch.float32)+ center = torch.tensor([0.0, 0.0, 0.0], dtype=torch.float32)+ self.mini = nn.Buffer(mini.to(dtype=torch.float32), persistent=False)+ self.maxi = nn.Buffer(maxi.to(dtype=torch.float32), persistent=False)+ self.center = nn.Buffer(center.to(dtype=torch.float32), persistent=False)++ self.learnable_fourier = LearnableFourierFeatures(3, pos_enc_dim)+ self.mlp = nn.Sequential(+ nn.Linear(pos_enc_dim, hidden_dim),+ nn.GELU(),+ nn.Linear(hidden_dim, output_dim),+ )++ def forward(self, inp):+ x = (inp - self.center) / (self.maxi - self.mini)+ x = self.learnable_fourier(x) * self.factor+ return self.mlp(x)+++class LearnableFourierFeatures(nn.Module):+ def __init__(self, in_features, out_features):+ super().__init__()+ if out_features % 2 != 0:+ raise ValueError('out_features must be even (sin and cos in pairs)')+ self.linear = nn.Linear(in_features, out_features // 2, bias=False)+ self.reset_parameters()++ def reset_parameters(self):+ nn.init.normal_(self.linear.weight, std=12)++ def forward(self, inp):+ x = self.linear(inp)+ return torch.cat([torch.sin(x), torch.cos(x)], dim=-1)diff --git a/models/wan/scail/nlf/multiperson_model.py b/models/wan/scail/nlf/multiperson_model.pynew file mode 100644index 0000000..2215aa8--- /dev/null+++ b/models/wan/scail/nlf/multiperson_model.py@@ -0,0 +1,809 @@+"""Multiperson NLF model."""+from __future__ import annotations++import math+from typing import Dict, List, Optional++import numpy as np+import smplfitter.pt+import torch+import torchvision.transforms.v2.functional++from . import ptu, ptu3d+from . import plausibility_check as plausib+from . import warping+++class MultipersonNLF(torch.nn.Module):+ def __init__(+ self,+ crop_model,+ detector,+ skeleton_infos,+ pad_white_pixels=True,+ *,+ cano_all: Optional[Dict[str, torch.Tensor]] = None,+ body_models: Optional[torch.nn.ModuleDict] = None,+ fitters: Optional[torch.nn.ModuleDict] = None,+ ):+ super().__init__()++ self.crop_model = crop_model+ self.detector = detector+ device = next(self.crop_model.parameters()).device++ if body_models is None:+ raise ValueError("body_models must be provided for eager mode")+ self.body_models = body_models++ if fitters is None:+ raise ValueError("fitters must be provided for eager mode")+ if cano_all is None:+ raise ValueError("cano_all must be provided for eager mode")+ self.fitters = fitters++ self.cano_all = {+ k: v.to(device=device, dtype=torch.float32) for k, v in cano_all.items()+ }+ nothing = torch.zeros([], device=device, dtype=torch.float32)++ self.weights = {+ k: dict(+ w_tensor=nothing,+ b_tensor=nothing,+ w_tensor_flipped=nothing,+ b_tensor_flipped=nothing,+ )+ for k in self.body_models+ }+ self.per_skeleton_indices = {+ k: torch.as_tensor(v['indices'], dtype=torch.int32) for k, v in skeleton_infos.items()+ }+ self.per_skeleton_joint_names = {k: v['names'] for k, v in skeleton_infos.items()}+ self.per_skeleton_joint_edges = {+ k: torch.as_tensor(v['edges'], dtype=torch.int32) for k, v in skeleton_infos.items()+ }+ self.skeleton_joint_indices_table = {k: v['indices'] for k, v in skeleton_infos.items()}+ self.pad_white_pixels = pad_white_pixels++ def detect_parametric_batched(+ self,+ images: torch.Tensor,+ intrinsic_matrix: Optional[torch.Tensor] = None,+ distortion_coeffs: Optional[torch.Tensor] = None,+ extrinsic_matrix: Optional[torch.Tensor] = None,+ world_up_vector: Optional[torch.Tensor] = None,+ default_fov_degrees: float = 55.0,+ internal_batch_size: int = 64,+ antialias_factor: int = 1,+ num_aug: int = 1,+ rot_aug_max_degrees: float = 25.0,+ detector_threshold: float = 0.3,+ detector_nms_iou_threshold: float = 0.7,+ max_detections: int = 150,+ detector_flip_aug: bool = False,+ detector_both_flip_aug: bool = False,+ suppress_implausible_poses: bool = True,+ beta_regularizer: float = 10.0,+ beta_regularizer2: float = 0.0,+ model_name: str = 'smpl',+ extra_boxes: Optional[List[torch.Tensor]] = None,+ ):+ images = im_to_linear(images)++ boxes = self.detector(+ images=images,+ threshold=detector_threshold,+ nms_iou_threshold=detector_nms_iou_threshold,+ max_detections=max_detections,+ extrinsic_matrix=extrinsic_matrix,+ world_up_vector=world_up_vector,+ flip_aug=detector_flip_aug,+ bothflip_aug=detector_both_flip_aug,+ extra_boxes=extra_boxes,+ )+ return self._estimate_parametric_batched(+ images,+ boxes,+ intrinsic_matrix,+ distortion_coeffs,+ extrinsic_matrix,+ world_up_vector,+ default_fov_degrees,+ internal_batch_size,+ antialias_factor,+ num_aug,+ rot_aug_max_degrees,+ suppress_implausible_poses,+ beta_regularizer,+ beta_regularizer2,+ model_name,+ )++ detect_smpl_batched = detect_parametric_batched++ def _estimate_parametric_batched(+ self,+ images: torch.Tensor,+ boxes: List[torch.Tensor],+ intrinsic_matrix: Optional[torch.Tensor],+ distortion_coeffs: Optional[torch.Tensor],+ extrinsic_matrix: Optional[torch.Tensor],+ world_up_vector: Optional[torch.Tensor],+ default_fov_degrees: float,+ internal_batch_size: int,+ antialias_factor: int,+ num_aug: int,+ rot_aug_max_degrees: float,+ suppress_implausible_poses: bool,+ beta_regularizer: float,+ beta_regularizer2: float,+ model_name: str,+ ):+ if model_name not in self.body_models:+ raise ValueError(+ f'Unknown model name {model_name}, use one of {self.body_models.keys()}'+ )++ if self.weights[model_name]['w_tensor'].ndim == 0:+ self.weights[model_name] = self.get_weights_for_canonical_points(+ self.cano_all[model_name]+ )++ result = self._estimate_poses_batched(+ images,+ boxes,+ self.weights[model_name],+ intrinsic_matrix,+ distortion_coeffs,+ extrinsic_matrix,+ world_up_vector,+ default_fov_degrees,+ internal_batch_size,+ antialias_factor,+ num_aug,+ rot_aug_max_degrees,+ suppress_implausible_poses=suppress_implausible_poses,+ )+ boxes = result['boxes']+ n_pose_per_image_list = [len(b) for b in boxes]+ if sum(n_pose_per_image_list) == 0:+ return self._predict_empty_parametric(images, model_name)++ poses3d_flat = torch.cat(result['poses3d'], dim=0)+ mean_poses = torch.mean(poses3d_flat, dim=-2, keepdim=True)+ poses3d_flat = poses3d_flat - mean_poses+ poses2d_flat = torch.cat(result['poses2d'], dim=0)+ uncertainties_flat = torch.cat(result['uncertainties'], dim=0)++ fitter = self.fitters['smpl'] if model_name == 'smpl' else self.fitters['smplx']+ vertices_flat, joints_flat = torch.split(+ poses3d_flat, [fitter.body_model.num_vertices, fitter.body_model.num_joints], dim=-2+ )+ vertex_uncertainties_flat, joint_uncertainties_flat = torch.split(+ uncertainties_flat,+ [fitter.body_model.num_vertices, fitter.body_model.num_joints],+ dim=-1,+ )++ vertex_weights = vertex_uncertainties_flat**-1.5+ vertex_weights = vertex_weights / torch.mean(vertex_weights, dim=-1, keepdim=True)+ joint_weights = joint_uncertainties_flat**-1.5+ joint_weights = joint_weights / torch.mean(joint_weights, dim=-1, keepdim=True)++ fit = fitter.fit(+ vertices_flat / 1000,+ joints_flat / 1000,+ vertex_weights=vertex_weights,+ joint_weights=joint_weights,+ num_iter=3,+ beta_regularizer=beta_regularizer,+ beta_regularizer2=beta_regularizer2,+ final_adjust_rots=True,+ requested_keys=['pose_rotvecs', 'shape_betas', 'trans'],+ )++ result['pose'] = torch.split(fit['pose_rotvecs'], n_pose_per_image_list)+ result['betas'] = torch.split(fit['shape_betas'], n_pose_per_image_list)+ result['trans'] = torch.split(+ fit['trans'] + mean_poses.squeeze(-2) / 1000, n_pose_per_image_list+ )++ body_model: smplfitter.pt.BodyModel = (+ self.body_models['smpl'] if model_name == 'smpl' else self.body_models['smplx']+ )+ fit_res = body_model.forward(+ fit['pose_rotvecs'], fit['shape_betas'], fit['trans'] + mean_poses.squeeze(-2) / 1000+ )+ fit_vertices_flat = fit_res['vertices'] * 1000+ fit_joints_flat = fit_res['joints'] * 1000+ result['vertices3d'] = torch.split(fit_vertices_flat, n_pose_per_image_list)+ result['joints3d'] = torch.split(fit_joints_flat, n_pose_per_image_list)++ result['vertices2d'] = project_ragged(+ images,+ [x for x in result['vertices3d']],+ extrinsic_matrix,+ intrinsic_matrix,+ distortion_coeffs,+ default_fov_degrees,+ )+ result['joints2d'] = project_ragged(+ images,+ [x for x in result['joints3d']],+ extrinsic_matrix,+ intrinsic_matrix,+ distortion_coeffs,+ default_fov_degrees,+ )++ result['vertices3d_nonparam'] = torch.split(+ vertices_flat + mean_poses, n_pose_per_image_list+ )+ result['joints3d_nonparam'] = torch.split(joints_flat + mean_poses, n_pose_per_image_list)+ vertices2d, joints2d = torch.split(+ poses2d_flat, [fitter.body_model.num_vertices, fitter.body_model.num_joints], dim=-2+ )++ result['vertices2d_nonparam'] = torch.split(vertices2d, n_pose_per_image_list)+ result['joints2d_nonparam'] = torch.split(joints2d, n_pose_per_image_list)++ result['vertex_uncertainties'] = torch.split(+ vertex_uncertainties_flat * 1000, n_pose_per_image_list+ )+ result['joint_uncertainties'] = torch.split(+ joint_uncertainties_flat * 1000, n_pose_per_image_list+ )++ del result['poses3d']+ del result['poses2d']+ del result['uncertainties']+ return result++ def _estimate_poses_batched(+ self,+ images: torch.Tensor,+ boxes: List[torch.Tensor],+ weights: Dict[str, torch.Tensor],+ intrinsic_matrix: Optional[torch.Tensor],+ distortion_coeffs: Optional[torch.Tensor],+ extrinsic_matrix: Optional[torch.Tensor],+ world_up_vector: Optional[torch.Tensor],+ default_fov_degrees: float,+ internal_batch_size: int,+ antialias_factor: int,+ num_aug: int,+ rot_aug_max_degrees: float,+ suppress_implausible_poses: bool,+ ):+ if sum(len(b) for b in boxes) == 0:+ return self._predict_empty(images, weights)++ images = im_to_linear(images)++ n_images = len(images)+ device = images.device++ if intrinsic_matrix is None:+ intrinsic_matrix = ptu3d.intrinsic_matrix_from_field_of_view(+ default_fov_degrees, images.shape[2:4], device=device+ )++ if len(intrinsic_matrix) == 1:+ intrinsic_matrix = torch.repeat_interleave(intrinsic_matrix, n_images, dim=0)++ if distortion_coeffs is None:+ distortion_coeffs = torch.zeros((n_images, 5), device=device)+ if len(distortion_coeffs) == 1:+ distortion_coeffs = torch.repeat_interleave(distortion_coeffs, n_images, dim=0)++ if extrinsic_matrix is None:+ extrinsic_matrix = torch.eye(4, device=device).unsqueeze(0)+ if len(extrinsic_matrix) == 1:+ extrinsic_matrix = torch.repeat_interleave(extrinsic_matrix, n_images, dim=0)++ n_box_per_image_list = [len(b) for b in boxes]+ n_box_per_image = torch.tensor([len(b) for b in boxes], device=device)++ intrinsic_matrix = torch.repeat_interleave(intrinsic_matrix, n_box_per_image, dim=0)+ distortion_coeffs = torch.repeat_interleave(distortion_coeffs, n_box_per_image, dim=0)++ if world_up_vector is None:+ world_up_vector = torch.tensor([0, -1, 0], device=device, dtype=torch.float32)++ camspace_up = torch.einsum('c,bCc->bC', world_up_vector, extrinsic_matrix[..., :3, :3])+ camspace_up = torch.repeat_interleave(camspace_up, n_box_per_image, dim=0)++ aug_gammas = ptu.linspace(0.6, 1.0, num_aug, dtype=torch.float32, device=device)++ aug_angle_range = rot_aug_max_degrees * (torch.pi / 180.0)+ aug_angles = ptu.linspace(+ -aug_angle_range, aug_angle_range, num_aug, dtype=torch.float32, device=device+ )++ if num_aug == 1:+ aug_scales = torch.tensor([1.0], device=device, dtype=torch.float32)+ else:+ aug_scales = torch.cat(+ [+ ptu.linspace(+ 0.8, 1.0, num_aug // 2, endpoint=False, dtype=torch.float32, device=device+ ),+ torch.linspace(+ 1.0, 1.1, num_aug - num_aug // 2, dtype=torch.float32, device=device+ ),+ ],+ dim=0,+ )+ aug_should_flip = (torch.arange(0, num_aug, device=device) - num_aug // 2) % 2 != 0+ aug_flipmat = torch.tensor(+ [[-1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=torch.float32, device=device+ )+ aug_maybe_flipmat = torch.where(+ aug_should_flip[:, torch.newaxis, torch.newaxis],+ aug_flipmat,+ torch.eye(3, device=device),+ )+ aug_rotmat = ptu3d.rotation_mat(-aug_angles, rot_axis='z')+ aug_rotflipmat = aug_maybe_flipmat @ aug_rotmat++ poses3d_flat, uncert_flat = self._predict_in_batches(+ images,+ weights,+ intrinsic_matrix,+ distortion_coeffs,+ camspace_up,+ boxes,+ internal_batch_size,+ aug_should_flip,+ aug_rotflipmat,+ aug_gammas,+ aug_scales,+ antialias_factor,+ )+ poses3d_flat = plausib.scale_align(poses3d_flat)+ mean = torch.mean(poses3d_flat, dim=(-3, -2), keepdim=True)+ poses3d_flat_submean = (poses3d_flat - mean).float()+ poses3d_flat_submean, final_weights = weighted_geometric_median(+ poses3d_flat_submean, uncert_flat**-1.5, dim=-3, n_iter=10, eps=50.0+ )+ poses3d_flat = poses3d_flat_submean.double() + mean.squeeze(1)++ uncert_flat = weighted_mean(uncert_flat, final_weights, dim=-2)++ poses2d_flat_normalized = ptu3d.to_homogeneous(+ warping.distort_points(ptu3d.project(poses3d_flat.float()), distortion_coeffs)+ )+ poses2d_flat = torch.einsum(+ 'bnk,bjk->bnj', poses2d_flat_normalized, intrinsic_matrix[:, :2, :]+ )++ poses3d = torch.split(poses3d_flat, n_box_per_image_list)+ poses2d = torch.split(poses2d_flat, n_box_per_image_list)+ uncert = torch.split(uncert_flat, n_box_per_image_list)++ if suppress_implausible_poses:+ boxes, poses3d, poses2d, uncert = self._filter_poses(boxes, poses3d, poses2d, uncert)++ n_box_per_image_list = [len(b) for b in boxes]++ if sum(n_box_per_image_list) == 0:+ return self._predict_empty(images, weights)++ n_box_per_image = torch.tensor(n_box_per_image_list, device=device)+ inv_extrinsic_matrix = torch.repeat_interleave(+ torch.linalg.inv(extrinsic_matrix.double()), n_box_per_image, dim=0+ )+ poses3d_flat = torch.einsum(+ 'bnk,bjk->bnj',+ ptu3d.to_homogeneous(torch.cat(poses3d)),+ inv_extrinsic_matrix[:, :3, :],+ )+ poses3d = torch.split(poses3d_flat.float(), n_box_per_image_list)++ result = dict(boxes=boxes, poses3d=poses3d, poses2d=poses2d, uncertainties=uncert)+ return result++ def _filter_poses(+ self,+ boxes: List[torch.Tensor],+ poses3d: List[torch.Tensor],+ poses2d: List[torch.Tensor],+ uncert: List[torch.Tensor],+ ):+ boxes_out = []+ poses3d_out = []+ poses2d_out = []+ uncert_out = []+ for boxes_, poses3d_, poses2d_, uncert_ in zip(boxes, poses3d, poses2d, uncert):+ is_uncert_low = plausib.is_uncertainty_low(uncert_)+ is_pose_consi = plausib.is_pose_consistent_with_box(poses2d_, boxes_)+ plausible_mask = torch.logical_and(is_uncert_low, is_pose_consi)+ nms_indices = plausib.pose_non_max_suppression(+ poses3d_, boxes_[..., 4] / torch.mean(uncert_, dim=-1), plausible_mask+ )+ boxes_out.append(boxes_[nms_indices])+ poses3d_out.append(poses3d_[nms_indices])+ poses2d_out.append(poses2d_[nms_indices])+ uncert_out.append(uncert_[nms_indices])+ return boxes_out, poses3d_out, poses2d_out, uncert_out++ def _predict_in_batches(+ self,+ images: torch.Tensor,+ weights: Dict[str, torch.Tensor],+ intrinsic_matrix: torch.Tensor,+ distortion_coeffs: torch.Tensor,+ camspace_up: torch.Tensor,+ boxes: List[torch.Tensor],+ internal_batch_size: int,+ aug_should_flip: torch.Tensor,+ aug_rotflipmat: torch.Tensor,+ aug_gammas: torch.Tensor,+ aug_scales: torch.Tensor,+ antialias_factor: int,+ ):+ num_aug = len(aug_gammas)+ boxes_per_batch = internal_batch_size // num_aug+ boxes_flat = torch.cat(boxes, dim=0)+ image_id_per_box = torch.repeat_interleave(+ torch.arange(len(boxes)), torch.tensor([len(b) for b in boxes])+ )++ if boxes_per_batch == 0:+ return self._predict_single_batch(+ images,+ weights,+ intrinsic_matrix,+ distortion_coeffs,+ camspace_up,+ boxes_flat,+ image_id_per_box,+ aug_rotflipmat,+ aug_should_flip,+ aug_scales,+ aug_gammas,+ antialias_factor,+ )+ else:+ n_total_boxes = len(boxes_flat)+ n_batches = int(math.ceil(n_total_boxes / boxes_per_batch))+ poses3d_batches = []+ uncert_batches = []+ for i in range(n_batches):+ batch_slice = slice(i * boxes_per_batch, (i + 1) * boxes_per_batch)+ poses3d, uncert = self._predict_single_batch(+ images,+ weights,+ intrinsic_matrix[batch_slice],+ distortion_coeffs[batch_slice],+ camspace_up[batch_slice],+ boxes_flat[batch_slice],+ image_id_per_box[batch_slice],+ aug_rotflipmat,+ aug_should_flip,+ aug_scales,+ aug_gammas,+ antialias_factor,+ )+ poses3d_batches.append(poses3d)+ uncert_batches.append(uncert)+ return torch.cat(poses3d_batches, dim=0), torch.cat(uncert_batches, dim=0)++ def _predict_single_batch(+ self,+ images: torch.Tensor,+ weights: Dict[str, torch.Tensor],+ intrinsic_matrix: torch.Tensor,+ distortion_coeffs: torch.Tensor,+ camspace_up: torch.Tensor,+ boxes: torch.Tensor,+ image_ids: torch.Tensor,+ aug_rotflipmat: torch.Tensor,+ aug_should_flip: torch.Tensor,+ aug_scales: torch.Tensor,+ aug_gammas: torch.Tensor,+ antialias_factor: int,+ ):+ crops, new_intrinsic_matrix, R = self._get_crops(+ images,+ intrinsic_matrix,+ distortion_coeffs,+ camspace_up,+ boxes,+ image_ids,+ aug_rotflipmat,+ aug_scales,+ aug_gammas,+ antialias_factor,+ )++ new_intrinsic_matrix_flat = torch.reshape(new_intrinsic_matrix, (-1, 3, 3))+ res = self.crop_model.input_resolution+ crops_flat = torch.reshape(crops, (-1, 3, res, res))++ n_cases = crops.shape[1]+ aug_should_flip_flat = torch.repeat_interleave(aug_should_flip, n_cases, dim=0)++ poses_flat, uncert_flat = self.crop_model.predict_multi_same_weights(+ crops_flat, new_intrinsic_matrix_flat, weights, aug_should_flip_flat+ )+ poses_flat = poses_flat.double()+ n_joints = poses_flat.shape[-2]++ poses = torch.reshape(poses_flat, [-1, n_cases, n_joints, 3])+ uncert = torch.reshape(uncert_flat, [-1, n_cases, n_joints])+ poses_orig_camspace = poses @ R.double()++ return poses_orig_camspace.transpose(0, 1), uncert.transpose(0, 1)++ def _get_crops(+ self,+ images: torch.Tensor,+ intrinsic_matrix: torch.Tensor,+ distortion_coeffs: torch.Tensor,+ camspace_up: torch.Tensor,+ boxes: torch.Tensor,+ image_ids: torch.Tensor,+ aug_rotflipmat: torch.Tensor,+ aug_scales: torch.Tensor,+ aug_gammas: torch.Tensor,+ antialias_factor: int,+ ):+ R_noaug, box_scales = self._get_new_rotation_and_scale(+ intrinsic_matrix, distortion_coeffs, camspace_up, boxes+ )++ device = images.device+ crop_scales = aug_scales[:, torch.newaxis] * box_scales[torch.newaxis, :]+ num_box = boxes.shape[0]+ num_aug = aug_gammas.shape[0]+ res = self.crop_model.input_resolution+ new_intrinsic_matrix = torch.cat(+ [+ torch.cat(+ [+ intrinsic_matrix[torch.newaxis, :, :2, :2]+ * crop_scales[:, :, torch.newaxis, torch.newaxis],+ torch.full(+ (num_aug, num_box, 2, 1), res / 2, dtype=torch.float32, device=device+ ),+ ],+ dim=3,+ ),+ torch.cat(+ [+ torch.zeros((num_aug, num_box, 1, 2), dtype=torch.float32, device=device),+ torch.ones((num_aug, num_box, 1, 1), dtype=torch.float32, device=device),+ ],+ dim=3,+ ),+ ],+ dim=2,+ )+ R = aug_rotflipmat[:, torch.newaxis] @ R_noaug+ new_invprojmat = torch.linalg.inv(new_intrinsic_matrix @ R)++ if antialias_factor > 1:+ scaling_mat = warping.corner_aligned_scale_mat(1 / antialias_factor)+ new_invprojmat = new_invprojmat @ scaling_mat.to(new_invprojmat.device)++ if self.pad_white_pixels:+ images.neg_().add_(1)++ crops = warping.warp_images_with_pyramid(+ images,+ intrinsic_matrix=torch.tile(intrinsic_matrix, [num_aug, 1, 1]),+ new_invprojmats=torch.reshape(new_invprojmat, [-1, 3, 3]),+ distortion_coeffs=torch.tile(distortion_coeffs, [num_aug, 1]),+ crop_scales=torch.reshape(crop_scales, [-1]) * antialias_factor,+ output_shape=(res * antialias_factor, res * antialias_factor),+ image_ids=torch.tile(image_ids, [num_aug]),+ )+ if self.pad_white_pixels:+ crops.neg_().add_(1).clamp_(0, 1)++ if antialias_factor == 2:+ crops = torch.nn.functional.avg_pool2d(crops, 2, 2)+ elif antialias_factor == 4:+ crops = torch.nn.functional.avg_pool2d(crops, 4, 4)+ elif antialias_factor > 4:+ crops = torchvision.transforms.v2.functional.resize(+ crops,+ (res, res),+ torchvision.transforms.v2.functional.InterpolationMode.BILINEAR,+ antialias=True,+ )+ crops = torch.reshape(crops, [num_aug, num_box, 3, res, res])+ crops **= torch.reshape(aug_gammas.to(crops.dtype) / 2.2, [-1, 1, 1, 1, 1])+ return crops, new_intrinsic_matrix, R++ def _get_new_rotation_and_scale(self, intrinsic_matrix, distortion_coeffs, camspace_up, boxes):+ x, y, w, h = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]+ boxpoints_homog = ptu3d.to_homogeneous(+ torch.stack(+ [+ torch.stack([x + w / 2, y + h / 2], dim=1),+ torch.stack([x + w / 2, y], dim=1),+ torch.stack([x + w, y + h / 2], dim=1),+ torch.stack([x + w / 2, y + h], dim=1),+ torch.stack([x, y + h / 2], dim=1),+ ],+ dim=1,+ )+ )++ boxpoints_camspace = torch.einsum(+ 'bpc,bCc->bpC', boxpoints_homog, torch.linalg.inv(intrinsic_matrix)+ )+ boxpoints_camspace = ptu3d.to_homogeneous(+ warping.undistort_points(boxpoints_camspace[:, :, :2], distortion_coeffs)+ )+ box_center_camspace = boxpoints_camspace[:, 0]+ R_noaug = ptu3d.lookat_matrix(forward_vector=box_center_camspace, up_vector=camspace_up)++ sidepoints_camspace = boxpoints_camspace[:, 1:5]+ sidepoints_new = ptu3d.project(+ torch.einsum('bpc,bCc->bpC', sidepoints_camspace, intrinsic_matrix @ R_noaug)+ )++ vertical_size = torch.linalg.norm(sidepoints_new[:, 0] - sidepoints_new[:, 2], dim=-1)+ horiz_size = torch.linalg.norm(sidepoints_new[:, 1] - sidepoints_new[:, 3], dim=-1)+ box_size_new = torch.maximum(vertical_size, horiz_size)++ box_scales = (+ torch.tensor(self.crop_model.input_resolution, dtype=box_size_new.dtype) / box_size_new+ )+ return R_noaug, box_scales++ def _predict_empty(self, image: torch.Tensor, weights: Dict[str, torch.Tensor]):+ device = image.device+ n_joints = weights['w_tensor'].shape[0]+ poses3d = torch.zeros((0, n_joints, 3), dtype=torch.float32, device=device)+ poses2d = torch.zeros((0, n_joints, 2), dtype=torch.float32, device=device)+ uncert = torch.zeros((0, n_joints), dtype=torch.float32, device=device)+ boxes = torch.zeros((0, 5), dtype=torch.float32, device=device)+ n_images = image.shape[0]++ result = dict(+ boxes=[boxes] * n_images,+ poses3d=[poses3d] * n_images,+ poses2d=[poses2d] * n_images,+ uncertainties=[uncert] * n_images,+ )+ return result++ def _predict_empty_parametric(self, image: torch.Tensor, model_name: str):+ device = image.device+ fitter = self.fitters['smpl'] if model_name == 'smpl' else self.fitters['smplx']+ n_joints = fitter.body_model.num_joints+ n_verts = fitter.body_model.num_vertices+ pose = torch.zeros((0, n_joints, 3), dtype=torch.float32, device=device)+ betas = torch.zeros((0, fitter.body_model.num_betas), dtype=torch.float32, device=device)+ trans = torch.zeros((0, 3), dtype=torch.float32, device=device)+ vertices3d = torch.zeros((0, n_verts, 3), dtype=torch.float32, device=device)+ joints3d = torch.zeros((0, n_joints, 3), dtype=torch.float32, device=device)+ vertices2d = torch.zeros((0, n_verts, 2), dtype=torch.float32, device=device)+ joints2d = torch.zeros((0, n_joints, 2), dtype=torch.float32, device=device)+ vertices3d_nonparam = torch.zeros((0, n_verts, 3), dtype=torch.float32, device=device)+ joints3d_nonparam = torch.zeros((0, n_joints, 3), dtype=torch.float32, device=device)+ vertices2d_nonparam = torch.zeros((0, n_verts, 2), dtype=torch.float32, device=device)+ joints2d_nonparam = torch.zeros((0, n_joints, 2), dtype=torch.float32, device=device)+ vertex_uncertainties = torch.zeros((0, n_verts), dtype=torch.float32, device=device)+ joint_uncertainties = torch.zeros((0, n_joints), dtype=torch.float32, device=device)+ n_images = image.shape[0]+ result = dict(+ pose=[pose] * n_images,+ betas=[betas] * n_images,+ trans=[trans] * n_images,+ vertices3d=[vertices3d] * n_images,+ joints3d=[joints3d] * n_images,+ vertices2d=[vertices2d] * n_images,+ joints2d=[joints2d] * n_images,+ vertices3d_nonparam=[vertices3d_nonparam] * n_images,+ joints3d_nonparam=[joints3d_nonparam] * n_images,+ vertices2d_nonparam=[vertices2d_nonparam] * n_images,+ joints2d_nonparam=[joints2d_nonparam] * n_images,+ vertex_uncertainties=[vertex_uncertainties] * n_images,+ joint_uncertainties=[joint_uncertainties] * n_images,+ )+ return result++ def get_weights_for_canonical_points(self, canonical_points: torch.Tensor):+ return self.crop_model.get_weights_for_canonical_points(canonical_points)+++def im_to_linear(im: torch.Tensor):+ if im.dtype == torch.uint8:+ return im.to(dtype=torch.float16).mul_(1.0 / 255.0).pow_(2.2)+ elif im.dtype == torch.uint16:+ return im.to(dtype=torch.float16).mul_(1.0 / 65504.0).nan_to_num_(posinf=1.0).pow_(2.2)+ elif im.dtype == torch.float16:+ return im**2.2+ else:+ return im.to(dtype=torch.float16).pow_(2.2)+++def project_ragged(+ images: torch.Tensor,+ poses3d: List[torch.Tensor],+ extrinsic_matrix: Optional[torch.Tensor],+ intrinsic_matrix: Optional[torch.Tensor],+ distortion_coeffs: Optional[torch.Tensor],+ default_fov_degrees: float = 55.0,+):+ device = images.device+ n_box_per_image_list = [len(b) for b in poses3d]+ n_box_per_image = torch.tensor([len(b) for b in poses3d], device=device)++ n_images = images.shape[0]++ if intrinsic_matrix is None:+ intrinsic_matrix = ptu3d.intrinsic_matrix_from_field_of_view(+ default_fov_degrees, images.shape[2:4], device=device+ )++ if intrinsic_matrix.shape[0] == 1:+ intrinsic_matrix = torch.repeat_interleave(intrinsic_matrix, n_images, dim=0)++ if distortion_coeffs is None:+ distortion_coeffs = torch.zeros((n_images, 5), device=device)++ if distortion_coeffs.shape[0] == 1:+ distortion_coeffs = torch.repeat_interleave(distortion_coeffs, n_images, dim=0)++ if extrinsic_matrix is None:+ extrinsic_matrix = torch.eye(4, device=device).unsqueeze(0)+ if extrinsic_matrix.shape[0] == 1:+ extrinsic_matrix = torch.repeat_interleave(extrinsic_matrix, n_images, dim=0)++ intrinsic_matrix_rep = torch.repeat_interleave(intrinsic_matrix, n_box_per_image, dim=0)+ distortion_coeffs_rep = torch.repeat_interleave(distortion_coeffs, n_box_per_image, dim=0)+ extrinsic_matrix_rep = torch.repeat_interleave(extrinsic_matrix, n_box_per_image, dim=0)++ poses3d_flat = torch.cat(poses3d, dim=0)+ poses3d_flat = torch.einsum(+ 'bnk,bjk->bnj', ptu3d.to_homogeneous(poses3d_flat), extrinsic_matrix_rep[:, :3, :]+ )++ poses2d_flat_normalized = ptu3d.to_homogeneous(+ warping.distort_points(ptu3d.project(poses3d_flat), distortion_coeffs_rep)+ )+ poses2d_flat = torch.einsum(+ 'bnk,bjk->bnj', poses2d_flat_normalized, intrinsic_matrix_rep[:, :2, :]+ )+ poses2d = torch.split(poses2d_flat, n_box_per_image_list)+ return poses2d+++def weighted_geometric_median(+ x: torch.Tensor,+ w: Optional[torch.Tensor],+ n_iter: int = 10,+ dim: int = -2,+ eps: float = 1e-1,+ keepdim: bool = False,+):+ if dim < 0:+ dim = len(x.shape) + dim++ if w is None:+ w = torch.ones_like(x[..., :1])+ else:+ w = w.unsqueeze(-1)++ new_weights = w+ y = weighted_mean(x, new_weights, dim=dim, keepdim=True)+ for _ in range(n_iter):+ dist = torch.norm(x - y, dim=-1, keepdim=True)+ new_weights = w / (dist + eps)+ y = weighted_mean(x, new_weights, dim=dim, keepdim=True)++ if not keepdim:+ y = y.squeeze(dim)++ return y, new_weights.squeeze(-1)+++def weighted_mean(x: torch.Tensor, w: torch.Tensor, dim: int = -2, keepdim: bool = False):+ return (x * w).sum(dim=dim, keepdim=keepdim) / w.sum(dim=dim, keepdim=keepdim)diff --git a/models/wan/scail/nlf/nlf_model.py b/models/wan/scail/nlf/nlf_model.pynew file mode 100644index 0000000..0c23cb0--- /dev/null+++ b/models/wan/scail/nlf/nlf_model.py@@ -0,0 +1,253 @@+"""NLF (Neural Localizer Fields) model."""+from __future__ import annotations++from dataclasses import dataclass+from typing import Dict, Optional++import torch+import torch.nn as nn+import torch.nn.functional as F++from . import ptu, ptu3d+from . import util as model_util+++@dataclass(frozen=True)+class NLFModelConfig:+ proc_side: int+ stride_test: int+ centered_stride: bool+ backbone_link_dim: int+ depth: int+ box_size_m: float+ uncert_bias: float = 0.0+ uncert_bias2: float = 0.001+ fix_uncert_factor: bool = False+ mix_3d_inside_fov: float = 0.5+ weak_perspective: bool = False+++class NLFModel(nn.Module):+ def __init__(+ self,+ backbone,+ weight_field,+ normalizer,+ backbone_channels=1280,+ *,+ config: Optional[NLFModelConfig] = None,+ n_joints: Optional[int] = None,+ n_left_joints: Optional[int] = None,+ n_center_joints: Optional[int] = None,+ ):+ super().__init__()+ if config is None:+ raise ValueError("config must be provided")+ self.backbone = backbone+ self.heatmap_head = LocalizerHead(+ weight_field, normalizer, in_channels=backbone_channels, config=config+ )+ self.input_resolution = int(config.proc_side)++ if n_joints is None or n_left_joints is None or n_center_joints is None:+ raise ValueError("n_joints, n_left_joints, n_center_joints must be provided")++ inv_permutation = torch.arange(int(n_joints), dtype=torch.int64)+ canonical_locs_init = torch.zeros((int(n_joints), 3), dtype=torch.float32)+ canonical_delta_mask = torch.ones((int(n_joints),), dtype=torch.float32)++ self.inv_permutation = nn.Buffer(inv_permutation.to(dtype=torch.int64), persistent=False)+ self.canonical_lefts = nn.Parameter(+ torch.zeros((int(n_left_joints), 3), dtype=torch.float32)+ )+ self.canonical_centers = nn.Parameter(+ torch.zeros((int(n_center_joints), 2), dtype=torch.float32)+ )+ self.canonical_locs_init = nn.Buffer(+ canonical_locs_init.to(dtype=torch.float32), persistent=False+ )+ self.canonical_delta_mask = nn.Buffer(+ canonical_delta_mask.to(dtype=torch.float32), persistent=False+ )++ @torch.jit.export+ def canonical_locs(self):+ canonical_rights = torch.cat(+ [-self.canonical_lefts[:, :1], self.canonical_lefts[:, 1:]], dim=1+ )+ canonical_centers = torch.cat(+ [torch.zeros_like(self.canonical_centers[:, :1]), self.canonical_centers], dim=1+ )+ permuted = torch.cat([self.canonical_lefts, canonical_rights, canonical_centers], dim=0)+ return (+ permuted.index_select(0, self.inv_permutation)+ * self.canonical_delta_mask[:, torch.newaxis]+ + self.canonical_locs_init+ )++ @torch.jit.export+ def get_features(self, image: torch.Tensor):+ f = self.backbone(image)+ return self.heatmap_head.layer(f)++ @torch.jit.export+ def predict_multi_same_weights(+ self,+ image: torch.Tensor,+ intrinsic_matrix: torch.Tensor,+ weights: Dict[str, torch.Tensor],+ flip_canonicals_per_image: torch.Tensor,+ ):+ features_processed = self.get_features(image)+ coords2d, coords3d, uncertainties = self.heatmap_head.decode_features_multi_same_weights(+ features_processed, weights, flip_canonicals_per_image+ )++ with torch.amp.autocast('cuda', enabled=False):+ return self.heatmap_head.reconstruct_absolute(+ coords2d.float(), coords3d.float(), uncertainties.float(), intrinsic_matrix.float()+ )++ @torch.jit.export+ def get_weights_for_canonical_points(self, canonical_points: torch.Tensor):+ return self.heatmap_head.get_weights_for_canonical_points(canonical_points)+++class LocalizerHead(nn.Module):+ def __init__(self, weight_field, normalizer, in_channels=1280, *, config: NLFModelConfig):+ super().__init__()+ self.uncert_bias = float(config.uncert_bias)+ self.uncert_bias2 = float(config.uncert_bias2)+ self.depth = int(config.depth)+ self.weight_field = weight_field+ self.stride_test = int(config.stride_test)+ self.centered_stride = bool(config.centered_stride)+ self.box_size_m = float(config.box_size_m)+ self.proc_side = int(config.proc_side)+ self.backbone_link_dim = int(config.backbone_link_dim)+ self.fix_uncert_factor = bool(config.fix_uncert_factor)+ self.mix_3d_inside_fov = float(config.mix_3d_inside_fov)+ self.weak_perspective = bool(config.weak_perspective)+ self.layer = nn.Sequential(+ nn.Conv2d(in_channels, self.backbone_link_dim, kernel_size=1, bias=False),+ normalizer(self.backbone_link_dim),+ nn.SiLU(),+ )++ @torch.jit.export+ def transpose_weights(self, weights: torch.Tensor, n_in_channels: int):+ n_out_channels = 2 + self.depth+ weights_resh = torch.unflatten(weights, -1, (n_in_channels + 1, n_out_channels))+ w_tensor = weights_resh[..., :-1, :]+ b_tensor = weights_resh[..., -1, :]+ w_tensor = w_tensor.permute(0, 2, 1)+ return w_tensor.contiguous(), b_tensor.contiguous()++ @torch.jit.export+ def apply_weights3d_same_canonicals_impl(+ self, features: torch.Tensor, w_tensor: torch.Tensor, b_tensor: torch.Tensor+ ):+ n_out_channels = 2 + self.depth+ w_tensor = torch.flatten(w_tensor, start_dim=0, end_dim=1).unsqueeze(-1).unsqueeze(-1)+ b_tensor = b_tensor.reshape(-1)++ logits = F.conv2d(features, w_tensor, bias=b_tensor).float()+ logits = torch.unflatten(logits, 1, (-1, n_out_channels))+ uncertainty_map = logits[:, :, 0]++ coords_metric_xy = ptu.soft_argmax(logits[:, :, 1], dim=[3, 2])+ heatmap25d = ptu.softmax(logits[:, :, 2:], dim=[4, 3, 2])+ heatmap2d = torch.sum(heatmap25d, dim=2)++ uncertainties = torch.einsum('nphw,nphw->np', uncertainty_map, heatmap2d.detach())+ uncertainties = F.softplus(uncertainties + self.uncert_bias) + self.uncert_bias2+ coords25d = ptu.decode_heatmap(heatmap25d, dim=[4, 3, 2])+ coords2d = coords25d[..., :2]+ coords3d = torch.cat([coords_metric_xy, coords25d[..., 2:]], dim=-1)+ return coords2d, coords3d, uncertainties++ @torch.jit.export+ def get_weights_for_canonical_points(self, canonical_points: torch.Tensor):+ weights = self.weight_field(canonical_points)+ w_tensor, b_tensor = self.transpose_weights(weights.half(), self.backbone_link_dim)+ weights_fl = self.weight_field(+ canonical_points+ * torch.tensor([-1, 1, 1], dtype=torch.float32, device=canonical_points.device)+ )+ w_tensor_fl, b_tensor_fl = self.transpose_weights(weights_fl.half(), self.backbone_link_dim)+ return dict(+ w_tensor=w_tensor,+ b_tensor=b_tensor,+ w_tensor_flipped=w_tensor_fl,+ b_tensor_flipped=b_tensor_fl,+ )++ @torch.jit.export+ def decode_features_multi_same_weights(+ self,+ features: torch.Tensor,+ weights: Dict[str, torch.Tensor],+ flip_canonicals_per_image: torch.Tensor,+ ):+ features_processed = features+ flip_canonicals_per_image_ind = flip_canonicals_per_image.to(torch.int32)++ nfl_features_processed, fl_features_processed = ptu.dynamic_partition(+ features_processed, flip_canonicals_per_image_ind, 2+ )+ partitioned_indices = ptu.dynamic_partition(+ torch.arange(features_processed.shape[0], device=flip_canonicals_per_image_ind.device),+ flip_canonicals_per_image_ind,+ 2,+ )+ nfl_coords2d, nfl_coords3d, nfl_uncertainties = self.apply_weights3d_same_canonicals_impl(+ nfl_features_processed, weights['w_tensor'], weights['b_tensor']+ )+ fl_coords2d, fl_coords3d, fl_uncertainties = self.apply_weights3d_same_canonicals_impl(+ fl_features_processed, weights['w_tensor_flipped'], weights['b_tensor_flipped']+ )+ coords2d = ptu.dynamic_stitch(partitioned_indices, [nfl_coords2d, fl_coords2d])+ coords3d = ptu.dynamic_stitch(partitioned_indices, [nfl_coords3d, fl_coords3d])+ uncertainties = ptu.dynamic_stitch(+ partitioned_indices, [nfl_uncertainties, fl_uncertainties]+ )++ coords2d = model_util.heatmap_to_image(+ coords2d, self.proc_side, self.stride_test, self.centered_stride+ )+ coords3d = model_util.heatmap_to_metric(+ coords3d,+ self.proc_side,+ self.stride_test,+ self.centered_stride,+ self.box_size_m,+ )+ return coords2d, coords3d, uncertainties++ @torch.jit.export+ def reconstruct_absolute(+ self,+ coords2d: torch.Tensor,+ coords3d: torch.Tensor,+ uncertainties: torch.Tensor,+ intrinsic_matrix: torch.Tensor,+ ):+ coords3d_abs = (+ ptu3d.reconstruct_absolute(+ coords2d,+ coords3d,+ intrinsic_matrix,+ proc_side=self.proc_side,+ stride=self.stride_test,+ centered_stride=self.centered_stride,+ weak_perspective=self.weak_perspective,+ mix_3d_inside_fov=0.5,+ point_validity_mask=uncertainties < 0.3,+ border_factor1=1.0,+ border_factor2=0.6,+ mix_based_on_3d=True,+ )+ * 1000+ )+ factor = 1 if self.fix_uncert_factor else 3+ return coords3d_abs, uncertainties * factordiff --git a/models/wan/scail/nlf/person_detector.py b/models/wan/scail/nlf/person_detector.pynew file mode 100644index 0000000..d429fa4--- /dev/null+++ b/models/wan/scail/nlf/person_detector.py@@ -0,0 +1,374 @@+"""Person detector for NLF (ONNX-based YOLOX)."""+from typing import List, Optional++import torch+import torch.nn as nn+import torch.nn.functional as F+import torchvision.ops++try:+ import onnxruntime as ort+except Exception:+ ort = None+++class PersonDetectorONNX(nn.Module):+ """ONNXRuntime-based person detector using YOLOX."""++ def __init__(self, model_path: str, providers: Optional[List[str]] = None):+ if ort is None:+ raise ImportError(+ "onnxruntime is required for PersonDetectorONNX. Install with `pip install onnxruntime-gpu` "+ "or `pip install onnxruntime`."+ )+ nn.Module.__init__(self)+ self.input_size = 640+ self.person_class_id = '0'++ if providers is None:+ providers = [+ 'CUDAExecutionProvider',+ 'CPUExecutionProvider',+ ]+ self.session = ort.InferenceSession(model_path, providers=providers)+ self.input_name = self.session.get_inputs()[0].name+ self.output_name = self.session.get_outputs()[0].name+ self._input_batch_dim = self.session.get_inputs()[0].shape[0]++ strides = [8, 16, 32]+ grids = []+ stride_vals = []+ for s in strides:+ h = self.input_size // s+ w = self.input_size // s+ yy, xx = torch.meshgrid(torch.arange(h), torch.arange(w), indexing='ij')+ grid = torch.stack([xx, yy], dim=-1).reshape(-1, 2)+ grids.append(grid)+ stride_vals.append(torch.full((grid.shape[0], 1), float(s), dtype=torch.float32))+ self._grid = torch.cat(grids, dim=0)+ self._stride = torch.cat(stride_vals, dim=0)++ def forward(+ self,+ images: torch.Tensor,+ threshold: float = 0.2,+ nms_iou_threshold: float = 0.7,+ max_detections: int = 150,+ extrinsic_matrix: Optional[torch.Tensor] = None,+ world_up_vector: Optional[torch.Tensor] = None,+ flip_aug: bool = False,+ bothflip_aug: bool = False,+ extra_boxes: Optional[List[torch.Tensor]] = None,+ ):+ if max_detections == -1:+ max_detections = 150+ device = images.device+ if extrinsic_matrix is None:+ extrinsic_matrix = torch.eye(4, device=device).unsqueeze(0)+ if len(extrinsic_matrix) == 1:+ extrinsic_matrix = torch.repeat_interleave(extrinsic_matrix, len(images), dim=0)+ if world_up_vector is None:+ world_up_vector = torch.tensor([0, -1, 0], device=device, dtype=torch.float32)++ images, x_factor, y_factor, half_pad_h_float, half_pad_w_float = resize_and_pad(+ images, self.input_size+ )++ cam_up_vector = matvec(extrinsic_matrix[:, :3, :3], world_up_vector)+ angle = torch.atan2(cam_up_vector[:, 1], cam_up_vector[:, 0])+ k = (torch.round(angle / (torch.pi / 2)) + 1).to(torch.int32) % 4+ images = batched_rot90(images, k)++ if bothflip_aug:+ boxes, scores = self.call_model_bothflip_aug(images)+ elif flip_aug:+ boxes, scores = self.call_model_flip_aug(images)+ else:+ boxes, scores = self.call_model(images)++ boxes = torch.stack(+ [+ boxes[..., 0] - boxes[..., 2] / 2,+ boxes[..., 1] - boxes[..., 3] / 2,+ boxes[..., 0] + boxes[..., 2] / 2,+ boxes[..., 1] + boxes[..., 3] / 2,+ ],+ dim=-1,+ )++ if self.person_class_id == '0':+ scores = scores[..., 0].to(device)+ else:+ class_ids = torch.tensor(+ [int(x) for x in self.person_class_id.split(',')], device=device+ )+ scores = scores[:, class_ids].sum(dim=-1)++ if extra_boxes is not None:+ unscaled_extra_boxes = [+ inv_scale_boxes(+ extra_boxes_,+ half_pad_w_float,+ half_pad_h_float,+ x_factor,+ y_factor,+ k_,+ self.input_size,+ )+ for extra_boxes_, k_ in zip(extra_boxes, k)+ ]+ extra_scores = [extra_boxes_[..., 4] for extra_boxes_ in extra_boxes]+ boxes_nms, scores_nms = nms_with_extra(+ boxes,+ scores,+ unscaled_extra_boxes,+ extra_scores,+ threshold,+ nms_iou_threshold,+ max_detections,+ )+ else:+ boxes_nms, scores_nms = nms(+ boxes, scores, threshold, nms_iou_threshold, max_detections+ )++ return [+ scale_boxes(+ boxes_,+ scores_,+ half_pad_w_float,+ half_pad_h_float,+ x_factor,+ y_factor,+ k_,+ self.input_size,+ )+ for boxes_, scores_, k_ in zip(boxes_nms, scores_nms, k)+ ]++ def call_model_flip_aug(self, images):+ device = images.device+ flipped = torch.flip(images, dims=[3])+ net_input = torch.cat([images, flipped], dim=0)+ boxes, scores = self.call_model(net_input)+ padded_width = images.shape[3]+ boxes_normal, boxes_flipped = torch.chunk(boxes, 2, dim=0)+ boxes_backflipped = torch.cat(+ [padded_width - boxes_flipped[..., :1], boxes_flipped[..., 1:]], dim=-1+ ).to(device)+ boxes = torch.cat([boxes_normal, boxes_backflipped], dim=1)+ scores = torch.cat(torch.chunk(scores, 2, dim=0), dim=1)+ return boxes, scores++ def call_model_bothflip_aug(self, images):+ device = images.device+ flipped_horiz = torch.flip(images, dims=[3])+ flipped_vert = torch.flip(images, dims=[2])+ net_input = torch.cat([images, flipped_horiz, flipped_vert], dim=0)+ boxes, scores = self.call_model(net_input)+ padded_width = images.shape[3]+ padded_height = images.shape[2]+ boxes_normal, boxes_flipped_horiz, boxes_flipped_vert = torch.chunk(boxes, 3, dim=0)+ boxes_backflipped_horiz = torch.cat(+ [padded_width - boxes_flipped_horiz[..., :1], boxes_flipped_horiz[..., 1:]], dim=-1+ ).to(device)+ boxes_backflipped_vert = torch.cat(+ [+ boxes_flipped_vert[..., :1],+ padded_height - boxes_flipped_vert[..., 1:2],+ boxes_flipped_vert[..., 2:],+ ],+ dim=-1,+ ).to(device)+ boxes = torch.cat(+ [boxes_normal, boxes_backflipped_horiz, boxes_backflipped_vert], dim=1+ ).to(device)+ scores = torch.cat(torch.chunk(scores, 3, dim=0), dim=1)+ return boxes, scores++ def call_model(self, images):+ device = images.device+ images_np = (images.detach().to(device='cpu', dtype=torch.float32) * 255.0).numpy()+ if self._input_batch_dim == 1 and images_np.shape[0] != 1:+ import numpy as np+ outs = [+ self.session.run([self.output_name], {self.input_name: images_np[i : i + 1]})[0]+ for i in range(images_np.shape[0])+ ]+ out = np.concatenate(outs, axis=0)+ else:+ out = self.session.run([self.output_name], {self.input_name: images_np})[0]+ preds = torch.from_numpy(out).to(device=device)+ grid = self._grid.to(device=device, dtype=preds.dtype)+ stride = self._stride.to(device=device, dtype=preds.dtype)+ xy = (preds[..., :2] + grid) * stride+ wh = torch.exp(preds[..., 2:4]) * stride+ boxes = torch.cat([xy, wh], dim=-1)+ obj = preds[..., 4:5]+ cls = preds[..., 5:]+ scores = obj * cls+ return boxes, scores+++def nms(+ boxes: torch.Tensor,+ scores: torch.Tensor,+ threshold: float,+ nms_iou_threshold: float,+ max_detections: int,+):+ selected_boxes = []+ selected_scores = []+ for boxes_now, scores_now in zip(boxes, scores):+ is_above_threshold = scores_now > threshold+ boxes_now = boxes_now[is_above_threshold]+ scores_now = scores_now[is_above_threshold]+ nms_indices = torchvision.ops.nms(boxes_now, scores_now, nms_iou_threshold)[+ :max_detections+ ]+ selected_boxes.append(boxes_now[nms_indices])+ selected_scores.append(scores_now[nms_indices])+ return selected_boxes, selected_scores+++def nms_with_extra(+ boxes: torch.Tensor,+ scores: torch.Tensor,+ extra_boxes: List[torch.Tensor],+ extra_scores: List[torch.Tensor],+ threshold: float,+ nms_iou_threshold: float,+ max_detections: int,+):+ selected_boxes = []+ selected_scores = []+ for boxes_now_, scores_now_, extra_boxes_now, extra_scores_now in zip(+ boxes, scores, extra_boxes, extra_scores+ ):+ boxes_now = torch.cat([boxes_now_, extra_boxes_now], dim=0)+ scores_now = torch.cat([scores_now_, extra_scores_now], dim=0)+ is_above_threshold = scores_now > threshold+ boxes_now = boxes_now[is_above_threshold]+ scores_now = scores_now[is_above_threshold]+ nms_indices = torchvision.ops.nms(boxes_now, scores_now, nms_iou_threshold)[+ :max_detections+ ]+ selected_boxes.append(boxes_now[nms_indices])+ selected_scores.append(scores_now[nms_indices])+ return selected_boxes, selected_scores+++def batched_rot90(images, k):+ batch_size = images.size(0)+ rotated_images = torch.empty_like(images)+ for i in range(batch_size):+ rotated_images[i] = torch.rot90(images[i], k=k[i], dims=[1, 2])+ return rotated_images+++def matvec(a, b):+ return (a @ b.unsqueeze(-1)).squeeze(-1)+++def resize_and_pad(images: torch.Tensor, input_size: int):+ h = float(images.shape[2])+ w = float(images.shape[3])+ max_side = max(h, w)+ factor = float(input_size) / max_side+ target_w = int(factor * w)+ target_h = int(factor * h)+ y_factor = h / float(target_h)+ x_factor = w / float(target_w)+ pad_h = input_size - target_h+ pad_w = input_size - target_w+ half_pad_h = pad_h // 2+ half_pad_w = pad_w // 2+ half_pad_h_float = float(half_pad_h)+ half_pad_w_float = float(half_pad_w)++ images = F.interpolate(+ images,+ (target_h, target_w),+ mode='bilinear' if factor > 1 else 'area',+ align_corners=False if factor > 1 else None,+ )+ images **= 1 / 2.2+ images = F.pad(+ images, (half_pad_w, pad_w - half_pad_w, half_pad_h, pad_h - half_pad_h), value=0.5+ )+ return images, x_factor, y_factor, half_pad_h_float, half_pad_w_float+++def scale_boxes(+ boxes: torch.Tensor,+ scores: torch.Tensor,+ half_pad_w_float: float,+ half_pad_h_float: float,+ x_factor: float,+ y_factor: float,+ k: torch.Tensor,+ input_size: int,+):+ midpoints = (boxes[:, :2] + boxes[:, 2:]) / 2+ midpoints = (+ matvec(rotmat2d(k.to(torch.float32) * (torch.pi / 2)), midpoints - (input_size - 1) / 2)+ + (input_size - 1) / 2+ )++ sizes = boxes[:, 2:] - boxes[:, :2]+ if k % 2 == 1:+ sizes = torch.flip(sizes, [1])++ boxes_ = torch.cat([midpoints - sizes / 2, sizes], dim=1)++ return torch.stack(+ [+ (boxes_[:, 0] - half_pad_w_float) * x_factor,+ (boxes_[:, 1] - half_pad_h_float) * y_factor,+ (boxes_[:, 2]) * x_factor,+ (boxes_[:, 3]) * y_factor,+ scores,+ ],+ dim=1,+ )+++def inv_scale_boxes(+ boxes: torch.Tensor,+ half_pad_w_float: float,+ half_pad_h_float: float,+ x_factor: float,+ y_factor: float,+ k: torch.Tensor,+ input_size: int,+):+ boxes_ = torch.stack(+ [+ boxes[:, 0] / x_factor + half_pad_w_float,+ boxes[:, 1] / y_factor + half_pad_h_float,+ boxes[:, 2] / x_factor,+ boxes[:, 3] / y_factor,+ ],+ dim=1,+ )++ sizes = boxes_[:, 2:]+ midpoints = boxes_[:, :2] + sizes / 2++ if k % 2 == 1:+ sizes = torch.flip(sizes, [1])++ midpoints = (+ matvec(rotmat2d(-k.to(torch.float32) * (torch.pi / 2)), midpoints - (input_size - 1) / 2)+ + (input_size - 1) / 2+ )++ return torch.cat([midpoints - sizes / 2, midpoints + sizes / 2], dim=1)+++def rotmat2d(angle: torch.Tensor):+ sin = torch.sin(angle)+ cos = torch.cos(angle)+ entries = [cos, -sin, sin, cos]+ result = torch.stack(entries, dim=-1)+ return torch.reshape(result, angle.shape + (2, 2))diff --git a/models/wan/scail/nlf/plausibility_check.py b/models/wan/scail/nlf/plausibility_check.pynew file mode 100644index 0000000..d6ddc96--- /dev/null+++ b/models/wan/scail/nlf/plausibility_check.py@@ -0,0 +1,71 @@+"""Plausibility checks for pose filtering."""+import torch+++def pose_non_max_suppression(poses, scores, is_pose_valid):+ plausible_indices_single_frame = torch.squeeze(torch.argwhere(is_pose_valid), 1)+ plausible_poses = poses[plausible_indices_single_frame]+ plausible_scores = scores[plausible_indices_single_frame]+ similarity_matrix = compute_pose_similarity(plausible_poses)+ nms_indices = non_max_suppression_overlaps(+ overlaps=similarity_matrix, scores=plausible_scores, overlap_threshold=0.4+ )+ return plausible_indices_single_frame[nms_indices]+++def is_uncertainty_low(uncerts):+ return torch.mean((uncerts < 0.25).float(), dim=-1) > 1 / 3+++def compute_pose_similarity(poses):+ square_scales = torch.mean(torch.square(poses), dim=(-2, -1), keepdim=True)+ square_scales1 = torch.unsqueeze(square_scales, 0)+ square_scales2 = torch.unsqueeze(square_scales, 1)+ mean_square_scales = (square_scales1 + square_scales2) / 2+ scale_factor1 = torch.sqrt(mean_square_scales / square_scales1)+ scale_factor2 = torch.sqrt(mean_square_scales / square_scales2)++ poses1 = torch.unsqueeze(poses, 0)+ poses2 = torch.unsqueeze(poses, 1)++ dists = torch.linalg.norm(scale_factor1 * poses1 - scale_factor2 * poses2, dim=-1)+ best_dists = torch.topk(dists, k=poses.shape[-2] // 5, sorted=False).values+ return torch.mean(torch.relu(1 - best_dists / 300), dim=-1)+++def is_pose_consistent_with_box(pose2d, box):+ posebox_start = torch.min(pose2d, dim=-2).values+ posebox_end = torch.max(pose2d, dim=-2).values++ box_start = box[..., :2]+ box_end = box[..., :2] + box[..., 2:4]+ box_area = torch.prod(box[..., 2:4], dim=-1)++ intersection_start = torch.maximum(box_start, posebox_start)+ intersection_end = torch.minimum(box_end, posebox_end)+ intersection_area = torch.prod(torch.relu(intersection_end - intersection_start), dim=-1)+ return intersection_area > 0.25 * box_area+++def scale_align(poses):+ square_scales = torch.mean(torch.square(poses), dim=(-2, -1), keepdim=True)+ mean_square_scale = torch.mean(square_scales, dim=-3, keepdim=True)+ return poses * torch.sqrt(mean_square_scale / square_scales)+++def non_max_suppression_overlaps(+ overlaps: torch.Tensor, scores: torch.Tensor, overlap_threshold: float+):+ n_items = overlaps.shape[0]+ if n_items == 0:+ return torch.zeros(0, dtype=torch.int32, device=overlaps.device)++ order = torch.argsort(scores, dim=0, descending=True)+ keep = []+ while order.shape[0] > 0:+ i = order[0]+ keep.append(i)+ inds = torch.where(overlaps[i, order[1:]] <= overlap_threshold)[0]+ order = order[inds + 1]++ return torch.stack(keep)diff --git a/models/wan/scail/nlf/ptu.py b/models/wan/scail/nlf/ptu.pynew file mode 100644index 0000000..1c46868--- /dev/null+++ b/models/wan/scail/nlf/ptu.py@@ -0,0 +1,134 @@+"""PyTorch utilities for NLF."""+from typing import List, Optional++import torch+++def mean_stdev_masked(+ input_tensor: torch.Tensor,+ is_valid: torch.Tensor,+ items_dim: int,+ dimensions_dim: int,+ fixed_ref: Optional[torch.Tensor] = None,+):+ if fixed_ref is not None:+ mean = fixed_ref+ else:+ mean = reduce_mean_masked(input_tensor, is_valid, dim=[items_dim], keepdim=True)+ centered = input_tensor - mean++ n_new_dims = input_tensor.ndim - is_valid.ndim+ is_valid = is_valid.reshape(is_valid.shape + (1,) * n_new_dims)+ n_valid = is_valid.sum(dim=items_dim, keepdim=True, dtype=input_tensor.dtype)++ sum_of_squared_deviations = reduce_sum_masked(+ torch.square(centered), is_valid, dim=[items_dim, dimensions_dim], keepdim=True+ )++ stdev = torch.sqrt(torch.nan_to_num(sum_of_squared_deviations / n_valid) + 1e-10)+ return mean, stdev+++def reduce_mean_masked(+ input_tensor: torch.Tensor,+ is_valid: Optional[torch.Tensor],+ dim: Optional[List[int]] = None,+ keepdim: bool = False,+):+ d: List[int] = [] if dim is None else dim++ if is_valid is None:+ return torch.mean(input_tensor, dim=d, keepdim=keepdim)++ if dim is None and not keepdim:+ return torch.masked_select(input_tensor, is_valid).mean()++ n_new_dims = input_tensor.ndim - is_valid.ndim+ is_valid = is_valid.reshape(is_valid.shape + (1,) * n_new_dims)+ replaced = torch.where(is_valid, input_tensor, torch.zeros_like(input_tensor))+ sum_valid = torch.sum(replaced, dim=d, keepdim=keepdim)+ n_valid = torch.sum(is_valid, dim=d, keepdim=keepdim, dtype=input_tensor.dtype)+ return torch.nan_to_num(sum_valid / n_valid)+++def reduce_sum_masked(+ input_tensor: torch.Tensor,+ is_valid: torch.Tensor,+ dim: Optional[List[int]] = None,+ keepdim: bool = False,+):+ if dim is None and not keepdim:+ return torch.masked_select(input_tensor, is_valid).sum()++ n_new_dims = input_tensor.ndim - is_valid.ndim+ is_valid = is_valid.reshape(is_valid.shape + (1,) * n_new_dims)+ replaced = torch.where(is_valid, input_tensor, torch.zeros_like(input_tensor))+ d: List[int] = [] if dim is None else dim+ return torch.sum(replaced, dim=d, keepdim=keepdim)+++def softmax(target: torch.Tensor, dim: List[int] = (-1,)):+ dim = [d if d >= 0 else d + target.ndim for d in dim]+ assert sorted(dim) == list(range(min(dim), max(dim) + 1))+ dim_min = min(dim)+ dim_max = max(dim)+ target_flattened = target.flatten(start_dim=dim_min, end_dim=dim_max)+ softmaxed_flattened = torch.softmax(target_flattened, dim=dim_min)+ return softmaxed_flattened.reshape(target.shape)+++def soft_argmax(inp: torch.Tensor, dim: List[int] = (-1,)):+ return decode_heatmap(softmax(inp, dim=dim), dim=dim)+++def decode_heatmap(inp: torch.Tensor, dim: List[int] = (-1,), output_coord_dim: int = -1):+ result = []+ dim = [d if d >= 0 else d + inp.ndim for d in dim]+ for d in dim:+ other_heatmap_dims = list(dim)+ other_heatmap_dims.remove(d)+ summed_over_other_heatmap_axes = torch.sum(inp, dim=other_heatmap_dims, keepdim=True)+ coords = linspace(+ 0.0, 1.0, inp.shape[d], dtype=inp.dtype, device=summed_over_other_heatmap_axes.device+ )+ decoded = torch.tensordot(summed_over_other_heatmap_axes, coords, dims=([d], [0]))+ x = torch.unsqueeze(decoded, d)+ for hd in sorted(dim)[::-1]:+ x = x.squeeze(hd)+ result.append(x)+ return torch.stack(result, dim=output_coord_dim)+++def linspace(+ start: float,+ stop: float,+ num: int,+ dtype: Optional[torch.dtype] = None,+ device: Optional[torch.device] = None,+ endpoint: bool = True,+):+ start = torch.as_tensor(start, device=device, dtype=dtype)+ stop = torch.as_tensor(stop, device=device, dtype=dtype)++ if endpoint:+ if num == 1:+ return torch.mean(torch.stack([start, stop], dim=0), dim=0, keepdim=True)+ else:+ return torch.linspace(start, stop, num, device=device, dtype=dtype)+ else:+ if num > 1:+ step = (stop - start) / num+ return torch.linspace(start, stop - step, num, device=device, dtype=dtype)+ else:+ return torch.linspace(start, stop, num, device=device, dtype=dtype)+++def dynamic_partition(x: torch.Tensor, partitions: torch.Tensor, num_partitions: int):+ return [x[partitions == i] for i in torch.arange(num_partitions, device=partitions.device)]+++def dynamic_stitch(index_lists: List[torch.Tensor], value_lists: List[torch.Tensor]):+ indices = torch.cat(index_lists, dim=0)+ values = torch.cat(value_lists, dim=0)+ inv_permutation = torch.argsort(indices)+ return values[inv_permutation]diff --git a/models/wan/scail/nlf/ptu3d.py b/models/wan/scail/nlf/ptu3d.pynew file mode 100644index 0000000..8a6c7c4--- /dev/null+++ b/models/wan/scail/nlf/ptu3d.py@@ -0,0 +1,231 @@+"""PyTorch 3D utilities for NLF."""+from typing import List, Optional++import numpy as np+import torch++from . import ptu+++def reconstruct_absolute(+ coords2d: torch.Tensor,+ coords3d_rel: torch.Tensor,+ intrinsics: torch.Tensor,+ proc_side: int,+ stride: int,+ centered_stride: bool,+ mix_3d_inside_fov: Optional[float] = None,+ weak_perspective: bool = None,+ point_validity_mask: Optional[torch.Tensor] = None,+ border_factor1: float = 0.75,+ border_factor2: Optional[float] = None,+ mix_based_on_3d: bool = True,+):+ inv_intrinsics = torch.linalg.inv(intrinsics.to(coords2d.dtype))+ coords2d_normalized = (to_homogeneous(coords2d) @ inv_intrinsics.transpose(1, 2))[..., :2]++ if border_factor2 is None:+ border_factor2 = border_factor1++ is_predicted_to_be_in_fov1 = is_within_fov(+ coords2d, proc_side, stride, centered_stride, border_factor1+ )++ if point_validity_mask is not None:+ is_predicted_to_be_in_fov1 = torch.logical_and(+ is_predicted_to_be_in_fov1, point_validity_mask+ )++ if weak_perspective:+ ref = reconstruct_ref_weakpersp(+ coords2d_normalized, coords3d_rel, is_predicted_to_be_in_fov1+ )+ else:+ ref = reconstruct_ref_fullpersp(+ coords2d_normalized, coords3d_rel, is_predicted_to_be_in_fov1+ )+ coords_abs_3d_based = coords3d_rel + ref.unsqueeze(1)+ reference_depth = ref[:, 2]+ relative_depths = coords3d_rel[..., 2]+ coords_abs_2d_based = back_project(coords2d_normalized, relative_depths, reference_depth)++ if mix_3d_inside_fov is not None:+ coords_abs_2d_based = (+ mix_3d_inside_fov * coords_abs_3d_based + (1 - mix_3d_inside_fov) * coords_abs_2d_based+ )++ if mix_based_on_3d:+ coords_proj_for_mix_decision = project_pose(coords_abs_3d_based, intrinsics)+ else:+ coords_proj_for_mix_decision = project_pose(coords_abs_2d_based, intrinsics)++ is_predicted_to_be_in_fov2 = torch.logical_and(+ is_within_fov(+ coords_proj_for_mix_decision, proc_side, stride, centered_stride, border_factor2+ ),+ coords_abs_3d_based[..., 2] > 0.001,+ )++ return torch.where(+ is_predicted_to_be_in_fov2[..., np.newaxis], coords_abs_2d_based, coords_abs_3d_based+ )+++def reconstruct_ref_weakpersp(normalized_2d, coords3d_rel, validity_mask):+ mean3d, stdev3d = ptu.mean_stdev_masked(+ coords3d_rel[..., :2], validity_mask, items_dim=1, dimensions_dim=2+ )++ mean2d, stdev2d = ptu.mean_stdev_masked(+ normalized_2d[..., :2], validity_mask, items_dim=1, dimensions_dim=2+ )++ stdev2d = torch.maximum(stdev2d, torch.tensor(1e-5))+ stdev3d = torch.maximum(stdev3d, torch.tensor(1e-5))++ old_mean = ptu.reduce_mean_masked(coords3d_rel, validity_mask, dim=[1], keepdim=True)+ new_mean_z = torch.nan_to_num(stdev3d / stdev2d)+ new_mean = to_homogeneous(mean2d) * new_mean_z+ return torch.squeeze(new_mean - old_mean, 1)+++def to_homogeneous(x):+ return torch.cat([x, torch.ones_like(x[..., :1])], dim=-1)+++def reconstruct_ref_fullpersp(normalized_2d, coords3d_rel, validity_mask):+ n_batch = normalized_2d.shape[0]+ n_points = normalized_2d.shape[1]++ eyes2 = (+ torch.eye(2, device=normalized_2d.device, dtype=normalized_2d.dtype)+ .unsqueeze(0)+ .repeat(n_batch, n_points, 1)+ )+ scale2d, reshaped2d = rms_normalize_and_reshape(normalized_2d, validity_mask, n_points)+ A = torch.cat([eyes2, -reshaped2d], dim=2)++ rel_backproj = normalized_2d * coords3d_rel[:, :, 2:] - coords3d_rel[:, :, :2]+ scale_rel_backproj, b = rms_normalize_and_reshape(rel_backproj, validity_mask, n_points)++ weights = validity_mask.to(normalized_2d.dtype) + 1e-8+ weights = torch.repeat_interleave(weights, 2, 1)+ ref = lstsq_cholesky(A, b, weights, l2_regularizer=1e-4)++ ref = torch.cat(+ [ref[:, :2] * scale_rel_backproj, ref[:, 2:] * (scale_rel_backproj / scale2d)], dim=1+ )+ return torch.squeeze(ref, dim=-1)+++def rms_normalize_and_reshape(x: torch.Tensor, validity_mask: torch.Tensor, n_points: int):+ scale = torch.sqrt(+ ptu.reduce_mean_masked(torch.square(x), validity_mask, dim=[1, 2], keepdim=True)+ + 1e-10+ )+ normalized = x / scale+ reshaped = normalized.reshape(-1, n_points * 2, 1)+ return scale, reshaped+++def lstsq_cholesky(+ matrix: torch.Tensor,+ rhs: torch.Tensor,+ weights: torch.Tensor,+ l2_regularizer: Optional[float] = None,+) -> torch.Tensor:+ weighted_matrix = weights.unsqueeze(-1) * matrix+ regularized_gramian = weighted_matrix.mT @ matrix+ if l2_regularizer is not None:+ regularized_gramian.diagonal(dim1=-2, dim2=-1).add_(l2_regularizer)++ ATb = weighted_matrix.mT @ rhs+ chol, _ = torch.linalg.cholesky_ex(regularized_gramian)+ return torch.cholesky_solve(ATb, chol)+++def back_project(camcoords2d, delta_z, z_offset):+ return to_homogeneous(camcoords2d) * torch.unsqueeze(+ delta_z + torch.unsqueeze(z_offset, -1), -1+ )+++def is_within_fov(+ imcoords: torch.Tensor,+ proc_side: int,+ stride: int,+ centered_stride: bool,+ border_factor: float = 0.75,+):+ offset = -stride / 2.0 if not centered_stride else 0.0+ lower = stride * border_factor + offset+ upper = proc_side - stride * border_factor + offset+ proj_in_fov = torch.all(torch.logical_and(imcoords >= lower, imcoords <= upper), dim=-1)+ return proj_in_fov+++def project_pose(coords3d, intrinsic_matrix):+ projected = coords3d / torch.maximum(+ torch.tensor(0.1, device=coords3d.device), coords3d[..., 2:]+ )+ return torch.einsum('bnk,bjk->bnj', projected, intrinsic_matrix[..., :2, :])+++def lookat_matrix(forward_vector, up_vector):+ new_z = forward_vector / torch.linalg.norm(forward_vector, dim=-1, keepdim=True)+ new_x = torch.linalg.cross(new_z, up_vector)+ new_x_alt = torch.stack([new_z[:, 2], torch.zeros_like(new_z[:, 2]), -new_z[:, 0]], dim=1)+ new_x = torch.where(torch.linalg.norm(new_x, dim=-1, keepdim=True) == 0, new_x_alt, new_x)+ new_x = new_x / torch.linalg.norm(new_x, dim=-1, keepdim=True)+ new_y = torch.linalg.cross(new_z, new_x)+ return torch.stack([new_x, new_y, new_z], dim=1)+++def project(points):+ return points[..., :2] / points[..., 2:3]+++def intrinsic_matrix_from_field_of_view(+ fov_degrees: float, imshape: List[int], device: Optional[torch.device] = None+):+ imshape = torch.tensor(imshape, dtype=torch.float32, device=device)+ fov_radians = fov_degrees * torch.tensor(torch.pi / 180, dtype=torch.float32, device=device)+ larger_side = torch.max(imshape)+ focal_length = larger_side / (torch.tan(fov_radians / 2) * 2)+ _0 = torch.tensor(0, dtype=torch.float32, device=device)+ _1 = torch.tensor(1, dtype=torch.float32, device=device)++ return (+ torch.stack(+ [+ focal_length,+ _0,+ (imshape[1] - 1) / 2,+ _0,+ focal_length,+ (imshape[0] - 1) / 2,+ _0,+ _0,+ _1,+ ],+ dim=-1,+ )+ .unflatten(-1, (3, 3))+ .unsqueeze(0)+ )+++def rotation_mat(angle: torch.Tensor, rot_axis: str):+ sin = torch.sin(angle)+ cos = torch.cos(angle)+ _0 = torch.zeros_like(angle)+ _1 = torch.ones_like(angle)++ if rot_axis == 'x':+ elems = [_1, _0, _0, _0, cos, sin, _0, -sin, cos]+ elif rot_axis == 'y':+ elems = [cos, _0, -sin, _0, _1, _0, sin, _0, cos]+ else:+ elems = [cos, -sin, _0, sin, cos, _0, _0, _0, _1]++ return torch.stack(elems, dim=-1).unflatten(-1, (3, 3))diff --git a/models/wan/scail/nlf/util.py b/models/wan/scail/nlf/util.pynew file mode 100644index 0000000..6adb109--- /dev/null+++ b/models/wan/scail/nlf/util.py@@ -0,0 +1,21 @@+"""Model utilities for NLF."""+import torch+++def heatmap_to_image(coords: torch.Tensor, proc_side: int, stride: int, centered_stride: bool):+ last_image_pixel = proc_side - 1+ last_receptive_center = last_image_pixel - (last_image_pixel % stride)+ coords_out = coords * last_receptive_center++ if centered_stride:+ coords_out = coords_out + stride // 2++ return coords_out+++def heatmap_to_metric(+ coords: torch.Tensor, proc_side: int, stride: int, centered_stride: bool, box_size_m: float+):+ xy = coords[..., :2]+ coords2d = heatmap_to_image(xy, proc_side, stride, centered_stride) * box_size_m / proc_side+ return torch.cat([coords2d, coords[..., 2:] * box_size_m], dim=-1)diff --git a/models/wan/scail/nlf/warping.py b/models/wan/scail/nlf/warping.pynew file mode 100644index 0000000..3722af5--- /dev/null+++ b/models/wan/scail/nlf/warping.py@@ -0,0 +1,197 @@+"""Image warping utilities for NLF."""+from typing import List, Tuple, Optional++import torch+import torch.nn.functional as F++from . import ptu3d+++def warp_images_with_pyramid(+ images: torch.Tensor,+ intrinsic_matrix: torch.Tensor,+ new_invprojmats: torch.Tensor,+ distortion_coeffs: torch.Tensor,+ crop_scales: torch.Tensor,+ output_shape: Tuple[int, int],+ image_ids: torch.Tensor,+ n_pyramid_levels: int = 3,+):+ image_levels = [images]+ for _ in range(1, n_pyramid_levels):+ image_levels.append(F.avg_pool2d(image_levels[-1], 2, 2))++ intrinsic_matrix_levels = [+ corner_aligned_scale_mat(1 / 2**i_level, device=intrinsic_matrix.device) @ intrinsic_matrix+ for i_level in range(n_pyramid_levels)+ ]++ i_pyramid_levels = torch.floor(-torch.log2(crop_scales))+ i_pyramid_levels = torch.clip(i_pyramid_levels, 0, n_pyramid_levels - 1).int()++ return torch.stack(+ [+ warp_single_image(+ image_levels[i_pyramid_levels[i]][image_ids[i]],+ intrinsic_matrix_levels[i_pyramid_levels[i]][i],+ new_invprojmats[i],+ distortion_coeffs[i],+ output_shape,+ )+ for i in range(len(image_ids))+ ]+ )+++def warp_single_image(+ image: torch.Tensor,+ intrinsic_matrix: torch.Tensor,+ new_invprojmat: torch.Tensor,+ distortion_coeffs: torch.Tensor,+ output_shape: Tuple[int, int],+):+ device = image.device+ new_coords = torch.stack(+ torch.meshgrid(+ torch.arange(output_shape[1], device=device),+ torch.arange(output_shape[0], device=device),+ indexing='xy',+ ),+ dim=-1,+ ).float()+ new_coords_homog = ptu3d.to_homogeneous(new_coords)+ old_coords_homog = torch.einsum('hwc,Cc->hwC', new_coords_homog, new_invprojmat)+ old_coords_homog = ptu3d.to_homogeneous(+ distort_points(ptu3d.project(old_coords_homog), distortion_coeffs)+ )+ old_coords = torch.einsum('hwc,Cc->hwC', old_coords_homog, intrinsic_matrix)[..., :2]+ size = torch.tensor([image.shape[2], image.shape[1]], dtype=old_coords.dtype, device=device)+ old_coords_normalized = old_coords.mul_(2.0 / (size - 1)).sub_(1.0)+ return F.grid_sample(+ image.unsqueeze(0),+ old_coords_normalized.unsqueeze(0).to(image.dtype),+ align_corners=True,+ mode='bilinear',+ padding_mode='zeros',+ ).squeeze(0)+++def distort_points(undist_points2d: torch.Tensor, distortion_coeffs: torch.Tensor):+ if torch.all(distortion_coeffs == 0):+ return undist_points2d+ elif distortion_coeffs.shape[-1] == 4:+ return distort_points_fisheye(undist_points2d, distortion_coeffs)+ else:+ a, b, c = distortion_formula_parts(undist_points2d, distortion_coeffs)+ return undist_points2d * (a + b) + c+++def undistort_points(dist_points2d: torch.Tensor, distortion_coeffs: torch.Tensor):+ if torch.all(distortion_coeffs == 0):+ return dist_points2d+ elif distortion_coeffs.shape[-1] == 4:+ return undistort_points_fisheye(dist_points2d, distortion_coeffs)+ else:+ undist_points2d = dist_points2d+ for _ in range(5):+ a, b, c = distortion_formula_parts(undist_points2d, distortion_coeffs)+ undist_points2d = (dist_points2d - c - undist_points2d * b) / a+ return undist_points2d+++def distortion_formula_parts(undist_points2d: torch.Tensor, distortion_coeffs: torch.Tensor):+ d = pad_axis_to_size(distortion_coeffs, 12, -1)+ broadcast_shape = (+ ([-1] if d.ndim > 1 else [])+ + [1] * (undist_points2d.ndim - d.ndim)+ + [12]+ )+ d = torch.reshape(d, broadcast_shape)++ r2 = torch.sum(torch.square(undist_points2d), dim=-1, keepdim=True)+ a = (((d[..., 4:5] * r2 + d[..., 1:2]) * r2 + d[..., 0:1]) * r2 + 1) / (+ ((d[..., 7:8] * r2 + d[..., 6:7]) * r2 + d[..., 5:6]) * r2 + 1+ )++ p2_1 = torch.flip(d[..., 2:4], dims=[-1])+ b = 2 * torch.sum(undist_points2d * p2_1, dim=-1, keepdim=True)+ c = (d[..., 9:12:2] * r2 + p2_1 + d[..., 8:11:2]) * r2++ return a, b, c+++def pad_axis_to_size(x: torch.Tensor, size: int, dim: int):+ paddings = [[0, 0]] * x.ndim+ paddings[dim] = [0, size - x.shape[dim]]++ ps: List[int] = []+ for p_ in paddings[::-1]:+ ps.extend(p_)++ return F.pad(x, ps)+++def distort_points_fisheye(+ undist_points2d: torch.Tensor, distortion_coeffs: torch.Tensor+) -> torch.Tensor:+ d = distortion_coeffs+ broadcast_shape = (+ ([-1] if d.ndim > 1 else [])+ + [1] * (undist_points2d.ndim - d.ndim)+ + [4]+ )+ d = torch.reshape(d, broadcast_shape)++ if torch.all(distortion_coeffs == 0):+ return undist_points2d+ else:+ r = torch.linalg.vector_norm(undist_points2d, dim=-1, keepdim=True)+ t = torch.atan(r)+ t2 = torch.square(t)+ t_d = (+ (((d[..., 3:4] * t2 + d[..., 2:3]) * t2 + d[..., 1:2]) * t2 + d[..., 0:1]) * t2 + 1+ ) * t+ return undist_points2d * torch.nan_to_num(t_d / r)+++def undistort_points_fisheye(+ dist_points2d: torch.Tensor, distortion_coeffs: torch.Tensor+) -> torch.Tensor:+ d = distortion_coeffs+ broadcast_shape = (+ ([-1] if d.ndim > 1 else [])+ + [1] * (dist_points2d.ndim - d.ndim)+ + [4]+ )+ d = torch.reshape(d, broadcast_shape)++ if torch.all(distortion_coeffs == 0):+ return dist_points2d++ t_d = torch.linalg.vector_norm(dist_points2d, dim=-1, keepdim=True)+ t = t_d+ for _ in range(5):+ t2 = torch.square(t)+ t4 = torch.square(t2)+ t6 = t2 * t4+ t8 = torch.square(t4)+ k0_t2 = d[..., 0:1] * t2+ k1_t4 = d[..., 1:2] * t4+ k2_t6 = d[..., 2:3] * t6+ k3_t8 = d[..., 3:4] * t8+ t = t - (+ (t * (1 + k0_t2 + k1_t4 + k2_t6 + k3_t8) - t_d)+ / (1 + 3 * k0_t2 + 5 * k1_t4 + 7 * k2_t6 + 9 * k3_t8)+ )++ undist_points2d = dist_points2d * torch.nan_to_num(torch.tan(t) / t_d)+ return undist_points2d+++def corner_aligned_scale_mat(factor: float, device: Optional[torch.device] = None) -> torch.Tensor:+ shift = (factor - 1.0) / 2.0+ return torch.tensor(+ [[factor, 0.0, shift], [0.0, factor, shift], [0.0, 0.0, 1.0]],+ dtype=torch.float32,+ device=device,+ )diff --git a/models/wan/scail/nlfpose_extractor.py b/models/wan/scail/nlfpose_extractor.pynew file mode 100644index 0000000..318d90d--- /dev/null+++ b/models/wan/scail/nlfpose_extractor.py@@ -0,0 +1,553 @@+"""+SCAIL NLFPose Extractor - 3D pose extraction using NLFPose.+Reuses WanGP's existing DWPose/YOLOX for detection, adds NLFPose for 3D lifting.+"""++import os+import math+import numpy as np+import torch+import cv2+from PIL import Image+from typing import List, Optional, Tuple, Union, Dict, Any++from shared.utils import files_locator as fl+from preprocessing.dwpose.wholebody import HWC3, Wholebody, resize_image+++ArrayImage = Union[np.ndarray, Image.Image, torch.Tensor]+++def _to_rgb_array(image: ArrayImage) -> np.ndarray:+ """Convert various image formats to RGB uint8 numpy array."""+ if isinstance(image, torch.Tensor):+ img = image.detach().cpu()+ if img.dim() == 4:+ img = img[0] # Take first batch+ if img.shape[0] in (1, 3, 4):+ img = img.permute(1, 2, 0)+ if img.min() < 0:+ img = (img + 1.0) * 127.5+ elif img.max() <= 1.0:+ img = img * 255.0+ arr = img.clamp(0, 255).byte().numpy()+ if arr.shape[2] == 1:+ arr = cv2.cvtColor(arr, cv2.COLOR_GRAY2RGB)+ elif arr.shape[2] == 4:+ arr = cv2.cvtColor(arr, cv2.COLOR_RGBA2RGB)+ return arr+ elif isinstance(image, Image.Image):+ return np.array(image.convert("RGB"))+ elif isinstance(image, np.ndarray):+ if image.ndim == 2:+ return cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)+ elif image.shape[2] == 4:+ return cv2.cvtColor(image, cv2.COLOR_RGBA2RGB)+ elif image.shape[2] == 3:+ return image if image.dtype == np.uint8 else (image * 255).astype(np.uint8)+ return image+ raise ValueError(f"Unsupported image type: {type(image)}")+++class NLFPoseExtractor:+ """+ NLFPose 3D keypoint extraction wrapper.++ Uses YOLOX for person detection, DWPose for 2D keypoint estimation (hands/face),+ and NLFPose (isarandi/nlf) for true 3D lifting from images.+ """++ # Expected NLFPose model filename+ # NLFPOSE_MODEL = "nlf_l_multi_0.3.2.torchscript"+ NLFPOSE_MODEL = "nlf_l_multi_0.3.2_torch2.7.1.torchscript"++ def __init__(+ self,+ device: str = None,+ detect_resolution: int = 1024,+ ):+ """+ Initialize the extractor.++ Args:+ device: Device to run models on (default: auto-detect)+ detect_resolution: Resolution for pose detection+ """+ self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")+ self.detect_resolution = detect_resolution++ # Locate model files+ self.det_model_path = fl.locate_file("pose/yolox_l.onnx")+ self.pose_model_path = fl.locate_file("pose/dw-ll_ucoco_384.onnx")++ # Try to locate NLFPose model+ self.nlfpose_model_path = self._locate_nlfpose_model()+ if self.nlfpose_model_path is None:+ print(+ f"[SCAIL] Warning: NLFPose model '{self.NLFPOSE_MODEL}' not found; using 2D pose + heuristic depth. "+ "Place it under `ckpts/pose/` or `ckpts/scail/` to enable true 3D lifting."+ )++ # Lazy load models+ self._wholebody = None+ self._nlfpose = None++ def _locate_nlfpose_model(self) -> Optional[str]:+ """Try to locate NLFPose model file."""+ # Try common locations+ try:+ path = fl.locate_file(f"pose/{self.NLFPOSE_MODEL}")+ if path and os.path.exists(path):+ return path+ except:+ pass++ try:+ path = fl.locate_file(f"scail/{self.NLFPOSE_MODEL}")+ if path and os.path.exists(path):+ return path+ except:+ pass++ # Try direct paths+ for path in [+ os.path.join("ckpts", self.NLFPOSE_MODEL),+ os.path.join("models", "pose", self.NLFPOSE_MODEL),+ ]:+ if os.path.exists(path):+ return path++ return None++ @property+ def wholebody(self) -> Wholebody:+ """Lazy load DWPose/YOLOX detector."""+ if self._wholebody is None:+ self._wholebody = Wholebody(+ self.det_model_path,+ self.pose_model_path,+ device=self.device+ )+ return self._wholebody++ @property+ def nlfpose(self):+ """Lazy load NLFPose model."""+ if self._nlfpose is None and self.nlfpose_model_path:+ try:+ self._nlfpose = torch.jit.load(self.nlfpose_model_path)+ self._nlfpose.to(self.device)+ self._nlfpose.eval()+ except Exception as e:+ print(f"[SCAIL] Warning: Could not load NLFPose model: {e}")+ print("[SCAIL] Falling back to 2D pose with estimated depth")+ self._nlfpose = None+ return self._nlfpose++ def extract_2d_keypoints(+ self,+ image: ArrayImage,+ mask: Optional[np.ndarray] = None+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, Optional[np.ndarray]]:+ """+ Extract 2D keypoints from an image using DWPose.++ Args:+ image: Input image+ mask: Optional mask to filter detected persons++ Returns:+ Tuple of (body_keypoints, hand_keypoints, face_keypoints, bbox)+ Each with shape (num_persons, num_joints, 2/3) for body, hands, face+ """+ rgb = _to_rgb_array(image)+ bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)+ bgr = HWC3(bgr)+ resized = resize_image(bgr, self.detect_resolution)+ H, W = resized.shape[:2]++ # Run DWPose detection+ candidate, subset, det_result = self.wholebody(resized)++ if len(candidate) == 0:+ return np.array([]), np.array([]), np.array([]), None++ # Normalize coordinates to [0, 1]+ candidate = candidate.copy()+ subset = subset.copy() if hasattr(subset, "copy") else subset+ candidate[..., 0] /= float(W)+ candidate[..., 1] /= float(H)+ bbox = None+ if det_result is not None and len(det_result) > 0:+ det_result = np.asarray(det_result).copy()+ det_result[:, [0, 2]] /= float(W)+ det_result[:, [1, 3]] /= float(H)++ # Filter by mask if provided+ if mask is not None:+ mask_resized = cv2.resize(mask, (W, H))+ candidate, subset, det_result = self._filter_by_mask(candidate, subset, det_result, mask_resized)++ # Extract first person's keypoints+ if len(candidate) == 0:+ return np.array([]), np.array([]), np.array([]), None++ # Pick the most confident person.+ # subset contains per-keypoint confidence scores (n, K).+ body_scores_all = subset[:, :18] if subset is not None and len(subset) > 0 else None+ if body_scores_all is None:+ max_ind = 0+ else:+ max_ind = int(np.nanargmax(np.nanmean(body_scores_all, axis=1)))++ # Body keypoints (18 OpenPose/COCO keypoints) with scores+ body_xy = candidate[max_ind, :18].copy()+ body_scores = (+ subset[max_ind, :18].copy()+ if subset is not None and len(subset) > 0+ else np.ones(18, dtype=np.float32)+ )+ body = np.concatenate([body_xy, body_scores[:, None]], axis=-1).astype(np.float32)+ low_conf_body = body_scores <= 0.3+ body[low_conf_body] = -1.0++ # Hands (21 keypoints each, right then left)+ hands = np.zeros((2, 21, 3), dtype=np.float32)+ if candidate.shape[1] >= 134:+ rh_xy = candidate[max_ind, 92:113].copy()+ lh_xy = candidate[max_ind, 113:134].copy()+ rh_scores = (+ subset[max_ind, 92:113].copy()+ if subset is not None and len(subset) > 0+ else np.ones(21, dtype=np.float32)+ )+ lh_scores = (+ subset[max_ind, 113:134].copy()+ if subset is not None and len(subset) > 0+ else np.ones(21, dtype=np.float32)+ )+ hands[0] = np.concatenate([rh_xy, rh_scores[:, None]], axis=-1)+ hands[1] = np.concatenate([lh_xy, lh_scores[:, None]], axis=-1)+ hands[hands[:, :, 2] <= 0.3] = -1.0++ # Face (68 keypoints)+ faces = np.zeros((1, 68, 3), dtype=np.float32)+ if candidate.shape[1] >= 92:+ face_xy = candidate[max_ind, 24:92].copy()+ face_scores = (+ subset[max_ind, 24:92].copy()+ if subset is not None and len(subset) > 0+ else np.ones(68, dtype=np.float32)+ )+ faces[0] = np.concatenate([face_xy, face_scores[:, None]], axis=-1)+ faces[0][faces[0, :, 2] <= 0.3] = -1.0++ if det_result is not None and len(det_result) > 0 and max_ind < len(det_result):+ bbox = det_result[max_ind].astype(np.float32)+ else:+ bbox = self._bbox_from_body(body)++ return body, hands, faces, bbox++ def _filter_by_mask(+ self,+ candidate: np.ndarray,+ subset: np.ndarray,+ det_result: Optional[np.ndarray],+ mask: np.ndarray+ ) -> Tuple[np.ndarray, np.ndarray, Optional[np.ndarray]]:+ """Filter detected persons by mask overlap (returns candidate, scores, and bboxes)."""+ H, W = mask.shape[:2]+ filtered_idx = []++ for i in range(len(candidate)):+ # Check if person's keypoints fall within mask+ body = candidate[i, :18]+ valid_pts = body[body[:, 0] >= 0]+ if len(valid_pts) == 0:+ continue++ # Convert normalized coords to pixel coords+ px = (valid_pts[:, 0] * W).astype(int).clip(0, W - 1)+ py = (valid_pts[:, 1] * H).astype(int).clip(0, H - 1)++ # Check mask overlap+ mask_vals = mask[py, px]+ overlap = np.mean(mask_vals > 0.5)++ if overlap > 0.3: # At least 30% overlap+ filtered_idx.append(i)++ if not filtered_idx:+ return np.array([]), np.array([]), None++ filtered_candidate = candidate[filtered_idx]+ filtered_subset = subset[filtered_idx] if subset is not None and len(subset) > 0 else subset+ filtered_det = det_result[filtered_idx] if det_result is not None and len(det_result) > 0 else det_result+ return filtered_candidate, filtered_subset, filtered_det++ def _bbox_from_body(self, body: np.ndarray) -> Optional[np.ndarray]:+ """Approximate person bbox from body keypoints (normalized xy)."""+ if body is None or not isinstance(body, np.ndarray) or body.size == 0:+ return None+ valid = (body[:, 0] >= 0) & (body[:, 1] >= 0)+ if not valid.any():+ return None+ xs = body[valid, 0]+ ys = body[valid, 1]+ x1, y1 = float(xs.min()), float(ys.min())+ x2, y2 = float(xs.max()), float(ys.max())+ # Expand slightly.+ w = max(x2 - x1, 1e-3)+ h = max(y2 - y1, 1e-3)+ x1 -= 0.05 * w+ x2 += 0.05 * w+ y1 -= 0.08 * h+ y2 += 0.08 * h+ return np.array([x1, y1, x2, y2], dtype=np.float32)++ def _estimate_3d_from_2d(self, keypoints_2d: np.ndarray) -> np.ndarray:+ """+ Fallback "3D" from 2D keypoints (no NLFPose available).+ Returns normalized x/y plus heuristic depth in [0.5, 1.0].+ """+ if keypoints_2d is None or not isinstance(keypoints_2d, np.ndarray) or keypoints_2d.size == 0:+ return np.full((18, 3), -1.0, dtype=np.float32)++ result = np.zeros((len(keypoints_2d), 3), dtype=np.float32)+ result[:, :2] = keypoints_2d[:, :2].astype(np.float32)++ # Estimate depth based on vertical position and body structure+ # Higher Y (lower in image) typically means closer to camera+ valid_mask = keypoints_2d[:, 0] >= 0++ if valid_mask.any():+ y_coords = keypoints_2d[valid_mask, 1]+ y_min, y_max = y_coords.min(), y_coords.max()+ y_range = max(y_max - y_min, 0.1)++ # Normalize depth to [0, 1] range+ for i in range(len(keypoints_2d)):+ if valid_mask[i]:+ # Invert so lower Y (higher in image) = larger depth+ normalized_y = (keypoints_2d[i, 1] - y_min) / y_range+ result[i, 2] = 1.0 - normalized_y * 0.5 # Depth range 0.5-1.0++ # Mark invalid keypoints+ result[~valid_mask, :] = -1++ return result++ def _run_nlfpose_batched(+ self,+ frames_rgb: List[np.ndarray],+ bboxes_norm: List[Optional[np.ndarray]],+ batch_size: int = 32,+ ) -> List[Optional[np.ndarray]]:+ """+ Run NLFPose torchscript on a list of frames using one bbox per frame.++ Returns:+ List[Optional[np.ndarray]]: per-frame SMPL-24 joints in camera space (24, 3) or None.+ """+ model = self.nlfpose+ if model is None:+ return [None] * len(frames_rgb)++ device = torch.device(self.device)+ out: List[Optional[np.ndarray]] = [None] * len(frames_rgb)++ def _call_model(img_batch: torch.Tensor) -> Any:+ # SCAIL-Pose uses `detect_smpl_batched` on this weight. Keep fallback for other wrappers.+ if hasattr(model, "detect_smpl_batched"):+ return model.detect_smpl_batched(img_batch)+ return model(img_batch)++ def _extract_joints(pred: Any, expected: int) -> List[Optional[torch.Tensor]]:+ if isinstance(pred, dict):+ val = None+ for k in ("joints3d_nonparam", "joints3d"):+ if k in pred:+ val = pred[k]+ break+ if val is None:+ return [None] * expected+ else:+ val = pred++ if isinstance(val, torch.Tensor):+ # (B, 24, 3) or (B, 1, 24, 3)+ if val.ndim == 4 and val.shape[1] == 1:+ val = val[:, 0]+ if val.ndim == 3:+ return [val[i] for i in range(min(expected, val.shape[0]))] + [None] * max(0, expected - val.shape[0])+ return [None] * expected++ if isinstance(val, (list, tuple)):+ items: List[Optional[torch.Tensor]] = []+ for i in range(expected):+ if i >= len(val):+ items.append(None)+ continue+ item = val[i]+ if isinstance(item, torch.Tensor):+ items.append(item)+ elif isinstance(item, (list, tuple)) and len(item) > 0 and isinstance(item[0], torch.Tensor):+ items.append(item[0])+ else:+ items.append(None)+ return items++ return [None] * expected++ with torch.inference_mode():+ for start in range(0, len(frames_rgb), batch_size):+ end = min(start + batch_size, len(frames_rgb))+ chunk_frames = frames_rgb[start:end]+ chunk_boxes = bboxes_norm[start:end]+ if not chunk_frames:+ continue++ H, W = chunk_frames[0].shape[:2]+ buf = torch.zeros((len(chunk_frames), H, W, 3), dtype=torch.uint8, device=device)++ for bi, (frame_np, bbox) in enumerate(zip(chunk_frames, chunk_boxes)):+ if bbox is None or not np.isfinite(bbox).all():+ continue+ frame_t = torch.from_numpy(frame_np).to(device=device, dtype=torch.uint8)+ x1, y1, x2, y2 = [float(v) for v in bbox.tolist()]+ # Expand bbox (matches SCAIL-Pose defaults).+ x1_px = max(0, math.floor(x1 * W - W * 0.025))+ y1_px = max(0, math.floor(y1 * H - H * 0.05))+ x2_px = min(W, math.ceil(x2 * W + W * 0.025))+ y2_px = min(H, math.ceil(y2 * H + H * 0.05))+ if x2_px <= x1_px or y2_px <= y1_px:+ continue+ buf[bi, y1_px:y2_px, x1_px:x2_px, :] = frame_t[y1_px:y2_px, x1_px:x2_px, :]++ img_batch = buf.permute(0, 3, 1, 2) # (B, 3, H, W)+ pred = _call_model(img_batch)+ joints_items = _extract_joints(pred, expected=len(chunk_frames))++ for bi, joints_t in enumerate(joints_items):+ if joints_t is None:+ continue+ jt = joints_t+ if jt.ndim == 3 and jt.shape[0] == 1:+ jt = jt[0]+ if jt.ndim != 2 or jt.shape[-1] != 3:+ continue+ out[start + bi] = jt.detach().float().cpu().numpy().astype(np.float32)++ return out++ def _smpl24_to_openpose18(self, joints24: np.ndarray) -> np.ndarray:+ """+ Map NLFPose SMPL-24 joints to OpenPose/COCO 18-joint order used by SCAIL-Pose rendering.++ Note: this mapping mirrors the one from zai-org/SCAIL-Pose (NLFPoseExtract/nlf_draw.py).+ """+ out = np.full((18, 3), -1.0, dtype=np.float32)+ if joints24 is None or not isinstance(joints24, np.ndarray) or joints24.shape[0] < 22:+ return out+ mapping = {+ 15: 0, # head+ 12: 1, # neck+ 17: 2, # (left shoulder -> openpose R_SHOULDER in upstream mapping)+ 19: 3, # left elbow+ 21: 4, # left hand+ 16: 5, # right shoulder+ 18: 6, # right elbow+ 20: 7, # right hand+ 2: 8, # left pelvis+ 5: 9, # left knee+ 8: 10, # left feet+ 1: 11, # right pelvis+ 4: 12, # right knee+ 7: 13, # right feet+ }+ for src, dst in mapping.items():+ pt = joints24[src]+ if not np.isfinite(pt).all():+ continue+ out[dst] = pt.astype(np.float32)+ # Invalidate non-positive depth (camera Z).+ invalid = out[:, 2] <= 0.0+ out[invalid] = -1.0+ return out++ def extract_3d_keypoints(+ self,+ frames: List[ArrayImage],+ masks: Optional[List[np.ndarray]] = None,+ return_details: bool = False,+ ):+ """+ Extract 3D keypoints from a sequence of frames.++ Args:+ frames: List of input frames+ masks: Optional list of masks for each frame++ Returns:+ List of 3D keypoints arrays, each shape (num_joints, 3)+ """+ # Collect DWPose details first (hands/face + bbox).+ frames_rgb: List[np.ndarray] = []+ details_2d: List[Dict[str, Any]] = []+ bboxes: List[Optional[np.ndarray]] = []++ for i, frame in enumerate(frames):+ mask = masks[i] if masks is not None and i < len(masks) else None+ rgb = _to_rgb_array(frame)+ frames_rgb.append(rgb)+ body_2d, hands_2d, faces_2d, bbox = self.extract_2d_keypoints(rgb, mask)+ details_2d.append({"body_2d": body_2d, "hands_2d": hands_2d, "face_2d": faces_2d})+ bboxes.append(bbox)++ # Run NLFPose (image-based) if available; otherwise fall back to heuristic depth.+ nlf_joints24 = self._run_nlfpose_batched(frames_rgb, bboxes) if self.nlfpose is not None else [None] * len(frames_rgb)++ results: List[Any] = []+ for d2d, joints24 in zip(details_2d, nlf_joints24):+ body_2d = d2d["body_2d"]+ hands_2d = d2d["hands_2d"]+ faces_2d = d2d["face_2d"]++ if joints24 is not None:+ body_3d = self._smpl24_to_openpose18(joints24)+ body_space = "camera"+ elif isinstance(body_2d, np.ndarray) and body_2d.size > 0:+ body_3d = self._estimate_3d_from_2d(body_2d)+ body_space = "normalized"+ else:+ body_3d = np.full((18, 3), -1.0, dtype=np.float32)+ body_space = "normalized"++ if return_details:+ results.append(+ {+ "body_3d": body_3d,+ "body_space": body_space,+ "hands_2d": hands_2d,+ "face_2d": faces_2d,+ }+ )+ else:+ results.append(body_3d)++ return results++ def extract_single(self, image: ArrayImage, mask: Optional[np.ndarray] = None) -> np.ndarray:+ """+ Extract 3D keypoints from a single image.++ Args:+ image: Input image+ mask: Optional mask++ Returns:+ 3D keypoints, shape (num_joints, 3)+ """+ result = self.extract_3d_keypoints([image], [mask] if mask is not None else None)+ return result[0] if result else np.full((18, 3), -1.0)diff --git a/models/wan/scail/pose_aligner.py b/models/wan/scail/pose_aligner.pynew file mode 100644index 0000000..809afcd--- /dev/null+++ b/models/wan/scail/pose_aligner.py@@ -0,0 +1,245 @@+"""+SCAIL Pose Aligner - Align 3D pose to reference image proportions.+Adapted from steadydancer/pose_align.py for 3D keypoints.+"""++import numpy as np+from typing import Dict, List, Tuple, Optional+++def _safe_ratio(num: float, den: float) -> float:+ """Safe division with fallback to 1.0."""+ if den == 0 or not np.isfinite(den):+ return 1.0+ val = num / den+ return float(val) if np.isfinite(val) else 1.0+++def _nan_to_one(val: float) -> float:+ """Replace NaN with 1.0."""+ return 1.0 if not np.isfinite(val) else float(val)+++def _dist_3d(keypoints: np.ndarray, a: int, b: int) -> float:+ """Compute 3D distance between two keypoints."""+ pa, pb = keypoints[a, :3], keypoints[b, :3]+ # Validity: camera-Z must be positive; X/Y can be negative in camera space.+ if not np.all(np.isfinite(pa)) or not np.all(np.isfinite(pb)):+ return np.nan+ if pa[2] <= 0 or pb[2] <= 0:+ return np.nan+ return float(np.linalg.norm(pa - pb))+++class ScailPoseAligner:+ """+ Align extracted 3D pose keypoints to reference image body proportions.++ This adapts the steadydancer alignment approach for 3D keypoints,+ computing scale factors for different body parts and applying them+ to match the reference image's body proportions.+ """++ # Body keypoint indices (COCO format)+ NOSE = 0+ NECK = 1+ R_SHOULDER = 2+ R_ELBOW = 3+ R_WRIST = 4+ L_SHOULDER = 5+ L_ELBOW = 6+ L_WRIST = 7+ R_HIP = 8+ R_KNEE = 9+ R_ANKLE = 10+ L_HIP = 11+ L_KNEE = 12+ L_ANKLE = 13+ R_EYE = 14+ L_EYE = 15+ R_EAR = 16+ L_EAR = 17++ def __init__(self):+ pass++ def compute_alignment_params(+ self,+ ref_keypoints: np.ndarray,+ driving_keypoints: np.ndarray+ ) -> Dict[str, float]:+ """+ Compute alignment parameters from reference and first driving frame.++ Args:+ ref_keypoints: Reference image 3D keypoints, shape (num_joints, 3)+ driving_keypoints: First frame driving video 3D keypoints, shape (num_joints, 3)++ Returns:+ Dictionary of scale factors for different body parts+ """+ body_ref = ref_keypoints.copy()+ body_drv = driving_keypoints.copy()++ # Compute scale factors for different body parts+ align_params = {+ "scale_neck": _safe_ratio(+ _dist_3d(body_ref, self.NOSE, self.NECK),+ _dist_3d(body_drv, self.NOSE, self.NECK)+ ),+ "scale_face_left": _safe_ratio(+ _dist_3d(body_ref, self.L_EAR, self.L_EYE) + _dist_3d(body_ref, self.L_EYE, self.NOSE),+ _dist_3d(body_drv, self.L_EAR, self.L_EYE) + _dist_3d(body_drv, self.L_EYE, self.NOSE)+ ),+ "scale_face_right": _safe_ratio(+ _dist_3d(body_ref, self.R_EAR, self.R_EYE) + _dist_3d(body_ref, self.R_EYE, self.NOSE),+ _dist_3d(body_drv, self.R_EAR, self.R_EYE) + _dist_3d(body_drv, self.R_EYE, self.NOSE)+ ),+ "scale_shoulder": _safe_ratio(+ _dist_3d(body_ref, self.R_SHOULDER, self.L_SHOULDER),+ _dist_3d(body_drv, self.R_SHOULDER, self.L_SHOULDER)+ ),+ "scale_arm_upper": np.nanmean([+ _safe_ratio(_dist_3d(body_ref, self.R_SHOULDER, self.R_ELBOW),+ _dist_3d(body_drv, self.R_SHOULDER, self.R_ELBOW)),+ _safe_ratio(_dist_3d(body_ref, self.L_SHOULDER, self.L_ELBOW),+ _dist_3d(body_drv, self.L_SHOULDER, self.L_ELBOW))+ ]),+ "scale_arm_lower": np.nanmean([+ _safe_ratio(_dist_3d(body_ref, self.R_ELBOW, self.R_WRIST),+ _dist_3d(body_drv, self.R_ELBOW, self.R_WRIST)),+ _safe_ratio(_dist_3d(body_ref, self.L_ELBOW, self.L_WRIST),+ _dist_3d(body_drv, self.L_ELBOW, self.L_WRIST))+ ]),+ "scale_body_len": _safe_ratio(+ _dist_3d(body_ref, self.NECK, self.R_HIP) if not np.isnan(_dist_3d(body_ref, self.NECK, self.R_HIP))+ else _dist_3d(body_ref, self.NECK, self.L_HIP),+ _dist_3d(body_drv, self.NECK, self.R_HIP) if not np.isnan(_dist_3d(body_drv, self.NECK, self.R_HIP))+ else _dist_3d(body_drv, self.NECK, self.L_HIP)+ ),+ "scale_leg_upper": np.nanmean([+ _safe_ratio(_dist_3d(body_ref, self.R_HIP, self.R_KNEE),+ _dist_3d(body_drv, self.R_HIP, self.R_KNEE)),+ _safe_ratio(_dist_3d(body_ref, self.L_HIP, self.L_KNEE),+ _dist_3d(body_drv, self.L_HIP, self.L_KNEE))+ ]),+ "scale_leg_lower": np.nanmean([+ _safe_ratio(_dist_3d(body_ref, self.R_KNEE, self.R_ANKLE),+ _dist_3d(body_drv, self.R_KNEE, self.R_ANKLE)),+ _safe_ratio(_dist_3d(body_ref, self.L_KNEE, self.L_ANKLE),+ _dist_3d(body_drv, self.L_KNEE, self.L_ANKLE))+ ]),+ }++ # Replace NaN values with mean of other scales+ finite_vals = [v for v in align_params.values() if np.isfinite(v)]+ mean_scale = np.mean(finite_vals) if finite_vals else 1.0+ align_params = {k: mean_scale if not np.isfinite(v) else v for k, v in align_params.items()}++ # Compute spatial offset (translate to match reference position)+ if body_ref[self.NECK, 2] > 0 and body_drv[self.NECK, 2] > 0:+ offset = body_ref[self.NECK, :3] - body_drv[self.NECK, :3]+ else:+ offset = np.zeros(3)+ align_params["offset"] = offset++ return align_params++ def apply_alignment(+ self,+ keypoints: np.ndarray,+ align_params: Dict[str, float],+ center_idx: int = 1 # NECK+ ) -> np.ndarray:+ """+ Apply alignment parameters to transform keypoints.++ Args:+ keypoints: 3D keypoints to transform, shape (num_joints, 3)+ align_params: Dictionary of scale factors from compute_alignment_params+ center_idx: Index of center keypoint for scaling (default: NECK)++ Returns:+ Transformed keypoints, shape (num_joints, 3)+ """+ result = keypoints.copy()+ center = result[center_idx, :3].copy()+ if not np.all(np.isfinite(center)) or center[2] <= 0:+ # No reliable center; apply only translation to valid keypoints.+ offset = align_params.get("offset", np.zeros(3))+ valid_mask = np.isfinite(result[:, 2]) & (result[:, 2] > 0)+ result[valid_mask, :3] += offset+ return result++ # Scale different body parts from their respective parent joints+ # Head/face region+ self._scale_from_center(result, [self.NOSE], center, align_params["scale_neck"])+ self._scale_from_center(result, [self.L_EYE, self.L_EAR], result[self.NOSE, :3], align_params["scale_face_left"])+ self._scale_from_center(result, [self.R_EYE, self.R_EAR], result[self.NOSE, :3], align_params["scale_face_right"])++ # Shoulders+ self._scale_from_center(result, [self.R_SHOULDER, self.L_SHOULDER], center, align_params["scale_shoulder"])++ # Arms+ self._scale_from_center(result, [self.R_ELBOW], result[self.R_SHOULDER, :3], align_params["scale_arm_upper"])+ self._scale_from_center(result, [self.R_WRIST], result[self.R_ELBOW, :3], align_params["scale_arm_lower"])+ self._scale_from_center(result, [self.L_ELBOW], result[self.L_SHOULDER, :3], align_params["scale_arm_upper"])+ self._scale_from_center(result, [self.L_WRIST], result[self.L_ELBOW, :3], align_params["scale_arm_lower"])++ # Torso/hips+ self._scale_from_center(result, [self.R_HIP, self.L_HIP], center, align_params["scale_body_len"])++ # Legs+ self._scale_from_center(result, [self.R_KNEE], result[self.R_HIP, :3], align_params["scale_leg_upper"])+ self._scale_from_center(result, [self.R_ANKLE], result[self.R_KNEE, :3], align_params["scale_leg_lower"])+ self._scale_from_center(result, [self.L_KNEE], result[self.L_HIP, :3], align_params["scale_leg_upper"])+ self._scale_from_center(result, [self.L_ANKLE], result[self.L_KNEE, :3], align_params["scale_leg_lower"])++ # Apply offset+ offset = align_params.get("offset", np.zeros(3))+ valid_mask = np.isfinite(result[:, 2]) & (result[:, 2] > 0)+ result[valid_mask, :3] += offset++ return result++ def _scale_from_center(+ self,+ keypoints: np.ndarray,+ indices: List[int],+ center: np.ndarray,+ scale: float+ ):+ """Scale keypoints relative to a center point."""+ for idx in indices:+ if np.isfinite(keypoints[idx, 2]) and keypoints[idx, 2] > 0: # Valid keypoint (camera-Z)+ diff = keypoints[idx, :3] - center+ keypoints[idx, :3] = center + diff * scale++ def align_sequence(+ self,+ ref_keypoints: np.ndarray,+ driving_keypoints_seq: List[np.ndarray]+ ) -> List[np.ndarray]:+ """+ Align a sequence of driving keypoints to match reference proportions.++ Args:+ ref_keypoints: Reference image 3D keypoints, shape (num_joints, 3)+ driving_keypoints_seq: List of driving video keypoints, each shape (num_joints, 3)++ Returns:+ List of aligned keypoints+ """+ if not driving_keypoints_seq:+ return []++ # Compute alignment from first frame+ align_params = self.compute_alignment_params(ref_keypoints, driving_keypoints_seq[0])++ # Apply to all frames+ aligned_seq = []+ for kp in driving_keypoints_seq:+ aligned_kp = self.apply_alignment(kp, align_params)+ aligned_seq.append(aligned_kp)++ return aligned_seqdiff --git a/models/wan/scail/scail_pose_align3d.py b/models/wan/scail/scail_pose_align3d.pynew file mode 100644index 0000000..dc4c71e--- /dev/null+++ b/models/wan/scail/scail_pose_align3d.py@@ -0,0 +1,97 @@+"""+Official SCAIL-Pose 3D retarget camera intrinsics solver.++Upstream: https://github.com/zai-org/SCAIL-Pose (NLFPoseExtract/align3d.py)+Note: the upstream file imports `sympy` but doesn't use it; this adaptation omits that import.+"""++from __future__ import annotations++import numpy as np+++def solve_new_camera_params_central(three_d_points, focal_length, imshape, new_2d_points):+ from scipy.optimize import minimize++ def objective(params):+ m, s, p, q = params+ K_new = np.array(+ [+ [focal_length * m, 0, imshape[1] / 2 + p],+ [0, focal_length * m * s, imshape[0] / 2 + q],+ [0, 0, 1],+ ]+ )++ new_projections = []+ for point in three_d_points:+ X, Y, Z = point+ u = (K_new[0, 0] * X / Z) + K_new[0, 2]+ v = (K_new[1, 1] * Y / Z) + K_new[1, 2]+ new_projections.append([u, v])+ new_projections = np.array(new_projections)++ error0 = np.sum((new_2d_points[:1] - new_projections[:1]) ** 2)+ error = np.sum((new_2d_points[1:] - new_projections[1:]) ** 2)+ return error0 * 8 + error++ initial_params = [1.0, 1.0, 0.0, 0.0]+ result = minimize(+ objective,+ initial_params,+ bounds=[(0.7, 1.4), (0.8, 1.15), (-imshape[1], imshape[1]), (-imshape[0], imshape[0])],+ )++ m, s, p, q = result.x+ K_final = np.array(+ [+ [focal_length * m, 0, imshape[1] / 2 + p],+ [0, focal_length * m * s, imshape[0] / 2 + q],+ [0, 0, 1],+ ]+ )+ return K_final, m+++def solve_new_camera_params_down(three_d_points, focal_length, imshape, new_2d_points):+ from scipy.optimize import minimize++ def objective(params):+ m, s, p, q = params+ K_new = np.array(+ [+ [focal_length * m, 0, imshape[1] / 2 + p],+ [0, focal_length * m * s, imshape[0] / 2 + q],+ [0, 0, 1],+ ]+ )++ new_projections = []+ for point in three_d_points:+ X, Y, Z = point+ u = (K_new[0, 0] * X / Z) + K_new[0, 2]+ v = (K_new[1, 1] * Y / Z) + K_new[1, 2]+ new_projections.append([u, v])+ new_projections = np.array(new_projections)++ error0 = np.sum((new_2d_points[:1] - new_projections[:1]) ** 2)+ error = np.sum((new_2d_points[1:] - new_projections[1:]) ** 2)+ return error0 + error * 4++ initial_params = [1.0, 1.0, 0.0, 0.0]+ result = minimize(+ objective,+ initial_params,+ bounds=[(0.7, 1.4), (0.8, 1.15), (-imshape[1], imshape[1]), (-imshape[0], imshape[0])],+ )++ m, s, p, q = result.x+ K_final = np.array(+ [+ [focal_length * m, 0, imshape[1] / 2 + p],+ [0, focal_length * m * s, imshape[0] / 2 + q],+ [0, 0, 1],+ ]+ )+ return K_final, m+diff --git a/models/wan/scail/scail_pose_draw.py b/models/wan/scail/scail_pose_draw.pynew file mode 100644index 0000000..35c3e52--- /dev/null+++ b/models/wan/scail/scail_pose_draw.py@@ -0,0 +1,308 @@+"""+2D pose overlay drawing utilities from the official SCAIL-Pose repo.++Upstream:+- https://github.com/zai-org/SCAIL-Pose (pose_draw/draw_utils.py)+- https://github.com/zai-org/SCAIL-Pose (pose_draw/draw_pose_utils.py)++Only the functions required by `render_nlf_as_images` are included.+"""++from __future__ import annotations++import math+import random++import cv2+import matplotlib+import numpy as np++eps = 0.01+++def draw_bodypose_augmentation(canvas, candidate, subset, drop_aug=True, shift_aug=False, all_cheek_aug=False):+ H, W, C = canvas.shape+ candidate = np.array(candidate)+ subset = np.array(subset)++ stickwidth = 4++ limbSeq = [+ [2, 3],+ [2, 6],+ [3, 4],+ [4, 5],+ [6, 7],+ [7, 8],+ [2, 9],+ [9, 10],+ [10, 11],+ [2, 12],+ [12, 13],+ [13, 14],+ [2, 1],+ [1, 15],+ [15, 17],+ [1, 16],+ [16, 18],+ [3, 17],+ [6, 18],+ ]++ colors = [+ [255, 0, 0],+ [255, 85, 0],+ [255, 170, 0],+ [255, 255, 0],+ [170, 255, 0],+ [85, 255, 0],+ [0, 255, 0],+ [0, 255, 85],+ [0, 255, 170],+ [0, 255, 255],+ [0, 170, 255],+ [0, 85, 255],+ [0, 0, 255],+ [85, 0, 255],+ [170, 0, 255],+ [255, 0, 255],+ [255, 0, 170],+ [255, 0, 85],+ ]++ if drop_aug:+ arr_drop = list(range(17))+ k_drop = random.choices([0, 1, 2], weights=[0.5, 0.3, 0.2])[0]+ drop_indices = random.sample(arr_drop, k_drop)+ else:+ drop_indices = []+ if shift_aug:+ shift_indices = random.sample(list(range(17)), 2)+ else:+ shift_indices = []+ if all_cheek_aug:+ drop_indices = list(range(13))++ for i in range(17):+ for n in range(len(subset)):+ index = subset[n][np.array(limbSeq[i]) - 1]+ if -1 in index:+ continue+ Y = candidate[index.astype(int), 0] * float(W)+ X = candidate[index.astype(int), 1] * float(H)++ if i in drop_indices:+ continue++ mX = np.mean(X)+ mY = np.mean(Y)+ length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5+ if i in shift_indices:+ mX = mX + random.uniform(-length / 4, length / 4)+ mY = mY + random.uniform(-length / 4, length / 4)+ angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))+ polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1)+ cv2.fillConvexPoly(canvas, polygon, colors[i])++ canvas = (canvas * 0.6).astype(np.uint8)++ for i in range(18):+ if all_cheek_aug:+ if i not in [0, 14, 15, 16, 17]:+ continue+ for n in range(len(subset)):+ index = int(subset[n][i])+ if index == -1:+ continue+ x, y = candidate[index][0:2]+ x = int(x * W)+ y = int(y * H)+ cv2.circle(canvas, (int(x), int(y)), 4, colors[i], thickness=-1)++ return canvas+++def draw_handpose(canvas, all_hand_peaks):+ H, W, C = canvas.shape+ stickwidth_thin = min(max(int(min(H, W) / 300), 1), 2)++ edges = [+ [0, 1],+ [1, 2],+ [2, 3],+ [3, 4],+ [0, 5],+ [5, 6],+ [6, 7],+ [7, 8],+ [0, 9],+ [9, 10],+ [10, 11],+ [11, 12],+ [0, 13],+ [13, 14],+ [14, 15],+ [15, 16],+ [0, 17],+ [17, 18],+ [18, 19],+ [19, 20],+ ]++ for peaks in all_hand_peaks:+ peaks = np.array(peaks)++ for ie, e in enumerate(edges):+ x1, y1 = peaks[e[0]]+ x2, y2 = peaks[e[1]]+ x1 = int(x1 * W)+ y1 = int(y1 * H)+ x2 = int(x2 * W)+ y2 = int(y2 * H)+ if x1 > eps and y1 > eps and x2 > eps and y2 > eps:+ cv2.line(+ canvas,+ (x1, y1),+ (x2, y2),+ matplotlib.colors.hsv_to_rgb([ie / float(len(edges)), 1.0, 1.0]) * 255,+ thickness=stickwidth_thin,+ )++ for i, keyponit in enumerate(peaks):+ x, y = keyponit+ x = int(x * W)+ y = int(y * H)+ if x > eps and y > eps:+ cv2.circle(canvas, (x, y), stickwidth_thin, (0, 0, 255), thickness=-1)+ return canvas+++def draw_facepose(canvas, all_lmks, optimized_face=True):+ H, W, C = canvas.shape+ stickwidth = min(max(int(min(H, W) / 200), 1), 3)+ stickwidth_thin = min(max(int(min(H, W) / 300), 1), 2)++ for lmks in all_lmks:+ lmks = np.array(lmks)+ for lmk_idx, lmk in enumerate(lmks):+ x, y = lmk+ x = int(x * W)+ y = int(y * H)+ if x > eps and y > eps:+ if optimized_face:+ if lmk_idx in list(range(17, 27)) + list(range(36, 70)):+ cv2.circle(canvas, (x, y), stickwidth_thin, (255, 255, 255), thickness=-1)+ else:+ cv2.circle(canvas, (x, y), stickwidth, (255, 255, 255), thickness=-1)+ return canvas+++def draw_pose(+ pose,+ H,+ W,+ show_feet=False,+ show_body=True,+ show_hand=True,+ show_face=True,+ show_cheek=False,+ dw_bgr=False,+ dw_hand=False,+ aug_body_draw=False,+ optimized_face=False,+):+ final_canvas = np.zeros(shape=(H, W, 3), dtype=np.uint8)+ for i in range(len(pose["bodies"]["candidate"])):+ canvas = np.zeros(shape=(H, W, 3), dtype=np.uint8)+ bodies = pose["bodies"]+ faces = pose["faces"][i : i + 1]+ hands = pose["hands"][2 * i : 2 * i + 2]+ candidate = bodies["candidate"][i]+ subset = bodies["subset"][i : i + 1]++ if show_cheek:+ if show_body:+ raise AssertionError("show_cheek and show_body cannot be True at the same time")+ canvas = draw_bodypose_augmentation(+ canvas, candidate, subset, drop_aug=True, shift_aug=False, all_cheek_aug=True+ )++ if show_hand:+ canvas = draw_handpose(canvas, hands)++ if show_face:+ canvas = draw_facepose(canvas, faces, optimized_face=optimized_face)++ final_canvas = final_canvas + canvas+ return final_canvas+++def scale_image_hw_keep_size(img, scale_h, scale_w):+ H, W = img.shape[:2]+ new_H, new_W = int(H * scale_h), int(W * scale_w)+ scaled = cv2.resize(img, (new_W, new_H), interpolation=cv2.INTER_LINEAR)++ result = np.zeros_like(img)++ if new_H >= H:+ y_start_src = (new_H - H) // 2+ y_end_src = y_start_src + H+ y_start_dst = 0+ y_end_dst = H+ else:+ y_start_src = 0+ y_end_src = new_H+ y_start_dst = (H - new_H) // 2+ y_end_dst = y_start_dst + new_H++ if new_W >= W:+ x_start_src = (new_W - W) // 2+ x_end_src = x_start_src + W+ x_start_dst = 0+ x_end_dst = W+ else:+ x_start_src = 0+ x_end_src = new_W+ x_start_dst = (W - new_W) // 2+ x_end_dst = x_start_dst + new_W++ result[y_start_dst:y_end_dst, x_start_dst:x_end_dst] = scaled[y_start_src:y_end_src, x_start_src:x_end_src]+ return result+++def draw_pose_to_canvas_np(+ poses,+ pool,+ H,+ W,+ reshape_scale,+ show_feet_flag=False,+ show_body_flag=True,+ show_hand_flag=True,+ show_face_flag=True,+ show_cheek_flag=False,+ dw_bgr=False,+ dw_hand=False,+ aug_body_draw=False,+):+ canvas_np_lst = []+ for pose in poses:+ if reshape_scale > 0 and pool is not None:+ pool.apply_random_reshapes(pose)+ canvas = draw_pose(+ pose,+ H,+ W,+ show_feet_flag,+ show_body_flag,+ show_hand_flag,+ show_face_flag,+ show_cheek_flag,+ dw_bgr,+ dw_hand,+ aug_body_draw,+ optimized_face=True,+ )+ canvas_np_lst.append(canvas)+ return canvas_np_lst+diff --git a/models/wan/scail/scail_pose_dwpose.py b/models/wan/scail/scail_pose_dwpose.pynew file mode 100644index 0000000..2774385--- /dev/null+++ b/models/wan/scail/scail_pose_dwpose.py@@ -0,0 +1,107 @@+"""+DWpose (YOLOX + RTMPose ONNX) wrapper from the official SCAIL-Pose repo.++Upstream: https://github.com/zai-org/SCAIL-Pose (DWPoseProcess/dwpose/__init__.py)++Minimal adaptations for WanGP:+- Weights are resolved from `ckpts/pose` via `shared.utils.files_locator`.+- Removes the `controlnet_aux` dependency by inlining `HWC3`.+- GPU-only ONNXRuntime providers (no CPU fallback).+"""++from __future__ import annotations++import os++os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"++import cv2+import numpy as np+import torch+from PIL import Image++from .scail_pose_dwpose_wholebody import Wholebody+++def HWC3(x: np.ndarray) -> np.ndarray:+ """Ensure image is HxWx3 uint8 (ControlNet-style utility)."""+ if x.ndim != 3:+ raise ValueError(f"HWC3 expects 3D array, got shape {x.shape}")+ h, w, c = x.shape+ if c == 3:+ return x+ if c == 1:+ return np.concatenate([x, x, x], axis=2)+ if c == 4:+ color = x[:, :, 0:3].astype(np.float32)+ alpha = x[:, :, 3:4].astype(np.float32) / 255.0+ y = color * alpha + 255.0 * (1.0 - alpha)+ return np.clip(y, 0, 255).astype(np.uint8)+ raise ValueError(f"HWC3 unsupported channel count: {c}")+++class DWposeDetector:+ def __init__(self, use_batch: bool = False):+ self.use_batch = use_batch++ def to(self, device: int):+ self.pose_estimation = Wholebody(device, self.use_batch)+ return self++ def _get_multi_result_from_est(self, candidate, score_result, det_result, H, W):+ nums, keys, locs = candidate.shape+ candidate[..., 0] /= float(W)+ candidate[..., 1] /= float(H)+ subset_score = score_result[:, :24]+ face_score = score_result[:, 24:92]+ hand_score = score_result[:, 92:113]+ hand_score = np.vstack([hand_score, score_result[:, 113:]])++ body_candidate = candidate[:, :24].copy()+ for i in range(len(subset_score)):+ for j in range(len(subset_score[i])):+ if subset_score[i][j] > 0.3:+ subset_score[i][j] = j+ else:+ subset_score[i][j] = -1++ un_visible = score_result < 0.3+ candidate[un_visible] = -1++ faces = candidate[:, 24:92]+ hands = candidate[:, 92:113]+ hands = np.vstack([hands, candidate[:, 113:]])++ bodies = dict(candidate=body_candidate, subset=subset_score)+ pose = dict(bodies=bodies, hands=hands, faces=faces)+ score = dict(body_score=subset_score, hand_score=hand_score, face_score=face_score)++ new_det_result = []+ for bbox in det_result:+ x1, y1, x2, y2 = bbox+ new_x1 = x1 / W+ new_y1 = y1 / H+ new_x2 = x2 / W+ new_y2 = y2 / H+ new_bbox = [new_x1, new_y1, new_x2, new_y2]+ new_det_result.append(new_bbox)++ return pose, score, new_det_result++ def __call__(self, input, **kwargs):+ if self.use_batch:+ raise NotImplementedError("DWposeDetector does not support batch mode")++ if isinstance(input, Image.Image):+ rgb = np.array(input, dtype=np.uint8)+ else:+ rgb = np.array(input, dtype=np.uint8)++ bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)+ bgr = HWC3(bgr)+ H, W, C = bgr.shape++ with torch.no_grad():+ candidate, subset, det_result = self.pose_estimation(bgr)+ return self._get_multi_result_from_est(candidate, subset, det_result, H, W)+diff --git a/models/wan/scail/scail_pose_dwpose_onnxdet.py b/models/wan/scail/scail_pose_dwpose_onnxdet.pynew file mode 100644index 0000000..2255e07--- /dev/null+++ b/models/wan/scail/scail_pose_dwpose_onnxdet.py@@ -0,0 +1,134 @@+# https://github.com/IDEA-Research/DWPose+import cv2+import numpy as np+import onnxruntime+++def nms(boxes, scores, nms_thr):+ """Single class NMS implemented in Numpy."""+ x1 = boxes[:, 0]+ y1 = boxes[:, 1]+ x2 = boxes[:, 2]+ y2 = boxes[:, 3]++ areas = (x2 - x1 + 1) * (y2 - y1 + 1)+ order = scores.argsort()[::-1]++ keep = []+ while order.size > 0:+ i = order[0]+ keep.append(i)+ xx1 = np.maximum(x1[i], x1[order[1:]])+ yy1 = np.maximum(y1[i], y1[order[1:]])+ xx2 = np.minimum(x2[i], x2[order[1:]])+ yy2 = np.minimum(y2[i], y2[order[1:]])++ w = np.maximum(0.0, xx2 - xx1 + 1)+ h = np.maximum(0.0, yy2 - yy1 + 1)+ inter = w * h+ ovr = inter / (areas[i] + areas[order[1:]] - inter)++ inds = np.where(ovr <= nms_thr)[0]+ order = order[inds + 1]++ return keep+++def multiclass_nms(boxes, scores, nms_thr, score_thr):+ """Multiclass NMS implemented in Numpy. Class-aware version."""+ final_dets = []+ num_classes = scores.shape[1]+ for cls_ind in range(num_classes):+ cls_scores = scores[:, cls_ind]+ valid_score_mask = cls_scores > score_thr+ if valid_score_mask.sum() == 0:+ continue+ else:+ valid_scores = cls_scores[valid_score_mask]+ valid_boxes = boxes[valid_score_mask]+ keep = nms(valid_boxes, valid_scores, nms_thr)+ if len(keep) > 0:+ cls_inds = np.ones((len(keep), 1)) * cls_ind+ dets = np.concatenate(+ [valid_boxes[keep], valid_scores[keep, None], cls_inds], 1+ )+ final_dets.append(dets)+ if len(final_dets) == 0:+ return None+ return np.concatenate(final_dets, 0)+++def demo_postprocess(outputs, img_size, p6=False):+ grids = []+ expanded_strides = []+ strides = [8, 16, 32] if not p6 else [8, 16, 32, 64]++ hsizes = [img_size[0] // stride for stride in strides]+ wsizes = [img_size[1] // stride for stride in strides]++ for hsize, wsize, stride in zip(hsizes, wsizes, strides):+ xv, yv = np.meshgrid(np.arange(wsize), np.arange(hsize))+ grid = np.stack((xv, yv), 2).reshape(1, -1, 2)+ grids.append(grid)+ shape = grid.shape[:2]+ expanded_strides.append(np.full((*shape, 1), stride))++ grids = np.concatenate(grids, 1)+ expanded_strides = np.concatenate(expanded_strides, 1)+ outputs[..., :2] = (outputs[..., :2] + grids) * expanded_strides+ outputs[..., 2:4] = np.exp(outputs[..., 2:4]) * expanded_strides++ return outputs+++def preprocess(img, input_size, swap=(2, 0, 1)):+ if len(img.shape) == 3:+ padded_img = np.ones((input_size[0], input_size[1], 3), dtype=np.uint8) * 114+ else:+ padded_img = np.ones(input_size, dtype=np.uint8) * 114++ r = min(input_size[0] / img.shape[0], input_size[1] / img.shape[1])+ resized_img = cv2.resize(+ img,+ (int(img.shape[1] * r), int(img.shape[0] * r)),+ interpolation=cv2.INTER_LINEAR,+ ).astype(np.uint8)+ padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img++ padded_img = padded_img.transpose(swap)+ padded_img = np.ascontiguousarray(padded_img, dtype=np.float32)+ return padded_img, r+++def inference_detector(session, oriImg):+ input_shape = (640, 640)+ img, ratio = preprocess(oriImg, input_shape)++ ort_inputs = {session.get_inputs()[0].name: img[None, :, :, :]}+ output = session.run(None, ort_inputs)+ predictions = demo_postprocess(output[0], input_shape)[0]++ boxes = predictions[:, :4]+ scores = predictions[:, 4:5] * predictions[:, 5:]++ boxes_xyxy = np.ones_like(boxes)+ boxes_xyxy[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.0+ boxes_xyxy[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.0+ boxes_xyxy[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.0+ boxes_xyxy[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.0+ boxes_xyxy /= ratio+ dets = multiclass_nms(boxes_xyxy, scores, nms_thr=0.45, score_thr=0.1)+ if dets is not None:+ final_boxes, final_scores, final_cls_inds = dets[:, :4], dets[:, 4], dets[:, 5]+ isscore = final_scores > 0.3+ iscat = final_cls_inds == 0+ isbbox = [i and j for (i, j) in zip(isscore, iscat)]+ final_boxes = final_boxes[isbbox]+ else:+ # print("no boxes detected")+ return []++ return final_boxes+++diff --git a/models/wan/scail/scail_pose_dwpose_onnxpose.py b/models/wan/scail/scail_pose_dwpose_onnxpose.pynew file mode 100644index 0000000..a8f1815--- /dev/null+++ b/models/wan/scail/scail_pose_dwpose_onnxpose.py@@ -0,0 +1,487 @@+# https://github.com/IDEA-Research/DWPose+from typing import List, Tuple++import cv2+import numpy as np+import onnxruntime as ort+++def preprocess(+ img: np.ndarray, out_bbox, input_size: Tuple[int, int] = (192, 256)+) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:+ """Do preprocessing for RTMPose model inference.++ Args:+ img (np.ndarray): Input image in shape.+ input_size (tuple): Input image size in shape (w, h).++ Returns:+ tuple:+ - resized_img (np.ndarray): Preprocessed image.+ - center (np.ndarray): Center of image.+ - scale (np.ndarray): Scale of image.+ """+ # get shape of image+ img_shape = img.shape[:2]+ out_img, out_center, out_scale = [], [], []+ if len(out_bbox) == 0:+ out_bbox = [[0, 0, img_shape[1], img_shape[0]]]+ for i in range(len(out_bbox)):+ x0 = out_bbox[i][0]+ y0 = out_bbox[i][1]+ x1 = out_bbox[i][2]+ y1 = out_bbox[i][3]+ bbox = np.array([x0, y0, x1, y1])++ # get center and scale+ center, scale = bbox_xyxy2cs(bbox, padding=1.25)++ # do affine transformation+ resized_img, scale = top_down_affine(input_size, scale, center, img)++ # normalize image+ mean = np.array([123.675, 116.28, 103.53])+ std = np.array([58.395, 57.12, 57.375])+ resized_img = (resized_img - mean) / std++ out_img.append(resized_img)+ out_center.append(center)+ out_scale.append(scale)++ return out_img, out_center, out_scale+++def inference(sess: ort.InferenceSession, img: np.ndarray) -> np.ndarray:+ """Inference RTMPose model.++ Args:+ sess (ort.InferenceSession): ONNXRuntime session.+ img (np.ndarray): Input image in shape.++ Returns:+ outputs (np.ndarray): Output of RTMPose model.+ """+ all_out = []+ # build input+ for i in range(len(img)):+ input = [img[i].transpose(2, 0, 1)]++ # build output+ sess_input = {sess.get_inputs()[0].name: input}+ sess_output = []+ for out in sess.get_outputs():+ sess_output.append(out.name)++ outputs = sess.run(sess_output, sess_input)+ # outputs 也是len为2的列表,outputs[0] outputs[1]第一维为1+ all_out.append(outputs)++ # breakpoint()++ return all_out+++def postprocess(+ outputs: List[np.ndarray],+ model_input_size: Tuple[int, int],+ center: Tuple[int, int], # 实际是List of tuple+ scale: Tuple[int, int],+ simcc_split_ratio: float = 2.0,+) -> Tuple[np.ndarray, np.ndarray]:+ """Postprocess for RTMPose model output.++ Args:+ outputs (np.ndarray): Output of RTMPose model.+ model_input_size (tuple): RTMPose model Input image size.+ center (tuple): List of Center of bbox in shape (x, y).+ scale (tuple): List of Scale of bbox in shape (w, h).+ simcc_split_ratio (float): Split ratio of simcc.++ Returns:+ tuple:+ - keypoints (np.ndarray): Rescaled keypoints.+ - scores (np.ndarray): Model predict scores.+ """+ all_key = []+ all_score = []+ for i in range(len(outputs)):+ # use simcc to decode+ simcc_x, simcc_y = outputs[i]+ keypoints, scores = decode(simcc_x, simcc_y, simcc_split_ratio)++ # rescale keypoints+ keypoints = keypoints / model_input_size * scale[i] + center[i] - scale[i] / 2+ all_key.append(keypoints[0])+ all_score.append(scores[0])++ return np.array(all_key), np.array(all_score)+++def bbox_xyxy2cs(+ bbox: np.ndarray, padding: float = 1.0+) -> Tuple[np.ndarray, np.ndarray]:+ """Transform the bbox format from (x,y,w,h) into (center, scale)++ Args:+ bbox (ndarray): Bounding box(es) in shape (4,) or (n, 4), formatted+ as (left, top, right, bottom)+ padding (float): BBox padding factor that will be multilied to scale.+ Default: 1.0++ Returns:+ tuple: A tuple containing center and scale.+ - np.ndarray[float32]: Center (x, y) of the bbox in shape (2,) or+ (n, 2)+ - np.ndarray[float32]: Scale (w, h) of the bbox in shape (2,) or+ (n, 2)+ """+ # convert single bbox from (4, ) to (1, 4)+ dim = bbox.ndim+ if dim == 1:+ bbox = bbox[None, :]++ # get bbox center and scale+ x1, y1, x2, y2 = np.hsplit(bbox, [1, 2, 3])+ center = np.hstack([x1 + x2, y1 + y2]) * 0.5+ scale = np.hstack([x2 - x1, y2 - y1]) * padding++ if dim == 1:+ center = center[0]+ scale = scale[0]++ return center, scale+++def _fix_aspect_ratio(bbox_scale: np.ndarray, aspect_ratio: float) -> np.ndarray:+ """Extend the scale to match the given aspect ratio.++ Args:+ scale (np.ndarray): The image scale (w, h) in shape (2, )+ aspect_ratio (float): The ratio of ``w/h``++ Returns:+ np.ndarray: The reshaped image scale in (2, )+ """+ w, h = np.hsplit(bbox_scale, [1])+ bbox_scale = np.where(+ w > h * aspect_ratio,+ np.hstack([w, w / aspect_ratio]),+ np.hstack([h * aspect_ratio, h]),+ )+ return bbox_scale+++def _rotate_point(pt: np.ndarray, angle_rad: float) -> np.ndarray:+ """Rotate a point by an angle.++ Args:+ pt (np.ndarray): 2D point coordinates (x, y) in shape (2, )+ angle_rad (float): rotation angle in radian++ Returns:+ np.ndarray: Rotated point in shape (2, )+ """+ sn, cs = np.sin(angle_rad), np.cos(angle_rad)+ rot_mat = np.array([[cs, -sn], [sn, cs]])+ return rot_mat @ pt+++def _get_3rd_point(a: np.ndarray, b: np.ndarray) -> np.ndarray:+ """To calculate the affine matrix, three pairs of points are required. This+ function is used to get the 3rd point, given 2D points a & b.++ The 3rd point is defined by rotating vector `a - b` by 90 degrees+ anticlockwise, using b as the rotation center.++ Args:+ a (np.ndarray): The 1st point (x,y) in shape (2, )+ b (np.ndarray): The 2nd point (x,y) in shape (2, )++ Returns:+ np.ndarray: The 3rd point.+ """+ direction = a - b+ c = b + np.r_[-direction[1], direction[0]]+ return c+++def get_warp_matrix(+ center: np.ndarray,+ scale: np.ndarray,+ rot: float,+ output_size: Tuple[int, int],+ shift: Tuple[float, float] = (0.0, 0.0),+ inv: bool = False,+) -> np.ndarray:+ """Calculate the affine transformation matrix that can warp the bbox area+ in the input image to the output size.++ Args:+ center (np.ndarray[2, ]): Center of the bounding box (x, y).+ scale (np.ndarray[2, ]): Scale of the bounding box+ wrt [width, height].+ rot (float): Rotation angle (degree).+ output_size (np.ndarray[2, ] | list(2,)): Size of the+ destination heatmaps.+ shift (0-100%): Shift translation ratio wrt the width/height.+ Default (0., 0.).+ inv (bool): Option to inverse the affine transform direction.+ (inv=False: src->dst or inv=True: dst->src)++ Returns:+ np.ndarray: A 2x3 transformation matrix+ """+ shift = np.array(shift)+ src_w = scale[0]+ dst_w = output_size[0]+ dst_h = output_size[1]++ # compute transformation matrix+ rot_rad = np.deg2rad(rot)+ src_dir = _rotate_point(np.array([0.0, src_w * -0.5]), rot_rad)+ dst_dir = np.array([0.0, dst_w * -0.5])++ # get four corners of the src rectangle in the original image+ src = np.zeros((3, 2), dtype=np.float32)+ src[0, :] = center + scale * shift+ src[1, :] = center + src_dir + scale * shift+ src[2, :] = _get_3rd_point(src[0, :], src[1, :])++ # get four corners of the dst rectangle in the input image+ dst = np.zeros((3, 2), dtype=np.float32)+ dst[0, :] = [dst_w * 0.5, dst_h * 0.5]+ dst[1, :] = np.array([dst_w * 0.5, dst_h * 0.5]) + dst_dir+ dst[2, :] = _get_3rd_point(dst[0, :], dst[1, :])++ if inv:+ warp_mat = cv2.getAffineTransform(np.float32(dst), np.float32(src))+ else:+ warp_mat = cv2.getAffineTransform(np.float32(src), np.float32(dst))++ return warp_mat+++def top_down_affine(+ input_size: dict, bbox_scale: dict, bbox_center: dict, img: np.ndarray+) -> Tuple[np.ndarray, np.ndarray]:+ """Get the bbox image as the model input by affine transform.++ Args:+ input_size (dict): The input size of the model.+ bbox_scale (dict): The bbox scale of the img.+ bbox_center (dict): The bbox center of the img.+ img (np.ndarray): The original image.++ Returns:+ tuple: A tuple containing center and scale.+ - np.ndarray[float32]: img after affine transform.+ - np.ndarray[float32]: bbox scale after affine transform.+ """+ w, h = input_size+ warp_size = (int(w), int(h))++ # reshape bbox to fixed aspect ratio+ bbox_scale = _fix_aspect_ratio(bbox_scale, aspect_ratio=w / h)++ # get the affine matrix+ center = bbox_center+ scale = bbox_scale+ rot = 0+ warp_mat = get_warp_matrix(center, scale, rot, output_size=(w, h))++ # do affine transform+ img = cv2.warpAffine(img, warp_mat, warp_size, flags=cv2.INTER_LINEAR)++ return img, bbox_scale+++def get_simcc_maximum(+ simcc_x: np.ndarray, simcc_y: np.ndarray+) -> Tuple[np.ndarray, np.ndarray]:+ """Get maximum response location and value from simcc representations.++ Note:+ instance number: N+ num_keypoints: K+ heatmap height: H+ heatmap width: W++ Args:+ simcc_x (np.ndarray): x-axis SimCC in shape (K, Wx) or (N, K, Wx)+ simcc_y (np.ndarray): y-axis SimCC in shape (K, Wy) or (N, K, Wy)++ Returns:+ tuple:+ - locs (np.ndarray): locations of maximum heatmap responses in shape+ (K, 2) or (N, K, 2)+ - vals (np.ndarray): values of maximum heatmap responses in shape+ (K,) or (N, K)+ """+ N, K, Wx = simcc_x.shape+ simcc_x = simcc_x.reshape(N * K, -1)+ simcc_y = simcc_y.reshape(N * K, -1)++ # get maximum value locations+ x_locs = np.argmax(simcc_x, axis=1)+ y_locs = np.argmax(simcc_y, axis=1)+ locs = np.stack((x_locs, y_locs), axis=-1).astype(np.float32)+ max_val_x = np.amax(simcc_x, axis=1)+ max_val_y = np.amax(simcc_y, axis=1)++ # get maximum value across x and y axis+ mask = max_val_x > max_val_y+ max_val_x[mask] = max_val_y[mask]+ vals = max_val_x+ locs[vals <= 0.0] = -1++ # reshape+ locs = locs.reshape(N, K, 2)+ vals = vals.reshape(N, K)++ return locs, vals+++def decode(+ simcc_x: np.ndarray, simcc_y: np.ndarray, simcc_split_ratio+) -> Tuple[np.ndarray, np.ndarray]:+ """Modulate simcc distribution with Gaussian.++ Args:+ simcc_x (np.ndarray[K, Wx]): model predicted simcc in x.+ simcc_y (np.ndarray[K, Wy]): model predicted simcc in y.+ simcc_split_ratio (int): The split ratio of simcc.++ Returns:+ tuple: A tuple containing center and scale.+ - np.ndarray[float32]: keypoints in shape (K, 2) or (n, K, 2)+ - np.ndarray[float32]: scores in shape (K,) or (n, K)+ """+ keypoints, scores = get_simcc_maximum(simcc_x, simcc_y)+ keypoints /= simcc_split_ratio++ return keypoints, scores+++def inference_pose(session, out_bbox, oriImg):+ h, w = session.get_inputs()[0].shape[2:]+ model_input_size = (w, h)+ resized_img, center, scale = preprocess(oriImg, out_bbox, model_input_size)+ outputs = inference(session, resized_img)+ keypoints, scores = postprocess(outputs, model_input_size, center, scale)++ return keypoints, scores+++def inference_pose_batch(session, out_bbox, oriImg):+ h, w = session.get_inputs()[0].shape[2:]+ model_input_size = (w, h)+ # breakpoint()+ num_boxes = [box.shape[0] if len(box)>=1 else 1 for box in out_bbox]+ resized_img, center, scale = preprocess_batch(oriImg, out_bbox, model_input_size)+ outputs = inference_batch(session, resized_img) # nparray 第0维为(\sum_{batch_num} num_box)+ keypoints, scores = postprocess_batch(outputs, num_boxes, model_input_size, center, scale)+ # keypoints和scores在postprocess中从(\sum_{batch_num} num_box) 恢复为 a list of batch_num of nparray[num_box, ...]++ return keypoints, scores+++def preprocess_batch(+ img_list: List[np.ndarray], out_bbox_list, input_size: Tuple[int, int] = (192, 256)+) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:+ # img_list shape: batch_num * nparray[C, H, W]+ # out_bbox_list shape: batch_bum * nparray[num_box, 4]+ resized_imgs = []+ centers = []+ scales = []++ for img, out_bbox in zip(img_list, out_bbox_list):+ resized_img, center, scale = preprocess(img, out_bbox, input_size)+ # 有的out_bbox是两个+ # resized_img: list of array, num_box*nparray [C, H', W']+ resized_imgs.extend(resized_img)+ centers.extend(center)+ scales.extend(scale)+ # resized_imgs 为 nparray 第0维为(\sum_{batch_num} num_box)+ # centers和scales 为 list of nparray len为(\sum_{batch_num} num_box)+ return np.stack(resized_imgs), centers, scales+++def inference_batch(sess: ort.InferenceSession, batch_img):+ """Inference RTMPose model in batch."""+ # build input+ input = batch_img.transpose(0, 3, 1, 2).astype(np.float32)++ # build output+ sess_input = {sess.get_inputs()[0].name: input}+ sess_output = []+ for out in sess.get_outputs():+ sess_output.append(out.name)++ outputs = sess.run(sess_output, sess_input)+ num = outputs[0].shape[0]+ split_0 = np.split(outputs[0], num, axis=0)+ split_1 = np.split(outputs[1], num, axis=0)+ # 创建最终的输出列表,其中每个元素是一个包含两个 nparray 的列表+ final_output = [[split_0[i], split_1[i]] for i in range(num)]+ return final_output # list of nparray 长度为(\sum_{batch_num} num_box)++def postprocess_batch(+ outputs: List[np.ndarray],+ num_boxes: List[int],+ model_input_size: Tuple[int, int],+ center: List[Tuple[int, int]],+ scale: List[Tuple[int, int]],+ simcc_split_ratio: float = 2.0,+) -> Tuple[np.ndarray, np.ndarray]:+ # keypoints和scores在postprocess中根据num_boxes从(\sum_{batch_num} num_box) 恢复为 a list of batch_num of nparray[num_box, ...]+ all_key, all_score = postprocess(outputs, model_input_size, center, scale, simcc_split_ratio)+ relist_all_key, relist_all_score = [], []+ start_idx = 0+ for num_box in num_boxes:+ # 按照每个 batch 的 num_box 从 all_key 和 all_score 中恢复出对应的部分+ split_indices = np.cumsum(num_boxes)+ split_indices = np.insert(split_indices, 0, 0) # 在开头插入0 -> 0, len1, len1+len2...+ # 恢复每个batch的 keypoints 和 scores+ relist_all_key = [all_key[split_indices[i]:split_indices[i + 1]] for i in range(len(split_indices) - 1)]+ relist_all_score = [all_score[split_indices[i]:split_indices[i + 1]] for i in range(len(split_indices) - 1)]+ return relist_all_key, relist_all_score # a list of batch_num of nparray[num_box, ...]+++# Main function for testing inference_pose_batch+def main():+ # 创建一个简单的测试图像和假边界框+ img = np.random.rand(256, 192, 3).astype(np.float32) # 一张随机图像+ out_bbox = np.array([[50, 50, 150, 150]])++ img_list = [np.random.rand(256, 192, 3).astype(np.float32) for _ in range(3)] # 3张随机图像+ out_bbox_list = [+ np.array([[50, 50, 150, 150]]), # 第一个批次: 1个框+ np.array([[30, 30, 130, 130], [50, 50, 200, 200]]), # 第二个批次: 2个框+ np.array([[10, 10, 100, 100]]), # 第三个批次: 1个框+ ]++ # 加载 ONNX 模型+ model_path = "/workspace/yanwenhao/Moore-AnimateAnyone/pretrained_weights/DWPose/dw-ll_ucoco_384.onnx" # 在此替换为实际的模型路径+ sess = ort.InferenceSession(model_path)++ # 调用 inference_pose 进行单张图像推理+ keypoints, scores = inference_pose(sess, out_bbox, img)++ # 输出结果+ print("single infer test")+ print("Keypoints:", keypoints.shape)+ print("Scores:", scores.shape)++ # 调用 inference_pose_batch 进行推理+ keypoints, scores = inference_pose_batch(sess, out_bbox_list, img_list)++ # 输出结果+ print("batch infer test")+ for i, (keypoint, score) in enumerate(zip(keypoints, scores)):+ print(f"Batch_index {i + 1}:")+ print("Keypoints:", keypoint.shape)+ print("Scores:", score.shape)++# 调用 main 函数+if __name__ == "__main__":+ main()diff --git a/models/wan/scail/scail_pose_dwpose_wholebody.py b/models/wan/scail/scail_pose_dwpose_wholebody.pynew file mode 100644index 0000000..ec1b101--- /dev/null+++ b/models/wan/scail/scail_pose_dwpose_wholebody.py@@ -0,0 +1,56 @@+# https://github.com/IDEA-Research/DWPose++import numpy as np+import onnxruntime as ort++from shared.utils import files_locator as fl++from .scail_pose_dwpose_onnxdet import inference_detector+from .scail_pose_dwpose_onnxpose import inference_pose, inference_pose_batch+++class Wholebody:+ def __init__(self, device, use_batch=False):+ providers = [("CUDAExecutionProvider", {+ "device_id": device+ })]+ # providers = [("CPUExecutionProvider", {})]+ onnx_det = fl.locate_file("pose/yolox_l.onnx")+ onnx_pose = fl.locate_file("pose/dw-ll_ucoco_384.onnx")++ self.session_det = ort.InferenceSession(+ path_or_bytes=onnx_det, providers=providers+ )+ self.session_pose = ort.InferenceSession(+ path_or_bytes=onnx_pose, providers=providers+ )+ self.use_batch = use_batch++ def _get_result_from_det_pose(self, det_result, keypoints, scores):+ keypoints_info = np.concatenate((keypoints, scores[..., None]), axis=-1) # (1, 133, 3)+ # compute neck joint+ neck = np.mean(keypoints_info[:, [5, 6]], axis=1) # (1, 3),对第五第六个点做平均+ # neck score when visualizing pred+ neck[:, 2:4] = np.logical_and(+ keypoints_info[:, 5, 2:4] > 0.3, keypoints_info[:, 6, 2:4] > 0.3+ ).astype(int) # 从第二个开始切片,这里维度为3,只切一片+ new_keypoints_info = np.insert(keypoints_info, 17, neck, axis=1) # 在17索引处插入neck+ # 调换骨骼索引+ mmpose_idx = [17, 6, 8, 10, 7, 9, 12, 14, 16, 13, 15, 2, 1, 4, 3]+ openpose_idx = [1, 2, 3, 4, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17] # openpose需要检测17点+1脖子关键点+ new_keypoints_info[:, openpose_idx] = new_keypoints_info[:, mmpose_idx]+ keypoints_info = new_keypoints_info++ keypoints, scores = keypoints_info[..., :2], keypoints_info[..., 2]++ return keypoints, scores, det_result+++ def __call__(self, oriImg):+ if not self.use_batch:+ det_result = inference_detector(self.session_det, oriImg)+ keypoints, scores = inference_pose(self.session_pose, det_result, oriImg) # keypoints: (n_bbox, 133, 2) scores: (n_bbox, 133) 不管输入是什么初步提取的关键点数量都是一致的+ return self._get_result_from_det_pose(det_result=det_result, keypoints=keypoints, scores=scores)++ else:+ raise NotImplementedError("DWposeDetector does not support batch mode")diff --git a/models/wan/scail/scail_pose_multi.py b/models/wan/scail/scail_pose_multi.pynew file mode 100644index 0000000..f9caeb5--- /dev/null+++ b/models/wan/scail/scail_pose_multi.py@@ -0,0 +1,60 @@+from __future__ import annotations++from typing import Sequence++import numpy as np+++def get_largest_bbox_indices(bboxes: Sequence[Sequence[float]], num_bboxes: int = 2) -> list[int]:+ """Return indices of the largest bboxes by area (normalized coords are fine)."""+ if num_bboxes <= 0:+ return []++ bboxes_with_area: list[tuple[int, float]] = []+ for i, bbox in enumerate(bboxes):+ try:+ x1, y1, x2, y2 = bbox+ except Exception:+ continue+ area = max(0.0, float(x2) - float(x1)) * max(0.0, float(y2) - float(y1))+ bboxes_with_area.append((i, area))++ bboxes_with_area.sort(key=lambda x: x[1], reverse=True)+ return [idx for idx, _area in bboxes_with_area[: min(num_bboxes, len(bboxes_with_area))]]+++def change_poses_to_limit_num(poses, bboxes, num_bboxes: int = 2):+ """Trim DWpose outputs to the top-N bboxes per frame (SCAIL-Pose multi-human helper)."""+ bboxes = list(bboxes)+ for frame_idx, (pose, bbox_list) in enumerate(zip(poses, bboxes)):+ if not bbox_list:+ continue++ largest_indices = get_largest_bbox_indices(bbox_list, num_bboxes)+ if not largest_indices:+ continue++ bodies = pose.get("bodies", {})+ if "candidate" in bodies:+ bodies["candidate"] = bodies["candidate"][largest_indices]+ if "subset" in bodies:+ bodies["subset"] = bodies["subset"][largest_indices]+ pose["bodies"] = bodies++ faces = pose.get("faces", None)+ if isinstance(faces, np.ndarray):+ pose["faces"] = faces[largest_indices]+ elif isinstance(faces, list):+ pose["faces"] = [faces[i] for i in largest_indices if i < len(faces)]++ hands = pose.get("hands", None)+ hand_indices = [j for i in largest_indices for j in (2 * i, 2 * i + 1)]+ if isinstance(hands, np.ndarray):+ pose["hands"] = hands[hand_indices]+ elif isinstance(hands, list):+ pose["hands"] = [hands[i] for i in hand_indices if i < len(hands)]++ bboxes[frame_idx] = [bbox_list[i] for i in largest_indices if i < len(bbox_list)]++ return poses, bboxes+diff --git a/models/wan/scail/scail_pose_nlf.py b/models/wan/scail/scail_pose_nlf.pynew file mode 100644index 0000000..2470624--- /dev/null+++ b/models/wan/scail/scail_pose_nlf.py@@ -0,0 +1,677 @@+"""+NLFPose extraction + rendering helpers from the official SCAIL-Pose implementation.++Upstream: https://github.com/zai-org/SCAIL-Pose+- NLFPoseExtract/extract_nlfpose_batch.py (process_video_nlf)+- NLFPoseExtract/nlf_draw.py (intrinsic_matrix_from_field_of_view, process_data_to_COCO_format)+- NLFPoseExtract/nlf_render.py (render_nlf_as_images and helpers)+- NLFPoseExtract/process_pose.py (recollect_* and scale_faces)++"""++from __future__ import annotations++import copy+import math+import random+from typing import List, Optional++import numpy as np+import torch++from .scail_pose_draw import draw_pose_to_canvas_np, scale_image_hw_keep_size+from .scail_pose_taichi_cylinder import render_whole+++def process_data_to_COCO_format(joints: np.ndarray) -> np.ndarray:+ """Map 24-joint NLF pose to (18, dim) COCO-like format used by SCAIL-Pose."""+ if joints.ndim != 2:+ raise ValueError(f"Expected shape (24,2) or (24,3), got {joints.shape}")++ dim = joints.shape[1]+ mapping = {+ 15: 0, # head+ 12: 1, # neck+ 17: 2, # left shoulder+ 16: 5, # right shoulder+ 19: 3, # left elbow+ 18: 6, # right elbow+ 21: 4, # left hand+ 20: 7, # right hand+ 2: 8, # left pelvis+ 1: 11, # right pelvis+ 5: 9, # left knee+ 4: 12, # right knee+ 8: 10, # left feet+ 7: 13, # right feet+ }++ new_joints = np.zeros((18, dim), dtype=joints.dtype)+ for src, dst in mapping.items():+ new_joints[dst] = joints[src]+ return new_joints+++def intrinsic_matrix_from_field_of_view(imshape, fov_degrees: float = 55):+ imshape = np.array(imshape)+ fov_radians = fov_degrees * np.array(np.pi / 180)+ larger_side = np.max(imshape)+ focal_length = larger_side / (np.tan(fov_radians / 2) * 2)+ return np.array(+ [+ [focal_length, 0, imshape[1] / 2],+ [0, focal_length, imshape[0] / 2],+ [0, 0, 1],+ ]+ )+++def process_video_nlf(model, vr_frames: torch.Tensor, bboxes):+ pose_meta_list = []+ vr_frames = vr_frames.cuda()+ height, width = vr_frames.shape[1], vr_frames.shape[2]+ result_list = []++ batch_size = 64+ buffer = torch.zeros((batch_size, height, width, 3), dtype=vr_frames.dtype, device="cuda")+ buffer_count = 0+ with torch.inference_mode():+ for frame, bbox_list in zip(vr_frames, bboxes):+ for bbox in bbox_list:+ x1, y1, x2, y2 = bbox+ x1_px = max(0, math.floor(x1 * width - width * 0.025))+ y1_px = max(0, math.floor(y1 * height - height * 0.05))+ x2_px = min(width, math.ceil(x2 * width + width * 0.025))+ y2_px = min(height, math.ceil(y2 * height + height * 0.05))++ cropped_region = frame[y1_px:y2_px, x1_px:x2_px, :]+ buffer[buffer_count, y1_px:y2_px, x1_px:x2_px, :] = cropped_region+ buffer_count += 1++ if buffer_count == batch_size:+ frame_batch = buffer.permute(0, 3, 1, 2)+ pred = model.detect_smpl_batched(frame_batch)+ if "joints3d_nonparam" in pred:+ result_list.extend(pred["joints3d_nonparam"])+ else:+ result_list.extend([None] * buffer_count)++ buffer.zero_()+ buffer_count = 0++ if buffer_count > 0:+ frame_batch = buffer[:buffer_count].permute(0, 3, 1, 2)+ pred = model.detect_smpl_batched(frame_batch)+ if "joints3d_nonparam" in pred:+ result_list.extend(pred["joints3d_nonparam"])+ else:+ result_list.extend([None] * buffer_count)++ index = 0+ for bbox_list in bboxes:+ n = len(bbox_list)+ pose_meta_list.append(+ {+ "video_height": height,+ "video_width": width,+ "bboxes": bbox_list,+ "nlfpose": result_list[index : index + n],+ }+ )+ index += n++ del buffer+ torch.cuda.empty_cache()+ return pose_meta_list+++def process_video_multi_nlf(model, vr_frames_list: List[torch.Tensor]):+ """Run NLF on pre-segmented per-person videos and keep results separate per person.++ This mirrors the official SCAIL-Pose multi-human pipeline: segment each character,+ run NLF independently per character-video, then render them together.++ Args:+ vr_frames_list: list of per-person tensors shaped (T,H,W,3) uint8.++ Returns:+ list of dicts (length T) with keys: video_height, video_width, bboxes=None,+ nlfpose=[per_person_prediction, ...] where each prediction is a tensor of+ shape (n_detections, 24, 3) (or empty) for that person.+ """+ if not vr_frames_list:+ return []++ n_people = len(vr_frames_list)+ lengths = [int(v.shape[0]) for v in vr_frames_list]+ if len(set(lengths)) != 1:+ raise ValueError(f"All person videos must have the same length, got {lengths}")++ vr_frames_list = [v.cuda() for v in vr_frames_list]+ vr_frames_first = vr_frames_list[0]+ height, width = int(vr_frames_first.shape[1]), int(vr_frames_first.shape[2])++ pose_meta_list = []+ result_list = []++ batch_size = 64+ buffer = torch.zeros((batch_size, height, width, 3), dtype=vr_frames_first.dtype, device="cuda")+ buffer_count = 0++ with torch.inference_mode():+ for frame_idx in range(lengths[0]):+ for person_idx in range(n_people):+ buffer[buffer_count] = vr_frames_list[person_idx][frame_idx]+ buffer_count += 1++ if buffer_count == batch_size:+ frame_batch = buffer.permute(0, 3, 1, 2)+ pred = model.detect_smpl_batched(frame_batch)+ if "joints3d_nonparam" in pred:+ result_list.extend(pred["joints3d_nonparam"])+ else:+ result_list.extend([None] * buffer_count)++ buffer.zero_()+ buffer_count = 0++ if buffer_count > 0:+ frame_batch = buffer[:buffer_count].permute(0, 3, 1, 2)+ pred = model.detect_smpl_batched(frame_batch)+ if "joints3d_nonparam" in pred:+ result_list.extend(pred["joints3d_nonparam"])+ else:+ result_list.extend([None] * buffer_count)++ index = 0+ for _ in range(lengths[0]):+ pose_meta_list.append(+ {"video_height": height, "video_width": width, "bboxes": None, "nlfpose": result_list[index : index + n_people]}+ )+ index += n_people++ del buffer+ torch.cuda.empty_cache()+ return pose_meta_list+++def recollect_nlf(data):+ new_data = []+ for item in data:+ new_item = item.copy()+ if len(item["bboxes"]) > 0:+ new_item["bboxes"] = item["bboxes"][:1]+ new_item["nlfpose"] = item["nlfpose"][:1]+ new_data.append(new_item)+ return new_data+++def recollect_dwposes(poses):+ new_poses = []+ for pose in poses:+ for i in range(1):+ bodies = pose["bodies"]+ faces = pose["faces"][i : i + 1]+ hands = pose["hands"][2 * i : 2 * i + 2]+ candidate = bodies["candidate"][i : i + 1]+ subset = bodies["subset"][i : i + 1]+ new_pose = {"bodies": {"candidate": candidate, "subset": subset}, "faces": faces, "hands": hands}+ new_poses.append(new_pose)+ return new_poses+++def scale_faces(poses, pose_2d_ref):+ ref = pose_2d_ref[0]+ pose_0 = poses[0]++ face_0 = pose_0["faces"]+ face_ref = ref["faces"]++ face_0 = np.array(face_0[0])+ face_ref = np.array(face_ref[0])++ center_idx = 30+ center_0 = face_0[center_idx]+ center_ref = face_ref[center_idx]++ dist = np.linalg.norm(face_0 - center_0, axis=1)+ dist_ref = np.linalg.norm(face_ref - center_ref, axis=1)++ dist = np.delete(dist, center_idx)+ dist_ref = np.delete(dist_ref, center_idx)++ mean_dist = np.mean(dist)+ mean_dist_ref = np.mean(dist_ref)++ if mean_dist < 1e-6:+ scale_n = 1.0+ else:+ scale_n = mean_dist_ref / mean_dist++ scale_n = np.clip(scale_n, 0.8, 1.5)++ for i, pose in enumerate(poses):+ face = pose["faces"]+ face = np.array(face[0])+ center = face[center_idx]+ scaled_face = (face - center) * scale_n + center+ poses[i]["faces"][0] = scaled_face++ body = pose["bodies"]+ candidate = body["candidate"]+ candidate_np = np.array(candidate[0])+ body_center = candidate_np[0]+ scaled_candidate = (candidate_np - body_center) * scale_n + body_center+ poses[i]["bodies"]["candidate"][0] = scaled_candidate++ pose["faces"][0] = scaled_face+ return scale_n+++def p3d_single_p2d(points, intrinsic_matrix):+ X, Y, Z = points[0], points[1], points[2]+ u = (intrinsic_matrix[0, 0] * X / Z) + intrinsic_matrix[0, 2]+ v = (intrinsic_matrix[1, 1] * Y / Z) + intrinsic_matrix[1, 2]+ u_np = u.cpu().numpy()+ v_np = v.cpu().numpy()+ return np.array([u_np, v_np])+++def shift_dwpose_according_to_nlf(smpl_poses, aligned_poses, ori_intrinstics, modified_intrinstics, height, width):+ for i in range(len(smpl_poses)):+ persons_joints_list = smpl_poses[i]+ poses_list = aligned_poses[i]+ for person_idx, person_joints in enumerate(persons_joints_list):+ face = poses_list["faces"][person_idx]+ right_hand = poses_list["hands"][2 * person_idx]+ left_hand = poses_list["hands"][2 * person_idx + 1]+ candidate = poses_list["bodies"]["candidate"][person_idx]++ person_joint_15_2d_shift = (+ p3d_single_p2d(person_joints[15], modified_intrinstics) - p3d_single_p2d(person_joints[15], ori_intrinstics)+ if person_joints[15, 2] > 0.01+ else np.array([0.0, 0.0])+ )+ person_joint_20_2d_shift = (+ p3d_single_p2d(person_joints[20], modified_intrinstics) - p3d_single_p2d(person_joints[20], ori_intrinstics)+ if person_joints[20, 2] > 0.01+ else np.array([0.0, 0.0])+ )+ person_joint_21_2d_shift = (+ p3d_single_p2d(person_joints[21], modified_intrinstics) - p3d_single_p2d(person_joints[21], ori_intrinstics)+ if person_joints[21, 2] > 0.01+ else np.array([0.0, 0.0])+ )++ face[:, 0] += person_joint_15_2d_shift[0] / width+ face[:, 1] += person_joint_15_2d_shift[1] / height+ right_hand[:, 0] += person_joint_20_2d_shift[0] / width+ right_hand[:, 1] += person_joint_20_2d_shift[1] / height+ left_hand[:, 0] += person_joint_21_2d_shift[0] / width+ left_hand[:, 1] += person_joint_21_2d_shift[1] / height+ candidate[:, 0] += person_joint_15_2d_shift[0] / width+ candidate[:, 1] += person_joint_15_2d_shift[1] / height+++def get_single_pose_cylinder_specs(args):+ idx, pose, focal, princpt, height, width, colors, limb_seq, draw_seq = args+ cylinder_specs = []++ for joints3d in pose:+ joints3d = joints3d.cpu().numpy()+ joints3d = process_data_to_COCO_format(joints3d)+ for line_idx in draw_seq:+ line = limb_seq[line_idx]+ start, end = line[0], line[1]+ if np.sum(joints3d[start]) == 0 or np.sum(joints3d[end]) == 0:+ continue+ cylinder_specs.append((joints3d[start], joints3d[end], colors[line_idx]))+ return cylinder_specs+++def collect_smpl_poses(data):+ uncollected_smpl_poses = [item["nlfpose"] for item in data]+ smpl_poses = [[] for _ in range(len(uncollected_smpl_poses))]+ for frame_idx in range(len(uncollected_smpl_poses)):+ for person_idx in range(len(uncollected_smpl_poses[frame_idx])):+ if len(uncollected_smpl_poses[frame_idx][person_idx]) > 0:+ smpl_poses[frame_idx].append(uncollected_smpl_poses[frame_idx][person_idx][0])+ else:+ smpl_poses[frame_idx].append(torch.zeros((24, 3), dtype=torch.float32))+ return smpl_poses+++def render_nlf_as_images(+ data,+ poses,+ reshape_pool=None,+ intrinsic_matrix=None,+ draw_2d=True,+ aug_2d=False,+ aug_cam=False,+):+ height, width = data[0]["video_height"], data[0]["video_width"]+ video_length = len(data)++ base_colors_255_dict = {+ "Red": [255, 0, 0],+ "Orange": [255, 85, 0],+ "Golden Orange": [255, 170, 0],+ "Yellow": [255, 240, 0],+ "Yellow-Green": [180, 255, 0],+ "Bright Green": [0, 255, 0],+ "Light Green-Blue": [0, 255, 85],+ "Aqua": [0, 255, 170],+ "Cyan": [0, 255, 255],+ "Sky Blue": [0, 170, 255],+ "Medium Blue": [0, 85, 255],+ "Pure Blue": [0, 0, 255],+ "Purple-Blue": [85, 0, 255],+ "Medium Purple": [170, 0, 255],+ "Grey": [150, 150, 150],+ "Pink-Magenta": [255, 0, 170],+ "Dark Pink": [255, 0, 85],+ "Violet": [100, 0, 255],+ "Dark Violet": [50, 0, 255],+ }++ ordered_colors_255 = [+ base_colors_255_dict["Red"],+ base_colors_255_dict["Cyan"],+ base_colors_255_dict["Orange"],+ base_colors_255_dict["Golden Orange"],+ base_colors_255_dict["Sky Blue"],+ base_colors_255_dict["Medium Blue"],+ base_colors_255_dict["Yellow-Green"],+ base_colors_255_dict["Bright Green"],+ base_colors_255_dict["Light Green-Blue"],+ base_colors_255_dict["Pure Blue"],+ base_colors_255_dict["Purple-Blue"],+ base_colors_255_dict["Medium Purple"],+ base_colors_255_dict["Grey"],+ base_colors_255_dict["Pink-Magenta"],+ base_colors_255_dict["Dark Violet"],+ base_colors_255_dict["Pink-Magenta"],+ base_colors_255_dict["Dark Violet"],+ ]++ limb_seq = [+ [1, 2],+ [1, 5],+ [2, 3],+ [3, 4],+ [5, 6],+ [6, 7],+ [1, 8],+ [8, 9],+ [9, 10],+ [1, 11],+ [11, 12],+ [12, 13],+ [1, 0],+ [0, 14],+ [14, 16],+ [0, 15],+ [15, 17],+ ]++ draw_seq = [+ 0,+ 2,+ 3,+ 1,+ 4,+ 5,+ 6,+ 7,+ 8,+ 9,+ 10,+ 11,+ 12,+ 13,+ 14,+ 15,+ 16,+ ]++ colors = [[c / 300 + 0.15 for c in color_rgb] + [0.8] for color_rgb in ordered_colors_255]++ if poses is not None:+ smpl_poses = collect_smpl_poses(data)+ aligned_poses = copy.deepcopy(poses)+ if reshape_pool is not None:+ for i in range(video_length):+ persons_joints_list = smpl_poses[i]+ poses_list = aligned_poses[i]+ for person_idx, person_joints in enumerate(persons_joints_list):+ candidate = poses_list["bodies"]["candidate"][person_idx]+ subset = poses_list["bodies"]["subset"][person_idx]+ face = poses_list["faces"][person_idx]+ right_hand = poses_list["hands"][2 * person_idx]+ left_hand = poses_list["hands"][2 * person_idx + 1]+ reshape_pool.apply_random_reshapes(person_joints, candidate, left_hand, right_hand, face, subset)+ else:+ smpl_poses = [item["nlfpose"] for item in data]+ aligned_poses = None++ if intrinsic_matrix is None:+ intrinsic_matrix = intrinsic_matrix_from_field_of_view((height, width))+ focal_x = intrinsic_matrix[0, 0]+ focal_y = intrinsic_matrix[1, 1]+ princpt = (intrinsic_matrix[0, 2], intrinsic_matrix[1, 2])++ if aug_cam and random.random() < 0.3 and aligned_poses is not None:+ w_shift_factor = random.uniform(-0.04, 0.04)+ h_shift_factor = random.uniform(-0.04, 0.04)+ princpt = (princpt[0] - w_shift_factor * width, princpt[1] - h_shift_factor * height)+ new_intrinsic_matrix = copy.deepcopy(intrinsic_matrix)+ new_intrinsic_matrix[0, 2] = princpt[0]+ new_intrinsic_matrix[1, 2] = princpt[1]+ shift_dwpose_according_to_nlf(smpl_poses, aligned_poses, intrinsic_matrix, new_intrinsic_matrix, height, width)++ cylinder_specs_list = []+ for i in range(video_length):+ cylinder_specs = get_single_pose_cylinder_specs((i, smpl_poses[i], None, None, None, None, colors, limb_seq, draw_seq))+ cylinder_specs_list.append(cylinder_specs)++ frames_np_rgba = render_whole(+ cylinder_specs_list, H=height, W=width, fx=focal_x, fy=focal_y, cx=princpt[0], cy=princpt[1]+ )++ if poses is not None and draw_2d:+ canvas_2d = draw_pose_to_canvas_np(+ aligned_poses,+ pool=None,+ H=height,+ W=width,+ reshape_scale=0,+ show_feet_flag=False,+ show_body_flag=False,+ show_cheek_flag=True,+ dw_hand=True,+ )+ scale_h = random.uniform(0.85, 1.15)+ scale_w = random.uniform(0.85, 1.15)+ rescale_flag = random.random() < 0.4 if reshape_pool is not None else False+ for i in range(len(frames_np_rgba)):+ frame_img = frames_np_rgba[i]+ canvas_img = canvas_2d[i]+ mask = canvas_img != 0+ frame_img[:, :, :3][mask] = canvas_img[mask]+ frames_np_rgba[i] = frame_img+ if aug_2d:+ if rescale_flag:+ frames_np_rgba[i] = scale_image_hw_keep_size(frames_np_rgba[i], scale_h, scale_w)+ if reshape_pool is not None:+ if random.random() < 0.04:+ frames_np_rgba[i][:, :, 0:3] = 0+ else:+ scale_h = random.uniform(0.85, 1.15)+ scale_w = random.uniform(0.85, 1.15)+ rescale_flag = random.random() < 0.4 if reshape_pool is not None else False+ for i in range(len(frames_np_rgba)):+ if aug_2d:+ if rescale_flag:+ frames_np_rgba[i] = scale_image_hw_keep_size(frames_np_rgba[i], scale_h, scale_w)+ if reshape_pool is not None:+ if random.random() < 0.04:+ frames_np_rgba[i][:, :, 0:3] = 0++ return frames_np_rgba+++def render_multi_nlf_as_images(+ data,+ poses,+ reshape_pool=None,+ intrinsic_matrix=None,+ draw_2d=True,+ aug_2d=False,+ aug_cam=False,+):+ """Render multi-person NLF results with per-person color palettes (SCAIL-Pose multi-human)."""+ height, width = data[0]["video_height"], data[0]["video_width"]+ video_length = len(data)++ # Pastel-ish palette for person 1, saturated palette for person 2 (matches upstream).+ second_person_base_colors_255_dict = {+ "Red": [255, 20, 20],+ "Orange": [255, 60, 0],+ "Golden Orange": [255, 110, 0],+ "Yellow": [255, 200, 0],+ "Yellow-Green": [160, 255, 40],+ "Bright Green": [0, 255, 50],+ "Light Green-Blue": [0, 255, 100],+ "Aqua": [0, 255, 200],+ "Cyan": [0, 230, 255],+ "Sky Blue": [0, 130, 255],+ "Medium Blue": [0, 70, 255],+ "Pure Blue": [0, 0, 255],+ "Purple-Blue": [80, 0, 255],+ "Medium Purple": [160, 0, 255],+ "Grey": [130, 130, 130],+ "Pink-Magenta": [255, 0, 150],+ "Dark Pink": [255, 0, 100],+ "Violet": [120, 0, 255],+ "Dark Violet": [60, 0, 255],+ }++ first_person_base_colors_255_dict = {+ "Red": [255, 150, 150],+ "Orange": [255, 180, 140],+ "Golden Orange": [255, 215, 150],+ "Yellow": [255, 240, 170],+ "Yellow-Green": [200, 255, 100],+ "Bright Green": [100, 255, 100],+ "Light Green-Blue": [140, 255, 180],+ "Aqua": [150, 240, 200],+ "Cyan": [180, 230, 240],+ "Sky Blue": [160, 200, 255],+ "Medium Blue": [100, 120, 255],+ "Pure Blue": [120, 140, 255],+ "Purple-Blue": [180, 90, 255],+ "Medium Purple": [190, 120, 255],+ "Grey": [210, 210, 210],+ "Pink-Magenta": [255, 120, 200],+ "Dark Pink": [255, 150, 180],+ "Violet": [200, 90, 255],+ "Dark Violet": [130, 80, 255],+ }++ ordered_colors_255_list = []+ for base_colors_255_dict in [first_person_base_colors_255_dict, second_person_base_colors_255_dict]:+ ordered_colors_255_list.append(+ [+ base_colors_255_dict["Red"],+ base_colors_255_dict["Cyan"],+ base_colors_255_dict["Orange"],+ base_colors_255_dict["Golden Orange"],+ base_colors_255_dict["Sky Blue"],+ base_colors_255_dict["Medium Blue"],+ base_colors_255_dict["Yellow-Green"],+ base_colors_255_dict["Bright Green"],+ base_colors_255_dict["Light Green-Blue"],+ base_colors_255_dict["Pure Blue"],+ base_colors_255_dict["Purple-Blue"],+ base_colors_255_dict["Medium Purple"],+ base_colors_255_dict["Grey"],+ base_colors_255_dict["Pink-Magenta"],+ base_colors_255_dict["Dark Violet"],+ base_colors_255_dict["Pink-Magenta"],+ base_colors_255_dict["Dark Violet"],+ ]+ )++ limb_seq = [+ [1, 2],+ [1, 5],+ [2, 3],+ [3, 4],+ [5, 6],+ [6, 7],+ [1, 8],+ [8, 9],+ [9, 10],+ [1, 11],+ [11, 12],+ [12, 13],+ [1, 0],+ [0, 14],+ [14, 16],+ [0, 15],+ [15, 17],+ ]++ draw_seq = [0, 2, 3, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]++ smpl_poses = collect_smpl_poses(data)+ max_people = max((len(p) for p in smpl_poses), default=0)+ colors_per_person = []+ for person_idx in range(max_people):+ palette_idx = min(person_idx, len(ordered_colors_255_list) - 1)+ colors_per_person.append([[c / 300 + 0.15 for c in rgb] + [0.8] for rgb in ordered_colors_255_list[palette_idx]])++ if intrinsic_matrix is None:+ intrinsic_matrix = intrinsic_matrix_from_field_of_view((height, width))+ focal_x = intrinsic_matrix[0, 0]+ focal_y = intrinsic_matrix[1, 1]+ princpt = (intrinsic_matrix[0, 2], intrinsic_matrix[1, 2])++ cylinder_specs_list = []+ for frame_idx in range(video_length):+ specs = []+ for person_idx, joints3d in enumerate(smpl_poses[frame_idx]):+ if person_idx >= len(colors_per_person):+ break+ joints3d_np = process_data_to_COCO_format(joints3d.cpu().numpy())+ for line_idx in draw_seq:+ start, end = limb_seq[line_idx]+ if np.sum(joints3d_np[start]) == 0 or np.sum(joints3d_np[end]) == 0:+ continue+ specs.append((joints3d_np[start], joints3d_np[end], colors_per_person[person_idx][line_idx]))+ cylinder_specs_list.append(specs)++ frames_np_rgba = render_whole(cylinder_specs_list, H=height, W=width, fx=focal_x, fy=focal_y, cx=princpt[0], cy=princpt[1])++ if poses is not None and draw_2d:+ aligned_poses = copy.deepcopy(poses)+ canvas_2d = draw_pose_to_canvas_np(+ aligned_poses,+ pool=None,+ H=height,+ W=width,+ reshape_scale=0,+ show_feet_flag=False,+ show_body_flag=False,+ show_cheek_flag=True,+ dw_hand=True,+ )+ for i in range(len(frames_np_rgba)):+ frame_img = frames_np_rgba[i]+ canvas_img = canvas_2d[i]+ mask = canvas_img != 0+ frame_img[:, :, :3][mask] = canvas_img[mask]+ frames_np_rgba[i] = frame_img++ return frames_np_rgbadiff --git a/models/wan/scail/scail_pose_taichi_cylinder.py b/models/wan/scail/scail_pose_taichi_cylinder.pynew file mode 100644index 0000000..8f137c6--- /dev/null+++ b/models/wan/scail/scail_pose_taichi_cylinder.py@@ -0,0 +1,198 @@+"""+Taichi cylinder renderer (GPU) from the official SCAIL-Pose implementation.++Upstream: https://github.com/zai-org/SCAIL-Pose (render_3d/taichi_cylinder.py)++Notes for WanGP integration:+- Initialization is done lazily to avoid import-time side effects.+- If there are no cylinder specs at all, we return black frames instead of crashing.+"""++from __future__ import annotations++import numpy as np++# Lazy import to avoid printing version message at app startup+ti = None+_TAICHI_INITIALIZED = False+++def _ensure_taichi_init() -> None:+ global ti, _TAICHI_INITIALIZED+ if _TAICHI_INITIALIZED:+ return+ import taichi as _ti+ ti = _ti+ try:+ ti.init(arch=ti.cuda, log_level=ti.ERROR)+ except Exception as exc: # pragma: no cover+ # Allow re-import/re-init patterns; keep GPU-only otherwise.+ msg = str(exc).lower()+ if "already" in msg and "init" in msg:+ _TAICHI_INITIALIZED = True+ return+ raise+ _TAICHI_INITIALIZED = True+++def flatten_specs(specs_list):+ """Flatten `specs_list` into numpy arrays + frame offsets/counts."""+ starts, ends, colors = [], [], []+ frame_offset, frame_count = [], []+ offset = 0+ for specs in specs_list:+ frame_offset.append(offset)+ frame_count.append(len(specs))+ for (start, end, color) in specs:+ starts.append(start)+ ends.append(end)+ colors.append(color)+ offset += len(specs)++ starts_np = np.asarray(starts, dtype=np.float32).reshape(-1, 3)+ ends_np = np.asarray(ends, dtype=np.float32).reshape(-1, 3)+ colors_np = np.asarray(colors, dtype=np.float32).reshape(-1, 4)+ frame_offset_np = np.asarray(frame_offset, dtype=np.int32)+ frame_count_np = np.asarray(frame_count, dtype=np.int32)+ return starts_np, ends_np, colors_np, frame_offset_np, frame_count_np+++def render_whole(specs_list, H=480, W=640, fx=500, fy=500, cx=240, cy=320, radius=21.5):+ _ensure_taichi_init()++ if len(specs_list) == 0:+ return []++ img = ti.Vector.field(4, dtype=ti.f32, shape=(H, W))+ starts, ends, colors, frame_offset, frame_count = flatten_specs(specs_list)+ total_cyl = int(starts.shape[0])+ n_frames = len(specs_list)++ if total_cyl == 0:+ return [np.zeros((H, W, 4), dtype=np.uint8) for _ in range(n_frames)]++ z_min = float(min(starts[:, 2].min(), ends[:, 2].min()))+ z_max = float(max(starts[:, 2].max(), ends[:, 2].max()))++ # ========= camera =========+ znear = 0.1+ zfar = max(min(z_max, 25000), 10000)+ C = ti.Vector([0.0, 0.0, 0.0])+ light_dir = ti.Vector([0.0, 0.0, 1.0])++ c_start = ti.Vector.field(3, dtype=ti.f32, shape=total_cyl)+ c_end = ti.Vector.field(3, dtype=ti.f32, shape=total_cyl)+ c_rgba = ti.Vector.field(4, dtype=ti.f32, shape=total_cyl)+ f_offset = ti.field(dtype=ti.i32, shape=n_frames)+ f_count = ti.field(dtype=ti.i32, shape=n_frames)+ frame_id = ti.field(dtype=ti.i32, shape=())+ z_min_field = ti.field(dtype=ti.f32, shape=())+ z_max_field = ti.field(dtype=ti.f32, shape=())++ z_min_field[None] = z_min+ z_max_field[None] = z_max++ c_start.from_numpy(starts)+ c_end.from_numpy(ends)+ c_rgba.from_numpy(colors)+ f_offset.from_numpy(frame_offset)+ f_count.from_numpy(frame_count)++ @ti.func+ def sd_cylinder(p, a, b, r):+ pa = p - a+ ba = b - a+ h = ba.norm()+ eps = 1e-8+ res = 0.0+ if h < eps:+ res = pa.norm() - r+ else:+ ba_n = ba / h+ proj = pa.dot(ba_n)+ proj_clamped = min(max(proj, 0.0), h)+ res = (pa - proj_clamped * ba_n).norm() - r+ return res++ @ti.func+ def scene_sdf(p):+ best_d = 1e6+ best_col = ti.Vector([0.0, 0.0, 0.0, 0.0])+ fid = frame_id[None]+ off = f_offset[fid]+ cnt = f_count[fid]+ for i in range(cnt):+ a = c_start[off + i]+ b = c_end[off + i]+ col = c_rgba[off + i]+ d = sd_cylinder(p, a, b, radius)+ if d < best_d:+ best_d = d+ best_col = col+ return best_d, best_col++ @ti.func+ def get_normal(p):+ e = 1e-3+ dx = scene_sdf(p + ti.Vector([e, 0.0, 0.0]))[0] - scene_sdf(p - ti.Vector([e, 0.0, 0.0]))[0]+ dy = scene_sdf(p + ti.Vector([0.0, e, 0.0]))[0] - scene_sdf(p - ti.Vector([0.0, e, 0.0]))[0]+ dz = scene_sdf(p + ti.Vector([0.0, 0.0, e]))[0] - scene_sdf(p - ti.Vector([0.0, 0.0, e]))[0]+ n = ti.Vector([dx, dy, dz])+ return n.normalized()++ @ti.func+ def pixel_to_ray(xi, yi):+ u = (xi - cx) / fx+ v = (yi - cy) / fy+ dir_cam = ti.Vector([u, v, 1.0]).normalized()+ Rcw = ti.Matrix.identity(ti.f32, 3)+ rd_world = Rcw @ dir_cam+ ro_world = C+ return ro_world, rd_world++ @ti.kernel+ def render():+ depth_near = ti.max(z_min_field[None], 0.1)+ depth_far = ti.min(z_max_field[None] + 6000, 20000)+ for y, x in img:+ ro, rd = pixel_to_ray(x, y)+ t = znear+ col_out = ti.Vector([0.0, 0.0, 0.0, 0.0])+ for _ in range(300):+ p = ro + rd * t+ d, col = scene_sdf(p)+ if d < 1e-3:+ n = get_normal(p)+ diff = max(n.dot(-light_dir), 0.0)++ view_dir = -rd.normalized()+ half_dir = (view_dir + -light_dir).normalized()+ spec = max(n.dot(half_dir), 0.0) ** 32++ depth_factor = 1.0 - (p.z - depth_near) / (depth_far - znear)+ depth_factor = ti.max(0.0, ti.min(1.0, depth_factor))++ diffuse_term = 0.3 + 0.7 * diff+ base = col.xyz * diffuse_term * depth_factor+ highlight = ti.Vector([1.0, 1.0, 1.0]) * (0.5 * spec) * depth_factor++ col_out = ti.Vector(+ [base.x + highlight.x, base.y + highlight.y, base.z + highlight.z, col.w]+ )+ break++ if t > zfar:+ break+ t += max(d, 1e-4)+ img[y, x] = col_out++ frames_np_rgba = []+ for f in range(n_frames):+ frame_id[None] = f+ render()+ arr = np.clip(img.to_numpy(), 0, 1)+ arr8 = (arr * 255).astype(np.uint8)+ frames_np_rgba.append(arr8)++ return frames_np_rgba+diff --git a/models/wan/wan_handler.py b/models/wan/wan_handler.pyindex 0e9f955..ff78a81 100644--- a/models/wan/wan_handler.py+++ b/models/wan/wan_handler.py@@ -1,5 +1,6 @@import os+import reimport torchimport numpy as npimport gradio as gr@@ -10,14 +11,14 @@ from shared.utils import files_locator as fldef test_vace(base_model_type):return base_model_type in ["vace_14B", "vace_14B_2_2", "vace_1.3B", "vace_multitalk_14B", "vace_standin_14B", "vace_lynx_14B", "vace_ditto_14B"]-def test_class_i2v(base_model_type):- return base_model_type in ["i2v", "i2v_2_2", "fun_inp_1.3B", "fun_inp", "flf2v_720p", "fantasy", "multitalk", "infinitetalk", "i2v_2_2_multitalk", "animate", "chrono_edit", "steadydancer", "wanmove" ]+def test_class_i2v(base_model_type):+ return base_model_type in ["i2v", "i2v_2_2", "fun_inp_1.3B", "fun_inp", "flf2v_720p", "fantasy", "multitalk", "infinitetalk", "i2v_2_2_multitalk", "animate", "chrono_edit", "steadydancer", "wanmove", "scail" ]def test_class_t2v(base_model_type):return base_model_type in ["t2v", "t2v_2_2", "alpha", "lynx"]def test_oneframe_overlap(base_model_type):- return test_class_i2v(base_model_type) and not (test_multitalk(base_model_type) or base_model_type in ["animate"]) or test_wan_5B(base_model_type)+ return test_class_i2v(base_model_type) and not (test_multitalk(base_model_type) or base_model_type in ["animate", "scail"]) or test_wan_5B(base_model_type)def test_class_1_3B(base_model_type):return base_model_type in [ "vace_1.3B", "t2v_1.3B", "recam_1.3B","phantom_1.3B","fun_inp_1.3B"]@@ -41,9 +42,9 @@ class family_handler():@staticmethoddef query_supported_types():return ["multitalk", "infinitetalk", "fantasy", "vace_14B", "vace_14B_2_2", "vace_multitalk_14B", "vace_standin_14B", "vace_lynx_14B",- "t2v_1.3B", "standin", "lynx_lite", "lynx", "t2v", "t2v_2_2", "vace_1.3B", "vace_ditto_14B", "phantom_1.3B", "phantom_14B",+ "t2v_1.3B", "standin", "lynx_lite", "lynx", "t2v", "t2v_2_2", "vace_1.3B", "vace_ditto_14B", "phantom_1.3B", "phantom_14B","recam_1.3B", "animate", "alpha", "alpha_lynx", "chrono_edit",- "i2v", "i2v_2_2", "i2v_2_2_multitalk", "ti2v_2_2", "lucy_edit", "flf2v_720p", "fun_inp_1.3B", "fun_inp", "mocha", "steadydancer", "wanmove"]+ "i2v", "i2v_2_2", "i2v_2_2_multitalk", "ti2v_2_2", "lucy_edit", "flf2v_720p", "fun_inp_1.3B", "fun_inp", "mocha", "steadydancer", "wanmove", "scail"]@staticmethod@@ -318,12 +319,49 @@ class family_handler():"scale": 3,"show_label" : False,}- extra_model_def["custom_preprocessor"] = "Extracting Pose Information"+ extra_model_def["custom_preprocessor"] = "Extracting Pose Information"extra_model_def["alt_guidance"] = "Condition Guidance"extra_model_def["no_guide2_refresh"] = Trueextra_model_def["no_mask_refresh"] = Trueextra_model_def["control_video_trim"] = True-++ if base_model_type in ["scail"]:+ extra_model_def["guide_custom_choices"] = {+ "choices": [+ ("Animate One Person", "V#1#"),+ ("Animate Two Persons", "V#2#"),+ ("Animate Three Persons", "V#3#"),+ ("Animate Four Persons", "V#4#"),+ ("Animate Five Persons", "V#5#"),+ ],+ "default": "V#1#",+ "letters_filter": "V#12345",+ "label": "Type of Process",+ "scale": 3,+ "show_label": True,+ }++ extra_model_def["preprocess_all"] = True+ extra_model_def["custom_preprocessor"] = "Extracting 3D Pose (NLFPose)"+ extra_model_def["forced_guide_mask_inputs"] = True+ extra_model_def["keep_frames_video_guide_not_supported"] = True+ extra_model_def["mask_preprocessing"] = {+ "selection": ["", "A", "NA"],+ "visible": True,+ "label": "Persons Locations"+ }+ extra_model_def["control_video_trim"] = True+ extra_model_def["extract_guide_from_window_start"] = True++ extra_model_def["return_image_refs_tensor"] = True+ # extra_model_def["image_ref_choices"] = {+ # "choices": [+ # ("No Reference Image", ""),+ # ("Reference Image of People", "I"),+ # ],+ # "visible": True,+ # "letters_filter":"I",+ # }if base_model_type in ["infinitetalk"]:extra_model_def["no_background_removal"] = True@@ -558,7 +596,7 @@ class family_handler():image_prompt_types_allowed = "TSVL"elif base_model_type in ["lucy_edit"]:image_prompt_types_allowed = "TVL"- elif multitalk or base_model_type in ["fantasy", "steadydancer"]:+ elif multitalk or base_model_type in ["fantasy", "steadydancer", "scail"]:image_prompt_types_allowed = "SVL"elif i2v:image_prompt_types_allowed = "SEVL"@@ -594,7 +632,7 @@ class family_handler():@staticmethoddef get_vae_block_size(base_model_type):- return 32 if test_wan_5B(base_model_type) else 16+ return 32 if test_wan_5B(base_model_type) or base_model_type in ["scail"] else 16@staticmethoddef get_rgb_factors(base_model_type ):@@ -617,6 +655,16 @@ class family_handler():"fileList" : [ [ "models_clip_open-clip-xlm-roberta-large-vit-huge-14-bf16.safetensors", "sentencepiece.bpe.model", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json"], ["special_tokens_map.json", "spiece.model", "tokenizer.json", "tokenizer_config.json"] + computeList(text_encoder_filename) , wan_files + computeList(model_filename) ]}]+ if base_model_type == "scail":+ # SCAIL pose extraction (NLFPose torchscript). Kept separate so it isn't downloaded for every model.+ download_def += [+ {+ "repoId": "DeepBeepMeep/Wan2.1",+ "sourceFolderList": ["pose"],+ "fileList": [["nlf_l_multi_0.3.2.eager.safetensors", "nlf_l_multi_0.3.2.eager.meta.json"]],+ }+ ]+if test_wan_5B(base_model_type):download_def += [ {"repoId" : "DeepBeepMeep/Wan2.2",@@ -627,23 +675,43 @@ class family_handler():return download_def@staticmethod- def custom_preprocess(base_model_type, video_guide, video_mask, pre_video_guide=None, max_workers = 1, expand_scale = 0, **kwargs):- from .steadydancer.pose_align import PoseAligner+ def custom_preprocess(base_model_type, video_guide, video_mask, pre_video_guide=None, max_workers = 1, expand_scale = 0, video_prompt_type = None, **kwargs):from shared.utils.utils import convert_tensor_to_imageref_image = convert_tensor_to_image(pre_video_guide[:, 0])frames = video_guidemask_frames = None if video_mask is None else video_mask- aligner = PoseAligner()- outputs = aligner.align( frames, ref_image, ref_video_mask=mask_frames, align_frame=0, max_frames=None, augment=True, include_composite= False, cpu_resize_workers= max_workers, expand_scale = expand_scale )-- video_guide_processed, video_guide_processed2 = outputs["pose_only"], outputs["pose_aug"]- if video_guide_processed.numel() == 0: return None, None, None+ if base_model_type == "scail":+ extract_max_people = lambda s: int(m.group(1)) if (m := re.search(r'#(\d+)#', s)) else 1++ # ref_image = ref_image.resize( (ref_image.width // 2, ref_image.height // 2), resample=Image.LANCZOS )+ from .scail import ScailPoseProcessor+ scail_max_people = extract_max_people(video_prompt_type)+ scail_multi_person = scail_max_people > 1+ processor = ScailPoseProcessor(multi_person=scail_multi_person, max_people=scail_max_people)+ video_guide_processed = processor.extract_and_render(+ frames,+ ref_image=ref_image,+ mask_frames=mask_frames,+ align_pose=True+ )+ if video_guide_processed.numel() == 0:+ gr.Info("Unable to detect a Person")+ return None, None, None, None+ # SCAIL doesn't use augmented poses+ return video_guide_processed, None, video_mask, None+ else:+ # Steadydancer/wanmove: Use 2D pose alignment+ from .steadydancer.pose_align import PoseAligner+ aligner = PoseAligner()+ outputs = aligner.align(frames, ref_image, ref_video_mask=mask_frames, align_frame=0, max_frames=None, augment=True, include_composite=False, cpu_resize_workers=max_workers, expand_scale=expand_scale)- video_mask_processed = video_mask_processed2 = None+ video_guide_processed, video_guide_processed2 = outputs["pose_only"], outputs["pose_aug"]+ if video_guide_processed.numel() == 0:+ return None, None, None, None- return video_guide_processed, video_guide_processed2, video_mask_processed, video_mask_processed2+ return video_guide_processed, video_guide_processed2, video_mask_processed, video_mask_processed2@staticmethod@@ -854,14 +922,22 @@ class family_handler():"force_fps": "control",})elif base_model_type in ["steadydancer"]:- ui_defaults.update({- "video_prompt_type": "VA",- "image_prompt_type": "S",+ ui_defaults.update({+ "video_prompt_type": "VA",+ "image_prompt_type": "S","audio_prompt_type": "R",- "force_fps": "control",+ "force_fps": "control","alt_guidance_scale" : 2.0,})-+ elif base_model_type in ["scail"]:+ ui_defaults.update({+ "video_prompt_type": "V#1#",+ "image_prompt_type": "S",+ "audio_prompt_type": "R",+ "force_fps": "control",+ "sliding_window_overlap" : 1,+ "sliding_window_size": 81,+ })if base_model_type in ["i2v_2_2"]:ui_defaults.update({"masking_strength": 0.1, "denoising_strength": 0.9})diff --git a/preprocessing/matanyone/app.py b/preprocessing/matanyone/app.pyindex 4007bf8..adcf26a 100644--- a/preprocessing/matanyone/app.py+++ b/preprocessing/matanyone/app.py@@ -17,7 +17,7 @@ from .tools.painter import mask_painterfrom .tools.interact_tools import SamControlerfrom .tools.misc import get_devicefrom .tools.download_util import load_file_from_url-from segment_anything.modeling.image_encoder import window_partition, window_unpartition, get_rel_pos, Block as image_encoder_block+from .tools.base_segmenter import set_image_encoder_patchfrom .utils.get_default_model import get_matanyone_modelfrom .matanyone.inference.inference_core import InferenceCorefrom .matanyone_wrapper import matanyone@@ -282,97 +282,6 @@ def get_end_number(track_pause_number_slider, video_state, interactive_state):return video_state["painted_images"][track_pause_number_slider],interactive_state-def patched_forward(self, x: torch.Tensor) -> torch.Tensor:- def split_mlp(mlp, x, divide = 4):- x_shape = x.shape- x = x.view(-1, x.shape[-1])- chunk_size = int(x.shape[0]/divide)- x_chunks = torch.split(x, chunk_size)- for i, x_chunk in enumerate(x_chunks):- mlp_chunk = mlp.lin1(x_chunk)- mlp_chunk = mlp.act(mlp_chunk)- x_chunk[...] = mlp.lin2(mlp_chunk)- return x.reshape(x_shape)-- def get_decomposed_rel_pos( q, rel_pos_h, rel_pos_w, q_size, k_size) -> torch.Tensor:- q_h, q_w = q_size- k_h, k_w = k_size- Rh = get_rel_pos(q_h, k_h, rel_pos_h)- Rw = get_rel_pos(q_w, k_w, rel_pos_w)- B, _, dim = q.shape- r_q = q.reshape(B, q_h, q_w, dim)- rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh)- rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw)- attn = torch.zeros(B, q_h, q_w, k_h, k_w, dtype=q.dtype, device=q.device)- attn += rel_h[:, :, :, :, None]- attn += rel_w[:, :, :, None, :]- return attn.view(B, q_h * q_w, k_h * k_w)-- def pay_attention(self, x: torch.Tensor, split_heads = 1) -> torch.Tensor:- B, H, W, _ = x.shape- # qkv with shape (3, B, nHead, H * W, C)- qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)-- if not bfloat16_supported: qkv = qkv.to(torch.float16)-- # q, k, v with shape (B * nHead, H * W, C)- q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)- if split_heads == 1:- attn_mask = None- if self.use_rel_pos:- attn_mask = get_decomposed_rel_pos(q, self.rel_pos_h.to(q), self.rel_pos_w.to(q), (H, W), (H, W))- x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, scale=self.scale)- else:- chunk_size = self.num_heads // split_heads- x = torch.empty_like(q)- q_chunks = torch.split(q, chunk_size)- k_chunks = torch.split(k, chunk_size)- v_chunks = torch.split(v, chunk_size)- x_chunks = torch.split(x, chunk_size)- for x_chunk, q_chunk, k_chunk, v_chunk in zip(x_chunks, q_chunks, k_chunks, v_chunks):- attn_mask = None- if self.use_rel_pos:- attn_mask = get_decomposed_rel_pos(q_chunk, self.rel_pos_h.to(q), self.rel_pos_w.to(q), (H, W), (H, W))- x_chunk[...] = F.scaled_dot_product_attention(q_chunk, k_chunk, v_chunk, attn_mask=attn_mask, scale=self.scale)- del x_chunk, q_chunk, k_chunk, v_chunk- del q, k, v, attn_mask- x = x.view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1)- if not bfloat16_supported: x = x.to(torch.bfloat16)-- return self.proj(x)-- shortcut = x- x = self.norm1(x)- # Window partition- if self.window_size > 0:- H, W = x.shape[1], x.shape[2]- x, pad_hw = window_partition(x, self.window_size)- x_shape = x.shape-- if x_shape[0] > 10:- chunk_size = int(x.shape[0]/4) + 1- x_chunks = torch.split(x, chunk_size)- for i, x_chunk in enumerate(x_chunks):- x_chunk[...] = pay_attention(self.attn,x_chunk)- else:- x = pay_attention(self.attn,x, 4)--- # Reverse window partition- if self.window_size > 0:- x = window_unpartition(x, self.window_size, pad_hw, (H, W))- x += shortcut- shortcut[...] = self.norm2(x)- # x += self.mlp(shortcut)- x += split_mlp(self.mlp, shortcut)-- return x--def set_image_encoder_patch():- if not hasattr(image_encoder_block, "patched"): #and False- image_encoder_block.forward = patched_forward- image_encoder_block.patched = True-# use sam to get the maskdef sam_refine(state, video_state, point_prompt, click_state, interactive_state, evt:gr.SelectData ): #"""diff --git a/preprocessing/matanyone/tools/base_segmenter.py b/preprocessing/matanyone/tools/base_segmenter.pyindex 64f702d..09fa309 100644--- a/preprocessing/matanyone/tools/base_segmenter.py+++ b/preprocessing/matanyone/tools/base_segmenter.py@@ -1,14 +1,117 @@import timeimport torch+import torch.nn.functional as Fimport cv2from PIL import Image, ImageDraw, ImageOpsimport numpy as npfrom typing import Unionfrom segment_anything import sam_model_registry, SamPredictor, SamAutomaticMaskGenerator+from segment_anything.modeling.image_encoder import window_partition, window_unpartition, get_rel_pos, Block as image_encoder_blockimport matplotlib.pyplot as pltimport PILfrom .mask_painter import mask_painter-from shared.utils import files_locator as fl+from shared.utils import files_locator as fl++# Detect bfloat16 support once at module load+_bfloat16_supported = torch.cuda.is_bf16_supported() if torch.cuda.is_available() else False+++def _patched_forward(self, x: torch.Tensor) -> torch.Tensor:+ """VRAM-optimized forward pass for SAM image encoder blocks.++ Optimizations made by DeepBeepMeep+ """+ def split_mlp(mlp, x, divide=4):+ x_shape = x.shape+ x = x.view(-1, x.shape[-1])+ chunk_size = int(x.shape[0] / divide)+ x_chunks = torch.split(x, chunk_size)+ for i, x_chunk in enumerate(x_chunks):+ mlp_chunk = mlp.lin1(x_chunk)+ mlp_chunk = mlp.act(mlp_chunk)+ x_chunk[...] = mlp.lin2(mlp_chunk)+ return x.reshape(x_shape)++ def get_decomposed_rel_pos(q, rel_pos_h, rel_pos_w, q_size, k_size) -> torch.Tensor:+ q_h, q_w = q_size+ k_h, k_w = k_size+ Rh = get_rel_pos(q_h, k_h, rel_pos_h)+ Rw = get_rel_pos(q_w, k_w, rel_pos_w)+ B, _, dim = q.shape+ r_q = q.reshape(B, q_h, q_w, dim)+ rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh)+ rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw)+ attn = torch.zeros(B, q_h, q_w, k_h, k_w, dtype=q.dtype, device=q.device)+ attn += rel_h[:, :, :, :, None]+ attn += rel_w[:, :, :, None, :]+ return attn.view(B, q_h * q_w, k_h * k_w)++ def pay_attention(self, x: torch.Tensor, split_heads=1) -> torch.Tensor:+ B, H, W, _ = x.shape+ # qkv with shape (3, B, nHead, H * W, C)+ qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)++ if not _bfloat16_supported:+ qkv = qkv.to(torch.float16)++ # q, k, v with shape (B * nHead, H * W, C)+ q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)+ if split_heads == 1:+ attn_mask = None+ if self.use_rel_pos:+ attn_mask = get_decomposed_rel_pos(q, self.rel_pos_h.to(q), self.rel_pos_w.to(q), (H, W), (H, W))+ x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, scale=self.scale)+ else:+ chunk_size = self.num_heads // split_heads+ x = torch.empty_like(q)+ q_chunks = torch.split(q, chunk_size)+ k_chunks = torch.split(k, chunk_size)+ v_chunks = torch.split(v, chunk_size)+ x_chunks = torch.split(x, chunk_size)+ for x_chunk, q_chunk, k_chunk, v_chunk in zip(x_chunks, q_chunks, k_chunks, v_chunks):+ attn_mask = None+ if self.use_rel_pos:+ attn_mask = get_decomposed_rel_pos(q_chunk, self.rel_pos_h.to(q), self.rel_pos_w.to(q), (H, W), (H, W))+ x_chunk[...] = F.scaled_dot_product_attention(q_chunk, k_chunk, v_chunk, attn_mask=attn_mask, scale=self.scale)+ del x_chunk, q_chunk, k_chunk, v_chunk+ del q, k, v, attn_mask+ x = x.view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1)+ if not _bfloat16_supported:+ x = x.to(torch.bfloat16)++ return self.proj(x)++ shortcut = x+ x = self.norm1(x)+ # Window partition+ if self.window_size > 0:+ H, W = x.shape[1], x.shape[2]+ x, pad_hw = window_partition(x, self.window_size)+ x_shape = x.shape++ if x_shape[0] > 10:+ chunk_size = int(x.shape[0] / 4) + 1+ x_chunks = torch.split(x, chunk_size)+ for i, x_chunk in enumerate(x_chunks):+ x_chunk[...] = pay_attention(self.attn, x_chunk)+ else:+ x = pay_attention(self.attn, x, 4)++ # Reverse window partition+ if self.window_size > 0:+ x = window_unpartition(x, self.window_size, pad_hw, (H, W))+ x += shortcut+ shortcut[...] = self.norm2(x)+ x += split_mlp(self.mlp, shortcut)++ return x+++def set_image_encoder_patch():+ """Apply VRAM optimizations to SAM image encoder blocks."""+ if not hasattr(image_encoder_block, "patched"):+ image_encoder_block.forward = _patched_forward+ image_encoder_block.patched = Trueclass BaseSegmenter:@@ -21,6 +124,9 @@ class BaseSegmenter:print(f"Initializing BaseSegmenter to {device}")assert model_type in ['vit_b', 'vit_l', 'vit_h'], 'model_type must be vit_b, vit_l, or vit_h'+ # Apply VRAM optimizations before loading model+ set_image_encoder_patch()+self.device = device# SAM_checkpoint = Noneself.torch_dtype = torch.float16 if 'cuda' in device else torch.float32diff --git a/profiles/wan_2_2/Lightning t2v v2025-12-17 2 Phases - 4 Steps.json b/profiles/wan_2_2/Lightning t2v v2025-12-17 2 Phases - 4 Steps.jsonnew file mode 100644index 0000000..4463c2b--- /dev/null+++ b/profiles/wan_2_2/Lightning t2v v2025-12-17 2 Phases - 4 Steps.json@@ -0,0 +1,14 @@+{+ "num_inference_steps": 4,+ "guidance_scale": 1,+ "guidance2_scale": 1,+ "switch_threshold": 876,+ "model_switch_phase": 1,+ "guidance_phases": 2,+ "flow_shift": 3,+ "loras_multipliers": "1;0 0;1",+ "activated_loras": [+ "https://huggingface.co/DeepBeepMeep/Wan2.2/resolve/main/loras_accelerators/wan2.2_t2v_A14b_high_noise_lora_rank64_lightx2v_4step_1217.safetensors",+ "https://huggingface.co/DeepBeepMeep/Wan2.2/resolve/main/loras_accelerators/wan2.2_t2v_A14b_low_noise_lora_rank64_lightx2v_4step_1217.safetensors"+ ]+}\ No newline at end of filediff --git a/profiles/wan_2_2/Lightning t2v v2025-12-17 3 Phases - 8 Steps.json b/profiles/wan_2_2/Lightning t2v v2025-12-17 3 Phases - 8 Steps.jsonnew file mode 100644index 0000000..d686f36--- /dev/null+++ b/profiles/wan_2_2/Lightning t2v v2025-12-17 3 Phases - 8 Steps.json@@ -0,0 +1,18 @@+{+ "num_inference_steps": 8,+ "guidance_scale": 3.5,+ "guidance2_scale": 1,+ "guidance3_scale": 1,+ "switch_threshold": 965,+ "switch_threshold2": 800,+ "guidance_phases": 3,+ "model_switch_phase": 2,+ "flow_shift": 3,+ "sample_solver": "euler",+ "activated_loras": [+ "https://huggingface.co/DeepBeepMeep/Wan2.2/resolve/main/loras_accelerators/wan2.2_t2v_A14b_high_noise_lora_rank64_lightx2v_4step_1217.safetensors",+ "https://huggingface.co/DeepBeepMeep/Wan2.2/resolve/main/loras_accelerators/wan2.2_t2v_A14b_low_noise_lora_rank64_lightx2v_4step_1217.safetensors"+ ],+} "loras_multipliers": "0;1;0 0;0;1",+ "help": "This finetune uses the Lightning 250928 4 steps Loras Accelerator for Wan 2.2 but extend them to 8 steps in order to insert a CFG phase before the 2 accelerated phases with no Guidance. The ultimate goal is reduce the slow motion effect of these Loras Accelerators."+}\ No newline at end of filediff --git a/profiles/wan_i2v/Image2Video lightx2v - 4 Steps.json b/profiles/wan_i2v/Image2Video lightx2v - 4 Steps.jsonnew file mode 100644index 0000000..cdced60--- /dev/null+++ b/profiles/wan_i2v/Image2Video lightx2v - 4 Steps.json@@ -0,0 +1,12 @@+{++ "activated_loras": [+ "https://huggingface.co/DeepBeepMeep/Wan2.1/resolve/main/loras_accelerators/Wan21_I2V_14B_lightx2v_cfg_step_distill_lora_rank64.safetensors"+ ],+ "loras_multipliers": "1",+ "num_inference_steps": 4,+ "guidance_phases": 1,+ "guidance_scale": 1,+ "alt_guidance_scale": 1,+ "audio_guidance_scale": 1+}diff --git a/requirements.txt b/requirements.txtindex e755bef..2dc5e06 100644--- a/requirements.txt+++ b/requirements.txt@@ -43,6 +43,7 @@ timminsightface @ https://github.com/deepbeepmeep/insightface/raw/refs/heads/master/wheels/insightface-0.7.3-cp310-cp310-win_amd64.whl ; sys_platform == "win32" and python_version == "3.10"insightface==0.7.3 ; sys_platform == "linux"facexlib==0.3.0+taichi# Config & orchestrationomegaconfdiff --git a/wgp.py b/wgp.pyindex 02d8e66..44f2cc2 100644--- a/wgp.py+++ b/wgp.py@@ -83,7 +83,7 @@ global_queue_ref = []AUTOSAVE_FILENAME = "queue.zip"PROMPT_VARS_MAX = 10target_mmgp_version = "3.6.9"-WanGP_version = "9.86"+WanGP_version = "9.9"settings_version = 2.41max_source_video_frames = 3000prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None@@ -2995,8 +2995,8 @@ def setup_loras(model_type, transformer, lora_dir, lora_preselected_preset, spldefault_lora_preset_prompt = ""from pathlib import Path-- lora_dir = get_lora_dir(model_type)+ base_model_type = get_base_model_type(model_type)+ lora_dir = get_lora_dir(base_model_type)if lora_dir != None :if not os.path.isdir(lora_dir):raise Exception("--lora-dir should be a path to a directory that contains Loras")@@ -3015,7 +3015,7 @@ def setup_loras(model_type, transformer, lora_dir, lora_preselected_preset, splloras_presets = [ Path(file_path).parts[-1] for file_path in dir_presets_settings + dir_presets]if transformer !=None:- loras = offload.load_loras_into_model(transformer, loras, activate_all_loras=False, check_only= True, preprocess_sd=get_loras_preprocessor(transformer, model_type), split_linear_modules_map = split_linear_modules_map) #lora_multiplier,+ loras = offload.load_loras_into_model(transformer, loras, activate_all_loras=False, check_only= True, preprocess_sd=get_loras_preprocessor(transformer, base_model_type), split_linear_modules_map = split_linear_modules_map) #lora_multiplier,if len(loras) > 0:loras = [ os.path.basename(lora) for lora in loras ]@@ -3024,7 +3024,7 @@ def setup_loras(model_type, transformer, lora_dir, lora_preselected_preset, splif not os.path.isfile(os.path.join(lora_dir, lora_preselected_preset + ".lset")):raise Exception(f"Unknown preset '{lora_preselected_preset}'")default_lora_preset = lora_preselected_preset- default_loras_choices, default_loras_multis_str, default_lora_preset_prompt, _ , error = extract_preset(model_type, default_lora_preset, loras)+ default_loras_choices, default_loras_multis_str, default_lora_preset_prompt, _ , error = extract_preset(base_model_type, default_lora_preset, loras)if len(error) > 0:print(error[:200])return loras, loras_presets, default_loras_choices, default_loras_multis_str, default_lora_preset_prompt, default_lora_preset@@ -3458,7 +3458,7 @@ def refresh_gallery(state): #, msgmulti_prompts_gen_type = params["multi_prompts_gen_type"]base_model_type = get_base_model_type(model_type)model_def = get_model_def(model_type)- onemorewindow_visible = test_any_sliding_window(base_model_type) and params.get("image_mode",0) == 0 and not params.get("mode","").startswith("edit_")+ onemorewindow_visible = test_any_sliding_window(base_model_type) and params.get("image_mode",0) == 0 and (not params.get("mode","").startswith("edit_")) and not model_def.get("preprocess_all", False)enhanced = Falseif prompt.startswith("!enhanced!\n"):enhanced = True@@ -4863,7 +4863,7 @@ def truncate_audio(generated_audio, trim_video_frames_beginning, trim_video_framend = len(generated_audio) - int(trim_video_frames_end * samples_per_frame)return generated_audio[start:end if end > 0 else None]-def custom_preprocess_video_with_mask(model_handler, base_model_type, pre_video_guide, video_guide, video_mask, height, width, max_frames, start_frame, fit_canvas, fit_crop, target_fps, block_size, expand_scale):+def custom_preprocess_video_with_mask(model_handler, base_model_type, pre_video_guide, video_guide, video_mask, height, width, max_frames, start_frame, fit_canvas, fit_crop, target_fps, block_size, expand_scale, video_prompt_type):pad_frames = 0if start_frame < 0:pad_frames= -start_frame@@ -4881,10 +4881,31 @@ def custom_preprocess_video_with_mask(model_handler, base_model_type, pre_video_video_mask = get_resampled_video(video_mask, start_frame, max_frames, target_fps).permute(-1, 0, 1, 2)video_mask = video_mask[:1] / 255.+ # Mask filtering: resize, binarize, expand mask and keep only masked areas of video guide+ if any_mask:+ invert_mask = "N" in video_prompt_type+ import concurrent.futures+ tgt_h, tgt_w = video_guide.shape[2], video_guide.shape[3]+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (abs(expand_scale), abs(expand_scale))) if expand_scale != 0 else None+ op = (cv2.dilate if expand_scale > 0 else cv2.erode) if expand_scale != 0 else None+ def process_mask(idx):+ m = (video_mask[0, idx].numpy() * 255).astype(np.uint8)+ if m.shape[0] != tgt_h or m.shape[1] != tgt_w:+ m = cv2.resize(m, (tgt_w, tgt_h), interpolation=cv2.INTER_NEAREST)+ _, m = cv2.threshold(m, 127, 255, cv2.THRESH_BINARY) # binarize grey values+ if op: m = op(m, kernel, iterations=3)+ if invert_mask:+ return torch.from_numpy((m <= 127).astype(np.float32))+ else:+ return torch.from_numpy((m > 127).astype(np.float32))+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as ex:+ video_mask = torch.stack([f.result() for f in [ex.submit(process_mask, i) for i in range(video_mask.shape[1])]]).unsqueeze(0)+ video_guide = video_guide * video_mask + (-1) * (1-video_mask)+if video_guide.shape[1] == 0 or any_mask and video_mask.shape[1] == 0:return None, None, None, None- video_guide_processed, video_guide_processed2, video_mask_processed, video_mask_processed2 = model_handler.custom_preprocess(base_model_type = base_model_type, pre_video_guide = pre_video_guide, video_guide = video_guide, video_mask = video_mask, height = height, width = width, fit_canvas = fit_canvas , fit_crop = fit_crop, target_fps = target_fps, block_size = block_size, max_workers = max_workers, expand_scale = expand_scale)+ video_guide_processed, video_guide_processed2, video_mask_processed, video_mask_processed2 = model_handler.custom_preprocess(base_model_type = base_model_type, pre_video_guide = pre_video_guide, video_guide = video_guide, video_mask = video_mask, height = height, width = width, fit_canvas = fit_canvas , fit_crop = fit_crop, target_fps = target_fps, block_size = block_size, max_workers = max_workers, expand_scale = expand_scale, video_prompt_type=video_prompt_type)# if pad_frames > 0:# masked_frames = masked_frames[0] * pad_frames + masked_frames@@ -5353,6 +5374,8 @@ def generate_video(gen["window_no"] = 1num_frames_generated = 0 # num of new frames created (lower than the number of frames really processed due to overlaps and discards)requested_frames_to_generate = default_requested_frames_to_generate # num of num frames to create (if any source window this num includes also the overlapped source window frames)+ cached_video_guide_processed = cached_video_mask_processed = cached_video_guide_processed2 = cached_video_mask_processed2 = None+ cached_video_video_start_frame = cached_video_video_end_frame = -1start_time = time.time()if prompt_enhancer_image_caption_model != None and prompt_enhancer !=None and len(prompt_enhancer)>0 and server_config.get("enhancer_mode", 0) == 0:send_cmd("progress", [0, get_latest_status(state, "Enhancing Prompt")])@@ -5474,6 +5497,11 @@ def generate_video(keep_frames_parsed += keep_frames_parsed_full[max(0, guide_frames_extract_start): aligned_guide_end_frame ]guide_frames_extract_count = len(keep_frames_parsed)+ process_all = model_def.get("preprocess_all", False)+ if process_all:+ guide_slice_to_extract = guide_frames_extract_count+ guide_frames_extract_count = (-guide_frames_extract_start if guide_frames_extract_start <0 else 0) + len( keep_frames_parsed_full[max(0, guide_frames_extract_start):] )+# Extract Faces to videoif "B" in video_prompt_type:send_cmd("progress", [0, get_latest_status(state, "Extracting Face Movements")])@@ -5486,38 +5514,50 @@ def generate_video(if "R" in video_prompt_type:sparse_video_image = get_video_frame(video_guide, aligned_guide_start_frame, return_last_if_missing = True, target_fps = fps, return_PIL = True)- # Generic Video Preprocessing- process_outside_mask = process_map_outside_mask.get(filter_letters(video_prompt_type, "YWX"), None)- preprocess_type, preprocess_type2 = "raw", None- for process_num, process_letter in enumerate( filter_letters(video_prompt_type, video_guide_processes)):- if process_num == 0:- preprocess_type = process_map_video_guide.get(process_letter, "raw")+ if not process_all or cached_video_video_start_frame < 0:+ # Generic Video Preprocessing+ process_outside_mask = process_map_outside_mask.get(filter_letters(video_prompt_type, "YWX"), None)+ preprocess_type, preprocess_type2 = "raw", None+ for process_num, process_letter in enumerate( filter_letters(video_prompt_type, video_guide_processes)):+ if process_num == 0:+ preprocess_type = process_map_video_guide.get(process_letter, "raw")+ else:+ preprocess_type2 = process_map_video_guide.get(process_letter, None)+ custom_preprocessor = model_def.get("custom_preprocessor", None)+ if custom_preprocessor is not None:+ status_info = custom_preprocessor+ send_cmd("progress", [0, get_latest_status(state, status_info)])+ video_guide_processed, video_guide_processed2, video_mask_processed, video_mask_processed2 = custom_preprocess_video_with_mask(model_handler, base_model_type, pre_video_guide, video_guide if sparse_video_image is None else sparse_video_image, video_mask, height=image_size[0], width = image_size[1], max_frames= guide_frames_extract_count, start_frame = guide_frames_extract_start, fit_canvas = sample_fit_canvas, fit_crop = fit_crop, target_fps = fps, block_size = block_size, expand_scale = mask_expand, video_prompt_type= video_prompt_type)else:- preprocess_type2 = process_map_video_guide.get(process_letter, None)- custom_preprocessor = model_def.get("custom_preprocessor", None)- if custom_preprocessor is not None:- status_info = custom_preprocessor- send_cmd("progress", [0, get_latest_status(state, status_info)])- video_guide_processed, video_guide_processed2, video_mask_processed, video_mask_processed2 = custom_preprocess_video_with_mask(model_handler, base_model_type, pre_video_guide, video_guide if sparse_video_image is None else sparse_video_image, video_mask, height=image_size[0], width = image_size[1], max_frames= guide_frames_extract_count, start_frame = guide_frames_extract_start, fit_canvas = sample_fit_canvas, fit_crop = fit_crop, target_fps = fps, block_size = block_size, expand_scale = mask_expand)- else:- status_info = "Extracting " + processes_names[preprocess_type]- extra_process_list = ([] if preprocess_type2==None else [preprocess_type2]) + ([] if process_outside_mask==None or process_outside_mask == preprocess_type else [process_outside_mask])- if len(extra_process_list) == 1:- status_info += " and " + processes_names[extra_process_list[0]]- elif len(extra_process_list) == 2:- status_info += ", " + processes_names[extra_process_list[0]] + " and " + processes_names[extra_process_list[1]]- context_scale = [control_net_weight /2, control_net_weight2 /2] if preprocess_type2 is not None else [control_net_weight]-- if not (preprocess_type == "identity" and preprocess_type2 is None and video_mask is None):send_cmd("progress", [0, get_latest_status(state, status_info)])- inpaint_color = 0 if preprocess_type=="pose" and process_outside_mask == "inpaint" else guide_inpaint_color- video_guide_processed, video_mask_processed = preprocess_video_with_mask(video_guide if sparse_video_image is None else sparse_video_image, video_mask, height=image_size[0], width = image_size[1], max_frames= guide_frames_extract_count, start_frame = guide_frames_extract_start, fit_canvas = sample_fit_canvas, fit_crop = fit_crop, target_fps = fps, process_type = preprocess_type, expand_scale = mask_expand, RGB_Mask = True, negate_mask = "N" in video_prompt_type, process_outside_mask = process_outside_mask, outpainting_dims = outpainting_dims, proc_no =1, inpaint_color =inpaint_color, block_size = block_size, to_bbox = "H" in video_prompt_type )- if preprocess_type2 != None:- video_guide_processed2, video_mask_processed2 = preprocess_video_with_mask(video_guide, video_mask, height=image_size[0], width = image_size[1], max_frames= guide_frames_extract_count, start_frame = guide_frames_extract_start, fit_canvas = sample_fit_canvas, fit_crop = fit_crop, target_fps = fps, process_type = preprocess_type2, expand_scale = mask_expand, RGB_Mask = True, negate_mask = "N" in video_prompt_type, process_outside_mask = process_outside_mask, outpainting_dims = outpainting_dims, proc_no =2, block_size = block_size, to_bbox = "H" in video_prompt_type )-- if video_guide_processed is not None and sample_fit_canvas is not None:- image_size = video_guide_processed.shape[-2:]- sample_fit_canvas = None-+ status_info = "Extracting " + processes_names[preprocess_type]+ extra_process_list = ([] if preprocess_type2==None else [preprocess_type2]) + ([] if process_outside_mask==None or process_outside_mask == preprocess_type else [process_outside_mask])+ if len(extra_process_list) == 1:+ status_info += " and " + processes_names[extra_process_list[0]]+ elif len(extra_process_list) == 2:+ status_info += ", " + processes_names[extra_process_list[0]] + " and " + processes_names[extra_process_list[1]]+ context_scale = [control_net_weight /2, control_net_weight2 /2] if preprocess_type2 is not None else [control_net_weight]++ if not (preprocess_type == "identity" and preprocess_type2 is None and video_mask is None):send_cmd("progress", [0, get_latest_status(state, status_info)])+ inpaint_color = 0 if preprocess_type=="pose" and process_outside_mask == "inpaint" else guide_inpaint_color+ video_guide_processed, video_mask_processed = preprocess_video_with_mask(video_guide if sparse_video_image is None else sparse_video_image, video_mask, height=image_size[0], width = image_size[1], max_frames= guide_frames_extract_count, start_frame = guide_frames_extract_start, fit_canvas = sample_fit_canvas, fit_crop = fit_crop, target_fps = fps, process_type = preprocess_type, expand_scale = mask_expand, RGB_Mask = True, negate_mask = "N" in video_prompt_type, process_outside_mask = process_outside_mask, outpainting_dims = outpainting_dims, proc_no =1, inpaint_color =inpaint_color, block_size = block_size, to_bbox = "H" in video_prompt_type )+ if preprocess_type2 != None:+ video_guide_processed2, video_mask_processed2 = preprocess_video_with_mask(video_guide, video_mask, height=image_size[0], width = image_size[1], max_frames= guide_frames_extract_count, start_frame = guide_frames_extract_start, fit_canvas = sample_fit_canvas, fit_crop = fit_crop, target_fps = fps, process_type = preprocess_type2, expand_scale = mask_expand, RGB_Mask = True, negate_mask = "N" in video_prompt_type, process_outside_mask = process_outside_mask, outpainting_dims = outpainting_dims, proc_no =2, block_size = block_size, to_bbox = "H" in video_prompt_type )++ if video_guide_processed is not None and sample_fit_canvas is not None:+ image_size = video_guide_processed.shape[-2:]+ sample_fit_canvas = None++ if process_all:+ cached_video_guide_processed, cached_video_mask_processed, cached_video_guide_processed2, cached_video_mask_processed2 = video_guide_processed, video_mask_processed, video_guide_processed2, video_mask_processed2+ cached_video_video_start_frame = guide_frames_extract_start++ if process_all:+ process_slice = slice(guide_frames_extract_start - cached_video_video_start_frame, guide_frames_extract_start - cached_video_video_start_frame + guide_slice_to_extract )+ video_guide_processed = None if cached_video_guide_processed is None else cached_video_guide_processed[:, process_slice]+ video_mask_processed = None if cached_video_mask_processed is None else cached_video_mask_processed[:, process_slice]+ video_guide_processed2 = None if cached_video_guide_processed2 is None else cached_video_guide_processed2[:, process_slice]+ video_mask_processed2 = None if cached_video_mask_processed2 is None else cached_video_mask_processed2[:, process_slice]+if window_no == 1 and image_refs is not None and len(image_refs) > 0:if sample_fit_canvas is not None and (nb_frames_positions > 0 or "K" in video_prompt_type) :from shared.utils.utils import get_outpainting_full_area_dimensions@@ -10401,6 +10441,10 @@ if __name__ == "__main__":if not os.path.isdir(args.output_dir):os.makedirs(args.output_dir, exist_ok=True)server_config["save_path"] = args.output_dir+ server_config["image_save_path"] = args.output_dir+ # Keep module-level paths in sync (used by save_video / get_available_filename).+ save_path = args.output_dir+ image_save_path = args.output_dirprint(f"Output directory: {args.output_dir}")# Create minimal state with all required fields