File size: 7,397 Bytes
72e760c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Retain bit-identical inference tensors from pinned author training checkpoints.

CPU serialization only; no model construction, inference, or quantization.
"""
import argparse
from collections import OrderedDict
import copy
import ctypes
import gc
import fcntl
import hashlib
import json
from pathlib import Path
import pickle
import types

ROOT=Path(__file__).resolve().parents[1]


def sha(path):
    h=hashlib.sha256()
    with path.open('rb') as f:
        for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)
    return h.hexdigest()


class CallbackMetadata:
    """Unused training callback key, never instantiated or executed."""


class TrainingMetadataUnpickler(pickle.Unpickler):
    def find_class(self,module,name):
        if name=='ModelCheckpoint' and module.startswith(('lightning.','pytorch_lightning.')):
            return CallbackMetadata
        return super().find_class(module,name)


def same(before,after):
    import torch
    if torch.is_tensor(before):
        assert torch.is_tensor(after) and before.shape==after.shape and before.dtype==after.dtype
        assert before.stride()==after.stride()
        assert torch.equal(before,after)
        for tensor in [before,after]:
            contiguous=tensor.contiguous()
            digest=hashlib.sha256(ctypes.string_at(contiguous.data_ptr(),contiguous.numel()*contiguous.element_size())).hexdigest()
            if tensor is before:expected_digest=digest
            else:assert digest==expected_digest
        return 1
    if isinstance(before,dict):
        assert list(before)==list(after)
        return sum(same(before[k],after[k]) for k in before)
    if isinstance(before,(list,tuple)):
        assert type(before)==type(after) and len(before)==len(after)
        return sum(same(a,b) for a,b in zip(before,after))
    assert before==after
    return 0


def deduplicate(value,seen,stats):
    """Share archive storage only for tensors proven equal in shape/dtype/value."""
    import torch
    if torch.is_tensor(value):
        if value.device.type!='cpu' or not value.is_contiguous():return value
        size=value.numel()*value.element_size()
        key=(str(value.dtype),tuple(value.shape),value.stride(),
             hashlib.sha256(ctypes.string_at(value.data_ptr(),size)).hexdigest())
        if key in seen:
            assert torch.equal(value,seen[key])
            stats['identical_tensor_references_shared']+=1
            stats['logical_duplicate_bytes']+=size
            return seen[key]
        seen[key]=value;return value
    if isinstance(value,dict):
        result=type(value)((k,deduplicate(v,seen,stats)) for k,v in value.items())
        if hasattr(value,'_metadata'):result._metadata=copy.deepcopy(value._metadata)
        return result
    if isinstance(value,list):return [deduplicate(v,seen,stats) for v in value]
    if isinstance(value,tuple):return tuple(deduplicate(v,seen,stats) for v in value)
    return value


def main():
    parser=argparse.ArgumentParser();parser.add_argument('name',choices=['dystream_motion','dystream_renderer']);args=parser.parse_args()
    (ROOT/'.cache').mkdir(exist_ok=True)
    lock=(ROOT/'.cache/compact_dystream.lock').open('a')
    fcntl.flock(lock,fcntl.LOCK_EX)
    import torch
    assert not torch.cuda.is_initialized()
    torch.set_num_threads(2)
    config_path=ROOT/'configs/weights.json';config=json.loads(config_path.read_text())
    spec=next(s for s in config['hf'] if s['name']==args.name)
    target=ROOT/'weights/dystream'/('last.ckpt' if args.name=='dystream_motion' else 'renderer.ckpt')
    previous=ROOT/'provenance'/f'{args.name}_INFERENCE_ONLY.json'
    if previous.is_file():
        record=json.loads(previous.read_text())
        if record.get('tensor_exact') and target.is_file() and sha(target)==record['sha256']:
            print('Already verified inference-only checkpoint',args.name,flush=True);return
    source=ROOT/'.cache/original_checkpoints'/args.name/'author.ckpt'
    if not source.is_file():
        original=ROOT/spec['destination']
        assert original.stat().st_size==spec['size'] and sha(original)==spec['sha256']
        source.parent.mkdir(parents=True,exist_ok=True);original.replace(source)
    assert source.stat().st_size==spec['size'] and sha(source)==spec['sha256']
    # The original SHA256 is verified before the author's pickle is read.
    module=types.ModuleType('verified_training_checkpoint_pickle')
    module.Unpickler=TrainingMetadataUnpickler;module.load=pickle.load
    original=torch.load(source,map_location='cpu',mmap=True,weights_only=False,pickle_module=module)
    if args.name=='dystream_motion':
        assert set(original['ema_state'])=={'decay','num_updates','shadow_params','collected_params'}
        ema=copy.copy(original['ema_state']);ema['collected_params']=None
        kept={'state_dict':original['state_dict'],'ema_state':ema}
        removed=['optimizer_states','loops','callbacks','lr_schedulers','ema_state.collected_params']
    else:
        prefixes=('motion_encoder.','face_encoder.','flow_estimator.','face_generator.')
        state=original['state_dict']
        kept_state=OrderedDict((k,v) for k,v in state.items() if k.startswith(prefixes))
        assert all(any(k.startswith(p) for k in kept_state) for p in prefixes)
        if hasattr(state,'_metadata'):
            kept_state._metadata={k:v for k,v in state._metadata.items() if not k or any(k==p[:-1] or k.startswith(p) for p in prefixes)}
        kept={'state_dict':kept_state}
        removed=['optimizer_states','loops','callbacks','lr_schedulers','discriminator','facial_discriminator','criterion_vgg']
    # tensor dtype, storage values and EMA parameter order are preserved.
    stats={'identical_tensor_references_shared':0,'logical_duplicate_bytes':0}
    packed=deduplicate(kept,{},stats)
    target.parent.mkdir(parents=True,exist_ok=True);temp=target.with_suffix('.ckpt.part')
    torch.save(packed,temp)
    roundtrip=torch.load(temp,map_location='cpu',mmap=True,weights_only=True)
    count=same(kept,roundtrip)
    digest=sha(temp);size=temp.stat().st_size
    del roundtrip,packed,kept,original;gc.collect();temp.replace(target)
    spec['destination']=str(source.relative_to(ROOT))
    download_receipt=ROOT/'provenance'/f'{args.name}_DOWNLOADED.json'
    if download_receipt.is_file():
        record=json.loads(download_receipt.read_text())
        record.update(original_download_path=record['path'],path=str(source.relative_to(ROOT)),
                      excluded_original_training_checkpoint=True)
        download_receipt.write_text(json.dumps(record,indent=2)+'\n')
    derived=dict(name=args.name,path=str(target.relative_to(ROOT)),bytes=size,sha256=digest,
        source_repository=spec['repo'],source_revision=spec['revision'],source_file=spec['file'],
        source_sha256=spec['sha256'],source_bytes=spec['size'],verified_tensors=count,
        tensor_exact=True,dtype_changed=False,quantized=False,model_inference_started=False,
        removed_training_only=removed,lossless_storage_deduplication=stats)
    derivatives=config.setdefault('inference_derivatives',{})
    derivatives[args.name]=derived
    config_path.write_text(json.dumps(config,indent=2)+'\n')
    (ROOT/'provenance'/f'{args.name}_INFERENCE_ONLY.json').write_text(json.dumps(derived,indent=2)+'\n')
    print(json.dumps(derived),flush=True)


if __name__=='__main__':main()