Download preprocess/kaolrm.py from tsinghua-ee/ELLSA2_data: direct link, hf CLI and curl.
- Browser
- Download file 4.35 kB
-
https://huggingface.co/datasets/tsinghua-ee/ELLSA2_data/resolve/main/preprocess/kaolrm.py
- Command line
-
hf download hf://datasets/tsinghua-ee/ELLSA2_data/preprocess/kaolrm.py
-
curl -L -o kaolrm.py https://huggingface.co/datasets/tsinghua-ee/ELLSA2_data/resolve/main/preprocess/kaolrm.py
4.35 kB
| # Copyright (c) 2023-2024, Zexin He | |
| # Copyright (c) 2025, Qingtian Zhu | |
| # Adapted from KaoLRM for parameter-only extraction; Apache-2.0. | |
| # See KAOLRM_LICENSE.txt. The upstream model weights have separate terms. | |
| """Load only KaoLRM's image-to-FLAME-parameter network, without mesh/render assets.""" | |
| import importlib | |
| import json | |
| from pathlib import Path | |
| import sys | |
| import types | |
| import numpy as np | |
| from safetensors import safe_open | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| def components(repo): | |
| # KaoLRM's models/__init__.py eagerly imports CUDA rasterizers and FLAME. | |
| # A separate namespace loads the unchanged parameter components directly. | |
| name = '_ellsa2_kaolrm_components' | |
| path = str(Path(repo).resolve() / 'kaolrm/models') | |
| if name not in sys.modules: | |
| package = types.ModuleType(name) | |
| package.__path__ = [path] | |
| sys.modules[name] = package | |
| assert sys.modules[name].__path__ == [path], 'Use one KaoLRM revision per process' | |
| return lambda module: importlib.import_module(name + '.' + module) | |
| class ParameterModel(nn.Module): | |
| def __init__(self, repo, checkpoint): | |
| super().__init__() | |
| # Match the original inference runner: float32, eager execution. | |
| torch._dynamo.config.disable = True | |
| from accelerate import PartialState | |
| PartialState() | |
| module = components(repo) | |
| cfg = json.loads((Path(checkpoint) / 'config.json').read_text()) | |
| assert cfg['encoder_type'] == 'dinov2' and cfg['ortho_proj'], 'Use the KaoLRM mono checkpoint' | |
| self.encoder = nn.Module() | |
| backbone = getattr(module('encoders.dinov2.hub.backbones'), cfg['encoder_model_name']) | |
| # The KaoLRM checkpoint already contains the entire DINO encoder. | |
| self.encoder.model = backbone(pretrained=False) | |
| self.camera_embedder = module('embedder').CameraEmbedder(16, cfg['camera_embed_dim']) | |
| self.low_res = cfg['triplane_low_res'] | |
| self.pos_embed = nn.Parameter(torch.empty(1, 3 * self.low_res**2, cfg['transformer_dim'])) | |
| self.transformer = module('transformer').TransformerDecoder( | |
| block_type='cond_mod', num_layers=cfg['transformer_layers'], | |
| num_heads=cfg['transformer_heads'], inner_dim=cfg['transformer_dim'], | |
| cond_dim=cfg['encoder_feat_dim'], mod_dim=cfg['camera_embed_dim']) | |
| self.upsampler = nn.ConvTranspose2d(cfg['transformer_dim'], cfg['triplane_dim'], 2, 2) | |
| self.flame_decoder = module('flame_decoder').FLAMEDecoder( | |
| cfg['triplane_dim'], cfg['triplane_high_res']) | |
| with safe_open(Path(checkpoint) / 'model.safetensors', framework='pt', device='cpu') as weights: | |
| state = {key: weights.get_tensor(key) for key in weights.keys() | |
| if not key.startswith(('flame_model.', 'gaussian_decoder.'))} | |
| self.load_state_dict(state, strict=True) | |
| self.eval() | |
| def forward(self, image): | |
| features = self.encoder.model(image, is_training=True) | |
| features = torch.cat([features['x_norm_clstoken'][:, None], features['x_norm_patchtokens']], dim=1) | |
| # Original canonical camera: flattened 3x4 extrinsics then fx, fy, cx, cy. | |
| camera = image.new_tensor([[1, 0, 0, 0, 0, 0, -1, -2, 0, 1, 0, 0, .75, .75, .5, .5]]) | |
| camera = self.camera_embedder(camera.expand(len(image), -1)) | |
| tokens = self.transformer(self.pos_embed.repeat(len(image), 1, 1), cond=features, mod=camera) | |
| planes = tokens.view(len(image), 3, self.low_res, self.low_res, -1) | |
| planes = planes.permute(1, 0, 4, 2, 3).reshape(3 * len(image), -1, self.low_res, self.low_res) | |
| planes = self.upsampler(planes) | |
| planes = planes.view(3, len(image), *planes.shape[-3:]).permute(1, 0, 2, 3, 4).contiguous() | |
| return self.flame_decoder(planes) | |
| def predict(self, crop): | |
| # OpenCV BGR -> original PIL RGB, followed by the same Torch bicubic resize. | |
| image = torch.from_numpy(np.ascontiguousarray(crop[..., ::-1])).to(self.pos_embed.device) | |
| image = image.permute(2, 0, 1)[None] / 255.0 | |
| image = F.interpolate(image, (224, 224), mode='bicubic', align_corners=True).clamp(0, 1) | |
| output = self(image) | |
| return {key: output[key][0].cpu().numpy() for key in ['expression', 'pose', 'shape']} | |