convert_old_snerffast_checkpoint.py 7.05 KB
Newer Older
Nianchen Deng's avatar
sync    
Nianchen Deng committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import sys
import os
import configargparse
import argparse
import torch
import re
from pathlib import Path
from typing import Any

sys.path.append(os.path.abspath(sys.path[0] + '/../'))


parser = argparse.ArgumentParser()
parser.add_argument('input', type=str)
args = parser.parse_args()


class SphericalViewSynConfig(object):

    def __init__(self):
        self.name = 'default'
        self.COLOR = "rgb"

        # Net parameters
        self.NET_TYPE = 'msl'
        self.N_ENCODE_DIM = 10
        self.N_DIR_ENCODE = None
        self.NORMALIZE = False
        self.DEPTH_REF = False
        self.FC_PARAMS = {
            'nf': 256,
            'n_layers': 8,
            'skips': [],
            'activation': 'relu'
        }
        self.SAMPLE_PARAMS = {
            'spherical': True,
            'depth_range': (1, 50),
            'n_samples': 32,
            'perturb_sample': True,
            'lindisp': True,
            'inverse_r': True,
        }
        self.NERF_FINE_NET_PARAMS = {
            'enable': False,
            'nf': 256,
            'n_layers': 8,
            'additional_samples': 64
        }

    def from_id(self, id: str):
        id_splited = id.split('@')
        if len(id_splited) == 2:
            self.name = id_splited[0]
        segs = id_splited[-1].split('_')
        for i, seg in enumerate(segs):
            if seg.startswith('ffc'):  # Full-connected network parameters
                self.NERF_FINE_NET_PARAMS['nf'], self.NERF_FINE_NET_PARAMS['n_layers'] = (
                    int(str) for str in seg[3:].split('x'))
                self.NERF_FINE_NET_PARAMS['enable'] = True
                continue
            if seg.startswith('fs'):  # Number of samples
                try:
                    self.NERF_FINE_NET_PARAMS['additional_samples'] = int(seg[2:])
                    self.NERF_FINE_NET_PARAMS['enable'] = True
                    continue
                except ValueError:
                    pass
            if seg.startswith('fc'):  # Full-connected network parameters
                self.FC_PARAMS['nf'], self.FC_PARAMS['n_layers'] = (
                    int(str) for str in seg[2:].split('x'))
                continue
            if seg.startswith('skip'):  # Skip connection
                self.FC_PARAMS['skips'] = [int(str)
                                           for str in seg[4:].split(',')]
                continue
            if seg.startswith('*'):  # Activation
                self.FC_PARAMS['activation'] = seg[1:]
                continue
            if seg.startswith('ed'):  # Encode direction
                self.N_DIR_ENCODE = int(seg[2:])
                if self.N_DIR_ENCODE == 0:
                    self.N_DIR_ENCODE = None
                continue
            if seg.startswith('e'):  # Encode
                self.N_ENCODE_DIM = int(seg[1:])
                continue
            if seg.startswith('d'):  # Depth range
                try:
                    self.SAMPLE_PARAMS['depth_range'] = tuple(
                        float(str) for str in seg[1:].split('-'))
                    continue
                except ValueError:
                    pass
            if seg.startswith('s'):  # Number of samples
                try:
                    self.SAMPLE_PARAMS['n_samples'] = int(seg[1:])
                    continue
                except ValueError:
                    pass
            if seg.startswith('~'):  # Negative flags
                if seg.find('p') >= 0:
                    self.SAMPLE_PARAMS['perturb_sample'] = False
                if seg.find('l') >= 0:
                    self.SAMPLE_PARAMS['lindisp'] = False
                if seg.find('i') >= 0:
                    self.SAMPLE_PARAMS['inverse_r'] = False
                if seg.find('n') >= 0:
                    self.NORMALIZE = False
                if seg.find('d') >= 0:
                    self.DEPTH_REF = False
                continue
            if seg.startswith('+'):  # Positive flags
                if seg.find('p') >= 0:
                    self.SAMPLE_PARAMS['perturb_sample'] = True
                if seg.find('l') >= 0:
                    self.SAMPLE_PARAMS['lindisp'] = True
                if seg.find('i') >= 0:
                    self.SAMPLE_PARAMS['inverse_r'] = True
                if seg.find('n') >= 0:
                    self.NORMALIZE = True
                if seg.find('d') >= 0:
                    self.DEPTH_REF = True
                continue
            if i == 0:  # NetType
                self.NET_TYPE, color_str = seg.split('-')
                self.COLOR = color_str

    def print(self):
        print('==== Config %s ====' % self.name)
        print('Net type: ', self.NET_TYPE)
        print('Encode dim: ', self.N_ENCODE_DIM)
        print('Normalize: ', self.NORMALIZE)
        print('Train with depth: ', self.DEPTH_REF)
        print('Support direction: ', False if self.N_DIR_ENCODE is None
              else f'encode to {self.N_DIR_ENCODE}')
        print('Full-connected network parameters:', self.FC_PARAMS)
        print('Sample parameters', self.SAMPLE_PARAMS)
        if self.NERF_FINE_NET_PARAMS['enable']:
            print('NeRF fine network parameters', self.NERF_FINE_NET_PARAMS)
        print('==========================')


def convert_snerffast(input_network_state: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
    output_model_state: dict[str, torch.Tensor] = {}
    for key, value in input_network_state.items():
        key = re.sub("mlp_(\d+)\.core\.layer(\d+)\.net\.0\.(\w+)",
                     "core.subnets.\\1.field.net.layers.\\2.net.0.\\3", key)
        key = re.sub("mlp_(\d+)\.density_out\.net\.(\w+)",
                     "core.subnets.\\1.density_decoder.net.net.0.\\2", key)
        key = re.sub("mlp_(\d+)\.color_out\.net\.(\w+)",
                     "core.subnets.\\1.color_decoder.net.net.0.\\2", key)
        output_model_state[key] = value
    return output_model_state


ckpt_path = Path(args.input)
expdir = ckpt_path.parent
config_id = expdir.name
ckpt_epochs = int(re.match("model-epoch_(\d+)", ckpt_path.stem).group(1))

config = SphericalViewSynConfig()
config.from_id(config_id)
input_checkpoint: dict[str, Any] = torch.load(ckpt_path)

output_model_state = convert_snerffast(input_checkpoint["model"])
config.print()
print(f"Epochs: {ckpt_epochs}")

output_args = {
    "model": "FsNeRF",
    "model_args": {
        "color": "rgb",
        "n_samples": config.SAMPLE_PARAMS["n_samples"],
        "n_fields": int(config.NET_TYPE[9:]),
        "depth": config.FC_PARAMS["n_layers"],
        "width": config.FC_PARAMS["nf"],
        "skips": config.FC_PARAMS["skips"],
        "act": config.FC_PARAMS["activation"],
        "ln": False,
        "xfreqs": config.N_ENCODE_DIM,
        "raw_noise_std": 0.,
        "near": config.SAMPLE_PARAMS["depth_range"][0],
        "far": config.SAMPLE_PARAMS["depth_range"][1],
        "white_bg": False,
        "coord": "dx"
    },
    "trainer": None
}

output_path = expdir / f"checkpoint_{ckpt_epochs}.tar"
torch.save({
    "args": output_args,
    "states": {
        "model": output_model_state
    }
}, output_path)
print(f"Checkpoint is saved to {output_path}")