The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
ComfyUI-InstantHMR: a pinned form with only the loader and the predictor
Adarshe4b747350622
diff --git a/comfy-nodes/ComfyUI-InstantHMR/LICENSE b/comfy-nodes/ComfyUI-InstantHMR/LICENSEnew file mode 100644index 00000000..84895331--- /dev/null+++ b/comfy-nodes/ComfyUI-InstantHMR/LICENSE@@ -0,0 +1,213 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for describing the origin of the Work and+ reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may accept and charge a+ fee for, the acceptance of support, warranty, indemnity, or other+ liability obligations and/or rights consistent with this License.+ However, in accepting such obligations, You may act only on Your+ own behalf and on Your sole responsibility, not on behalf of any+ other Contributor, and only if You agree to indemnify, defend, and+ hold each Contributor harmless for any liability incurred by, or+ claims asserted against, such Contributor by reason of your accepting+ any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright 2026 InstantHMR authors++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied. See the License for the specific language governing permissions+ and limitations under the License.++================================================================================++THIRD-PARTY NOTICES+-------------------++This license covers the code in this repository. The InstantHMR weights+(https://huggingface.co/jtydhr88/ComfyUI-InstantHMR, converted from+https://huggingface.co/momolesang/InstantHMR) are under the SAM License, since+they are trained on SAM 3D Body annotations and contain parts of its+checkpoint. The nano, tiny, small and medium weights are also for+non-commercial use only. The SAM License text ships with the weights.diff --git a/comfy-nodes/ComfyUI-InstantHMR/NOTICE b/comfy-nodes/ComfyUI-InstantHMR/NOTICEnew file mode 100644index 00000000..3ea60bf6--- /dev/null+++ b/comfy-nodes/ComfyUI-InstantHMR/NOTICE@@ -0,0 +1,9 @@+ComfyUI-InstantHMR (Fuobe's pinned form)++Based on ComfyUI-InstantHMR by jtydhr88, https://github.com/jtydhr88/ComfyUI-InstantHMR,+commit 36d85573438e5de5d2fe63ba2dbca927c6a16c9b, licensed under the Apache License 2.0 (see LICENSE).++Changes from that commit:+- __init__.py registers only the loader (InstantHMRLoader) and the predictor (InstantHMRPredict).+- The live capture node, its HTTP routes and its web files (live.py, humanoid.py, web/, static/) are left out.+- nodes.py and instanthmr_model.py are unchanged.diff --git a/comfy-nodes/ComfyUI-InstantHMR/README.md b/comfy-nodes/ComfyUI-InstantHMR/README.mdnew file mode 100644index 00000000..1a89adb5--- /dev/null+++ b/comfy-nodes/ComfyUI-InstantHMR/README.md@@ -0,0 +1,24 @@+# ComfyUI-InstantHMR (Fuobe's pinned form)++InstantHMR for ComfyUI: one MHR body (pose, shape, hands, 70 keypoints and the mesh) for every person in a picture or+every frame of a clip, as `MHR_POSE_DATA` for ComfyUI's own SAM 3D Body nodes. Fuobe's Body Double runs on it.++This is jtydhr88's ComfyUI-InstantHMR with only its two processing nodes registered: **Load InstantHMR Model** and+**Run InstantHMR Prediction**. See `NOTICE` for what differs from the original.++## Install++Copy this folder into `ComfyUI/custom_nodes/ComfyUI-InstantHMR` and restart ComfyUI. Put the checkpoint in+`ComfyUI/models/detection/`:++| File | Download (pinned revision) | Bytes | SHA-256 |+|---|---|---|---|+| `instanthmr_medium.safetensors` | https://huggingface.co/jtydhr88/ComfyUI-InstantHMR/resolve/964effb58c3358ca8a0e35da386f49de1480ac9e/instanthmr_medium.safetensors | 180,730,516 | `76bd71c76683b5c0ea156b8b9c527b8f392832701c3a0377f81b8ba14277ca5e` |+| `instanthmr_medium_commercial.safetensors` (commercial use allowed under the SAM License) | https://huggingface.co/jtydhr88/ComfyUI-InstantHMR/resolve/964effb58c3358ca8a0e35da386f49de1480ac9e/instanthmr_medium_commercial.safetensors | 180,730,516 | `6fb700552d994da13f8c35434dbcd5836ee01eeba1bba7026764cf06fb7c7d42` |++Requirements: ComfyUI 0.42 or later (its SAM 3D Body and RT-DETR nodes). No other packages.++## Licence++Code: Apache-2.0 (`LICENSE`, `NOTICE`). The InstantHMR weights are under the SAM License; the medium file is+non-commercial, the medium_commercial file allows commercial use under its terms.diff --git a/comfy-nodes/ComfyUI-InstantHMR/__init__.py b/comfy-nodes/ComfyUI-InstantHMR/__init__.pynew file mode 100644index 00000000..68a15637--- /dev/null+++ b/comfy-nodes/ComfyUI-InstantHMR/__init__.py@@ -0,0 +1,18 @@+# ComfyUI-InstantHMR (jtydhr88) @ 36d85573438e5de5d2fe63ba2dbca927c6a16c9b, trimmed for this server:+# only the loader and the predictor are registered. The Live Capture node, its /instanthmr/* routes+# (an unauthenticated websocket that writes recordings and can send UDP) and its web files are left out.+from typing_extensions import override++from comfy_api.latest import ComfyExtension, io++from .nodes import InstantHMRLoader, InstantHMRPredict+++class InstantHMRExtension(ComfyExtension):+ @override+ async def get_node_list(self) -> list[type[io.ComfyNode]]:+ return [InstantHMRLoader, InstantHMRPredict]+++async def comfy_entrypoint() -> InstantHMRExtension:+ return InstantHMRExtension()diff --git a/comfy-nodes/ComfyUI-InstantHMR/instanthmr_model.py b/comfy-nodes/ComfyUI-InstantHMR/instanthmr_model.pynew file mode 100644index 00000000..adcee5ff--- /dev/null+++ b/comfy-nodes/ComfyUI-InstantHMR/instanthmr_model.py@@ -0,0 +1,252 @@+import torch+import torch.nn as nn+import torch.nn.functional as F++import comfy.model_management+from comfy.ldm.modules.attention import optimized_attention_for_device+from comfy.ldm.sam3d_body.mhr.mhr_head import MHRHead+from comfy.ldm.sam3d_body.mhr.mhr_rig import MHRRig+from comfy.ldm.sam3d_body.mhr.mhr_utils import batchXYZfrom6D, compact_cont_to_model_params_body+from comfy.ops import cast_to_input++# HGNetV2 b0/b1/b2/b4 as in timm: stem (mid, out), stages (ic, mc, oc, blocks, downsample, light, k, layers), LAB+BACKBONES = {+ "nano": ((16, 16), [(16, 16, 64, 1, False, False, 3, 3), (64, 32, 256, 1, True, False, 3, 3), (256, 64, 512, 2, True, True, 5, 3), (512, 128, 1024, 1, True, True, 5, 3)], True),+ "tiny": ((24, 32), [(32, 32, 64, 1, False, False, 3, 3), (64, 48, 256, 1, True, False, 3, 3), (256, 96, 512, 2, True, True, 5, 3), (512, 192, 1024, 1, True, True, 5, 3)], True),+ "small": ((24, 32), [(32, 32, 96, 1, False, False, 3, 4), (96, 64, 384, 1, True, False, 3, 4), (384, 128, 768, 3, True, True, 5, 4), (768, 256, 1536, 1, True, True, 5, 4)], True),+ "medium": ((32, 48), [(48, 48, 128, 1, False, False, 3, 6), (128, 96, 512, 1, True, False, 3, 6), (512, 192, 1024, 3, True, True, 5, 6), (1024, 384, 2048, 1, True, True, 5, 6)], False),+}++NUM_KEYPOINTS = 70+D_MODEL = 512+N_HEADS = 8+N_LAYERS = 4+KP2D_BINS = 96+++def backbone_from_state_dict(sd):+ stem = sd["backbone.stem.stem1.conv.weight"].shape[0]+ stage1 = sd["backbone.stages.0.blocks.0.aggregation.1.conv.weight"].shape[0]+ for name, ((mid, _), stages, _) in BACKBONES.items():+ if mid == stem and stages[0][2] == stage1:+ return name+ raise ValueError(f"Unknown InstantHMR backbone (stem {stem}, stage1 {stage1})")+++class ConvAct(nn.Module):+ # BatchNorm is folded into the conv in the released weights.+ def __init__(self, ic, oc, k, s=1, groups=1, use_act=True, use_lab=False, device=None, dtype=None, operations=None):+ super().__init__()+ self.conv = operations.Conv2d(ic, oc, k, s, (k - 1) // 2, groups=groups, device=device, dtype=dtype)+ self.use_act = use_act+ self.lab = nn.Parameter(torch.empty(2, device=device, dtype=dtype)) if use_act and use_lab else None++ def forward(self, x):+ x = self.conv(x)+ if self.use_act:+ x = F.relu(x)+ if self.lab is not None:+ lab = cast_to_input(self.lab, x)+ x = x * lab[0] + lab[1]+ return x+++class LightConvAct(nn.Module):+ def __init__(self, ic, oc, k, use_lab, device=None, dtype=None, operations=None):+ super().__init__()+ self.conv1 = ConvAct(ic, oc, 1, use_act=False, use_lab=use_lab, device=device, dtype=dtype, operations=operations)+ self.conv2 = ConvAct(oc, oc, k, groups=oc, use_lab=use_lab, device=device, dtype=dtype, operations=operations)++ def forward(self, x):+ return self.conv2(self.conv1(x))+++class Stem(nn.Module):+ def __init__(self, mc, oc, use_lab, device=None, dtype=None, operations=None):+ super().__init__()+ kw = dict(use_lab=use_lab, device=device, dtype=dtype, operations=operations)+ self.stem1 = ConvAct(3, mc, 3, 2, **kw)+ self.stem2a = ConvAct(mc, mc // 2, 2, **kw)+ self.stem2b = ConvAct(mc // 2, mc, 2, **kw)+ self.stem3 = ConvAct(mc * 2, mc, 3, 2, **kw)+ self.stem4 = ConvAct(mc, oc, 1, **kw)+ self.pool = nn.MaxPool2d(2, 1, ceil_mode=True)++ def forward(self, x):+ x = F.pad(self.stem1(x), (0, 1, 0, 1))+ x2 = self.stem2b(F.pad(self.stem2a(x), (0, 1, 0, 1)))+ return self.stem4(self.stem3(torch.cat([self.pool(x), x2], 1)))+++class HGBlock(nn.Module):+ def __init__(self, ic, mc, oc, layer_num, k, residual, light, use_lab, device=None, dtype=None, operations=None):+ super().__init__()+ kw = dict(use_lab=use_lab, device=device, dtype=dtype, operations=operations)+ self.residual = residual+ if light:+ self.layers = nn.ModuleList([LightConvAct(ic if i == 0 else mc, mc, k, **kw) for i in range(layer_num)])+ else:+ self.layers = nn.ModuleList([ConvAct(ic if i == 0 else mc, mc, k, **kw) for i in range(layer_num)])+ self.aggregation = nn.Sequential(ConvAct(ic + layer_num * mc, oc // 2, 1, **kw), ConvAct(oc // 2, oc, 1, **kw))++ def forward(self, x):+ outs = [x]+ for layer in self.layers:+ outs.append(layer(outs[-1]))+ y = self.aggregation(torch.cat(outs, 1))+ return y + x if self.residual else y+++class HGStage(nn.Module):+ def __init__(self, ic, mc, oc, blocks, downsample, light, k, layer_num, use_lab, device=None, dtype=None, operations=None):+ super().__init__()+ kw = dict(use_lab=use_lab, device=device, dtype=dtype, operations=operations)+ self.downsample = ConvAct(ic, ic, 3, 2, groups=ic, use_act=False, **kw) if downsample else nn.Identity()+ self.blocks = nn.Sequential(*[HGBlock(ic if i == 0 else oc, mc, oc, layer_num, k, i != 0, light, **kw) for i in range(blocks)])++ def forward(self, x):+ return self.blocks(self.downsample(x))+++class HGNetV2(nn.Module):+ def __init__(self, stem, stages, use_lab, device=None, dtype=None, operations=None):+ super().__init__()+ self.stem = Stem(*stem, use_lab, device=device, dtype=dtype, operations=operations)+ self.stages = nn.Sequential(*[HGStage(*cfg, use_lab, device=device, dtype=dtype, operations=operations) for cfg in stages])+ self.out_channels = stages[-1][2]++ def forward(self, x):+ return self.stages(self.stem(x))+++class Attention(nn.Module):+ def __init__(self, dim, heads, device=None, dtype=None, operations=None):+ super().__init__()+ self.heads = heads+ self.q = operations.Linear(dim, dim, device=device, dtype=dtype)+ self.kv = operations.Linear(dim, dim * 2, device=device, dtype=dtype)+ self.out = operations.Linear(dim, dim, device=device, dtype=dtype)++ def forward(self, x, context):+ k, v = self.kv(context).chunk(2, dim=-1)+ attention = optimized_attention_for_device(x.device, small_input=True)+ return self.out(attention(self.q(x), k, v, self.heads))+++class DecoderLayer(nn.Module):+ # nn.TransformerDecoderLayer(norm_first=True, activation="gelu")+ def __init__(self, dim, heads, device=None, dtype=None, operations=None):+ super().__init__()+ kw = dict(device=device, dtype=dtype, operations=operations)+ self.norm1 = operations.LayerNorm(dim, device=device, dtype=dtype)+ self.self_attn = Attention(dim, heads, **kw)+ self.norm2 = operations.LayerNorm(dim, device=device, dtype=dtype)+ self.cross_attn = Attention(dim, heads, **kw)+ self.norm3 = operations.LayerNorm(dim, device=device, dtype=dtype)+ self.mlp = nn.Sequential(operations.Linear(dim, dim * 4, device=device, dtype=dtype), nn.GELU(),+ operations.Linear(dim * 4, dim, device=device, dtype=dtype))++ def forward(self, x, memory):+ h = self.norm1(x)+ x = x + self.self_attn(h, h)+ x = x + self.cross_attn(self.norm2(x), memory)+ return x + self.mlp(self.norm3(x))+++class MHRBodyRig(MHRRig):+ # InstantHMR is trained on the MHR mesh without pose correctives, so their 663 MB weights are not loaded.+ def __init__(self, device=None):+ super().__init__(device=device)+ self.pose_corr_weight = None+ self.pose_corr_sparse_weight = None+ self.pose_corr_sparse_indices = None++ def forward(self, identity_coeffs, model_parameters, expr_coeffs, apply_correctives=False):+ return super().forward(identity_coeffs, model_parameters, expr_coeffs, apply_correctives=False)+++class InstantHMRHead(MHRHead):+ """SAM 3D Body's continuous MHR head without the face block, with bounded body size."""++ def __init__(self, dim, mhr_rig, device=None, dtype=None, operations=None):+ super().__init__(dim, mhr_rig, device=device, dtype=dtype, operations=operations)+ self.npose -= self.num_face_comps+ self.proj = nn.Sequential(operations.LayerNorm(dim, device=device, dtype=dtype),+ operations.Linear(dim, dim, device=device, dtype=dtype), nn.GELU(),+ operations.Linear(dim, self.npose, device=device, dtype=dtype))+ self.init_estimate = nn.Parameter(torch.empty(1, self.npose, device=device), requires_grad=False)+ # (lo, half range) of the tanh bounds on the 6 *_flexible body channels and the 28 bone-scale coefficients+ self.flex_bounds = nn.Parameter(torch.empty(2, 6, device=device), requires_grad=False)+ self.scale_bounds = nn.Parameter(torch.empty(2, self.num_scale_comps, device=device), requires_grad=False)++ def forward(self, x):+ pred = self.proj(x).float() + self.init_estimate+ B = pred.shape[0]+ root, body, shape, scale, hand = pred.split([6, self.body_cont_dim, self.num_shape_comps, self.num_scale_comps, self.num_hand_comps * 2], dim=1)++ global_rot = batchXYZfrom6D(root)+ body_pose = compact_cont_to_model_params_body(body)+ body_pose[:, 124:130] = self.flex_bounds[0] + self.flex_bounds[1] * (body_pose[:, 124:130].tanh() + 1)+ scale = self.scale_bounds[0] + self.scale_bounds[1] * (scale.tanh() + 1)+ face = pred.new_zeros(B, self.num_face_comps)++ verts, j3d, jcoords, model_params, joint_rots = self.mhr_forward(+ global_trans=torch.zeros_like(global_rot), global_rot=global_rot, body_pose_params=body_pose,+ hand_pose_params=hand, scale_params=scale, shape_params=shape, expr_params=face,+ return_keypoints=True, return_joint_coords=True, return_model_params=True, return_joint_rotations=True,+ )+ j3d = j3d[:, :NUM_KEYPOINTS]+ for t in (verts, j3d, jcoords):+ t[..., [1, 2]] *= -1+ return {+ "global_rot": global_rot,+ "body_pose": body_pose,+ "shape": shape,+ "scale": scale,+ "hand": hand,+ "face": face,+ "pred_keypoints_3d": j3d,+ "pred_vertices": verts,+ "pred_joint_coords": jcoords,+ "joint_global_rots": joint_rots,+ "mhr_model_params": model_params,+ }+++class InstantHMR(nn.Module):+ image_size = 288++ def __init__(self, backbone, device=None, dtype=None, operations=None):+ super().__init__()+ stem, stages, use_lab = BACKBONES[backbone]+ self.backbone = HGNetV2(stem, stages, use_lab, device=device, dtype=dtype, operations=operations)+ self.feat_proj = operations.Linear(self.backbone.out_channels, D_MODEL, device=device, dtype=dtype)+ tokens = (self.image_size // 32) ** 2+ self.mem_pos_embed = nn.Parameter(torch.empty(1, tokens, D_MODEL, device=device, dtype=dtype), requires_grad=False)+ self.query_embed = nn.Parameter(torch.empty(1, 1 + NUM_KEYPOINTS, D_MODEL, device=device, dtype=dtype), requires_grad=False)+ self.cond_proj = nn.Sequential(operations.Linear(3, 128, device=device, dtype=dtype), nn.GELU(),+ operations.Linear(128, D_MODEL, device=device, dtype=dtype))+ self.layers = nn.ModuleList([DecoderLayer(D_MODEL, N_HEADS, device=device, dtype=dtype, operations=operations) for _ in range(N_LAYERS)])+ self.mhr = MHRBodyRig(device=device)+ self.head_pose = InstantHMRHead(D_MODEL, self.mhr, device=device, dtype=dtype, operations=operations)+ self.head_cam = operations.Linear(D_MODEL, 3, device=device, dtype=dtype)+ self.head_2d = nn.Sequential(operations.Linear(D_MODEL, 256, device=device, dtype=dtype), nn.GELU(),+ operations.Linear(256, 2 * KP2D_BINS, device=device, dtype=dtype))+ self.kp2d_bin_centers = nn.Parameter(torch.empty(KP2D_BINS, device=device), requires_grad=False)++ def forward(self, image, cliff_cond):+ """image (B, 3, 288, 288) ImageNet-normalised crop, cliff_cond (B, 3) box position in the frame."""+ memory = self.feat_proj(self.backbone(image).flatten(2).transpose(1, 2))+ memory = memory + cast_to_input(self.mem_pos_embed, memory)+ x = cast_to_input(self.query_embed, memory) + self.cond_proj(cliff_cond).unsqueeze(1)+ for layer in self.layers:+ x = layer(x, memory)++ out = self.head_pose(x[:, 0])+ out["pred_cam_t"] = self.head_cam(x[:, 0]).float()+ logits = self.head_2d(x[:, 1:]).float().unflatten(-1, (2, KP2D_BINS))+ out["pred_keypoints_2d_crop"] = (logits.softmax(-1) * self.kp2d_bin_centers).sum(-1)+ return out++ def memory_used_forward(self, batch):+ return batch * 64 * 1024 * 1024 * comfy.model_management.dtype_size(self.feat_proj.weight.dtype)diff --git a/comfy-nodes/ComfyUI-InstantHMR/nodes.py b/comfy-nodes/ComfyUI-InstantHMR/nodes.pynew file mode 100644index 00000000..39f090d8--- /dev/null+++ b/comfy-nodes/ComfyUI-InstantHMR/nodes.py@@ -0,0 +1,225 @@+import math+import os++import numpy as np+import torch+import torch.nn.functional as F++import comfy.model_management+import comfy.model_patcher+import comfy.ops+import comfy.utils+import folder_paths+from comfy_api.latest import InputImpl, io+from comfy_extras.nodes_sam3d_body import _per_frame_bboxes_from_detections+from comfy_extras.sam3d_body.utils import compute_canonical_colors, compute_hand_vert_mask, inputs_from_sam3_track++from .instanthmr_model import InstantHMR, backbone_from_state_dict++InstantHMRModel = io.Custom("INSTANTHMR_MODEL")+SAM3TrackData = io.Custom("SAM3_TRACK_DATA")+MHRPoseData = io.Custom("MHR_POSE_DATA")++IMAGENET_MEAN = (0.485, 0.456, 0.406)+IMAGENET_STD = (0.229, 0.224, 0.225)+CROP_EXPAND = 1.2+RECORD_DIR = "instanthmr_live"+CHARACTER_EXTENSIONS = (".fbx", ".glb", ".gltf", ".vrm")+LIVE_CAMERAS = ["Phone / other device", "This device"]+MHR_BODY = "MHR body"+# Focal when the camera is unknown, as a multiple of the image diagonal (InstantHMR's training default).+FOCAL_DIAG = 1.05+++class InstantHMRLoader(io.ComfyNode):+ @classmethod+ def define_schema(cls):+ return io.Schema(+ node_id="InstantHMRLoader",+ display_name="Load InstantHMR Model",+ category="image/detection",+ inputs=[io.Combo.Input("model_file", options=folder_paths.get_filename_list("detection"))],+ outputs=[InstantHMRModel.Output(display_name="instanthmr_model")],+ )++ @classmethod+ def execute(cls, model_file) -> io.NodeOutput:+ sd = comfy.utils.load_torch_file(folder_paths.get_full_path_or_raise("detection", model_file), safe_load=True)+ load_device = comfy.model_management.get_torch_device()+ dtype = comfy.model_management.unet_dtype(load_device, model_params=-1, supported_dtypes=[torch.float16, torch.bfloat16, torch.float32],+ weight_dtype=comfy.utils.weight_dtype(sd))+ manual_cast_dtype = comfy.model_management.unet_manual_cast(dtype, load_device)+ operations = comfy.ops.pick_operations(dtype, manual_cast_dtype, load_device=load_device, disable_fast_fp8=True)++ model = InstantHMR(backbone_from_state_dict(sd), dtype=dtype, operations=operations)+ model.load_state_dict(sd, strict=True)+ model.dtype = manual_cast_dtype or dtype+ patcher = comfy.model_patcher.CoreModelPatcher(model, load_device=load_device, offload_device=comfy.model_management.unet_offload_device(),+ size=comfy.model_management.module_size(model))+ return io.NodeOutput(patcher)+++def crop_batch(frame, boxes, focal, size):+ """The square 1.2x box crops InstantHMR is trained on, their CLIFF vectors, and the crop squares (x0, y0, side)."""+ _, H, W = frame.shape+ # float64 like the reference: in float32 a box edge on an integer pixel can floor one pixel off.+ x1, y1, x2, y2 = boxes.double().unbind(-1)+ cx, cy = (x1 + x2) / 2, (y1 + y2) / 2+ box = torch.maximum(x2 - x1, y2 - y1)+ cliff = torch.stack([torch.atan((cx - W / 2) / focal), torch.atan((cy - H / 2) / focal), box / focal], -1)++ side = box * CROP_EXPAND+ sx, sy = cx - side / 2, cy - side / 2+ # The reference cuts the pixel-aligned patch around the square and resizes it to the crop size.+ px, py = torch.floor(sx), torch.floor(sy)+ pw, ph = torch.ceil(sx + side) - px, torch.ceil(sy + side) - py+ t = (torch.arange(size, device=frame.device, dtype=torch.float64) + 0.5) / size+ gx = (px[:, None] + t[None] * pw[:, None]) * (2 / W) - 1+ gy = (py[:, None] + t[None] * ph[:, None]) * (2 / H) - 1+ grid = torch.stack([gx[:, None, :].expand(-1, size, -1), gy[:, :, None].expand(-1, -1, size)], -1).float()+ crops = F.grid_sample(frame[None].expand(len(boxes), -1, -1, -1), grid, mode="bilinear", padding_mode="zeros", align_corners=False)+ mean = torch.tensor(IMAGENET_MEAN, device=frame.device).view(1, 3, 1, 1)+ std = torch.tensor(IMAGENET_STD, device=frame.device).view(1, 3, 1, 1)+ return (crops - mean) / std, cliff.float(), torch.stack([sx, sy, side], -1).float()+++class InstantHMRPredict(io.ComfyNode):+ @classmethod+ def define_schema(cls):+ return io.Schema(+ node_id="InstantHMRPredict",+ display_name="Run InstantHMR Prediction",+ category="image/detection",+ inputs=[+ InstantHMRModel.Input("instanthmr_model"),+ io.Image.Input("image"),+ SAM3TrackData.Input("track_data", optional=True, tooltip="Person tracks from SAM3 Video Track, for multi-person video"),+ io.BoundingBox.Input("bboxes", optional=True, force_input=True, tooltip="Per-frame person boxes, e.g. from RT-DETR Detect with class 'person'"),+ io.Float.Input("fov", default=0.0, min=0.0, max=180.0, step=0.1, advanced=True,+ tooltip="Vertical FoV in degrees. Sets the depth and absolute scale. 0 = focal of 1.05x the image diagonal."),+ io.Int.Input("batch_size", default=64, min=1, max=1024, advanced=True, tooltip="Person crops per forward pass"),+ ],+ outputs=[MHRPoseData.Output("mhr_pose_data")],+ )++ @classmethod+ def execute(cls, instanthmr_model, image, track_data=None, bboxes=None, fov=0.0, batch_size=64) -> io.NodeOutput:+ B, H, W, _ = image.shape+ per_frame_boxes, per_frame_masks = None, None+ if track_data is not None:+ per_frame_boxes, per_frame_masks = inputs_from_sam3_track(track_data, B, H, W)+ if per_frame_boxes is None and bboxes:+ per_frame_boxes = _per_frame_bboxes_from_detections(bboxes, B)+ if per_frame_boxes is None:+ per_frame_boxes = [torch.tensor([[0.0, 0.0, float(W), float(H)]]) for _ in range(B)]+ focal = H / (2 * math.tan(math.radians(fov) / 2)) if fov > 0 else FOCAL_DIAG * math.hypot(H, W)++ comfy.model_management.load_models_gpu([instanthmr_model], memory_required=instanthmr_model.model.memory_used_forward(batch_size))+ model = instanthmr_model.model+ device = instanthmr_model.load_device++ jobs = [(f, k) for f in range(B) for k in range(per_frame_boxes[f].shape[0])]+ frames_out = [[] for _ in range(B)]+ pbar = comfy.utils.ProgressBar(len(jobs))+ for start in range(0, len(jobs), batch_size):+ chunk = jobs[start:start + batch_size]+ crops, cliffs, squares = [], [], []+ for f in sorted({f for f, _ in chunk}):+ ks = [k for g, k in chunk if g == f]+ frame = image[f].to(device=device, dtype=torch.float32).permute(2, 0, 1)+ c, cl, sq = crop_batch(frame, per_frame_boxes[f][ks].to(device), focal, model.image_size)+ crops.append(c)+ cliffs.append(cl)+ squares.append(sq)+ squares = torch.cat(squares)+ out = model(torch.cat(crops).to(model.dtype), torch.cat(cliffs).to(model.dtype))+ out["pred_keypoints_2d"] = (out.pop("pred_keypoints_2d_crop") + 1) * 0.5 * squares[:, None, 2:] + squares[:, None, :2]+ out = {k: v.float().cpu().numpy() for k, v in out.items()}++ for i, (f, k) in enumerate(chunk):+ masks = per_frame_masks[f] if per_frame_masks is not None else None+ frames_out[f].append({+ "bbox": per_frame_boxes[f][k].numpy(),+ "focal_length": np.float32(focal),+ "pred_keypoints_3d": out["pred_keypoints_3d"][i],+ "pred_keypoints_2d": out["pred_keypoints_2d"][i],+ "pred_vertices": out["pred_vertices"][i],+ "pred_cam_t": out["pred_cam_t"][i],+ "global_rot": out["global_rot"][i],+ "body_pose_params": out["body_pose"][i],+ "hand_pose_params": out["hand"][i],+ "scale_params": out["scale"][i],+ "shape_params": out["shape"][i],+ "expr_params": out["face"][i],+ "mask": (masks[k] if masks.shape[0] > 1 else masks[0]) if masks is not None else None,+ "pred_joint_coords": out["pred_joint_coords"][i],+ "pred_global_rots": out["joint_global_rots"][i],+ "mhr_model_params": out["mhr_model_params"][i],+ "pred_face_keypoints_3d": None,+ "pred_face_keypoints_2d": None,+ })+ pbar.update(len(chunk))++ return io.NodeOutput({+ "frames": frames_out,+ "faces": model.head_pose.faces_np(),+ "image_size": (int(H), int(W)),+ "canonical_colors": compute_canonical_colors(model),+ "hand_vert_mask": compute_hand_vert_mask(model),+ })+++def recording_files():+ root = os.path.join(folder_paths.get_input_directory(), RECORD_DIR)+ if not os.path.isdir(root):+ return []+ return sorted((f"{RECORD_DIR}/{f}" for f in os.listdir(root) if f.endswith(".mp4")), reverse=True)+++def character_files():+ root = folder_paths.get_input_directory()+ files = []+ for folder, _, names in os.walk(root):+ files += [os.path.relpath(os.path.join(folder, n), root).replace(os.sep, "/") for n in names if n.lower().endswith(CHARACTER_EXTENSIONS)]+ return sorted(files)+++class InstantHMRLiveCapture(io.ComfyNode):+ """Live preview from this device's camera or a phone on the LAN; the recorded clip is the output.+ Like WebcamCapture, the live settings are inputs the node's frontend reads; execute only loads the recording."""++ @classmethod+ def define_schema(cls):+ return io.Schema(+ node_id="InstantHMRLiveCapture",+ display_name="InstantHMR Live Capture",+ category="image/detection",+ inputs=[+ io.Combo.Input("recording", options=recording_files(), tooltip="A clip recorded with the live view"),+ io.Combo.Input("model", options=[f for f in folder_paths.get_filename_list("detection") if "instanthmr" in f.lower()],+ tooltip="InstantHMR model for the live view"),+ io.Combo.Input("detector", options=[f for f in folder_paths.get_filename_list("diffusion_models") if "rt_detr" in f.lower()],+ tooltip="RT-DETR person detector for the live view"),+ io.Combo.Input("camera", options=LIVE_CAMERAS, tooltip="Phone / other device shows a QR code to open on the phone"),+ io.Combo.Input("character", options=[MHR_BODY, *character_files()],+ tooltip="Body in the 3D view: the MHR mesh, or a rigged FBX, glTF or VRM character from the input folder"),+ io.String.Input("vmc", default="", placeholder="host:port, e.g. 127.0.0.1:39539",+ tooltip="Stream the first person to a VMC protocol app (VSeeFace, Warudo, VNyan...); empty = off"),+ io.Float.Input("fov", default=0.0, min=0.0, max=179.0, step=1.0, advanced=True,+ tooltip="Vertical field of view in degrees; 0 uses a focal of 1.05x the image diagonal"),+ io.Int.Input("detect_every", default=2, min=1, max=10, advanced=True,+ tooltip="Run the detector every N frames and reuse its boxes in between"),+ ],+ outputs=[io.Video.Output()],+ )++ @classmethod+ def execute(cls, recording, **live_settings) -> io.NodeOutput:+ return io.NodeOutput(InputImpl.VideoFromFile(folder_paths.get_annotated_filepath(recording)))++ @classmethod+ def validate_inputs(cls, recording, model, detector, character):+ # Only the recording is needed to run; the live models and character may be missing on this machine.+ if recording not in recording_files():+ return f"Recording not found: {recording}"+ return True