Scheaven
2021-09-18 291deeb1fcf45dbf39a24aa72a213ff3fd6b3405
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
B
ÿŽŠ`i7ã@sèddlZddlZddlZddlZddlmZddlmZddlZddl    Z    ddl
m Z ddl m Z ddlmZmZddlmZGdd    „d    eƒZGd
d „d ƒZed œd d„Zed œdd„Zejedœdd„Zed œdd„Zedœdd„ZdS)éN)Ú defaultdict)ÚAny)Úcolored)Ú DataParallelÚDistributedDataParallelé)Ú PathManagerc@s²eZdZdZd%ddœejeeedœdd„Z    ee
dœd    d
„Z ed œd d „Z dd„Z dd„Zdd„Zddœeedœdd„Zedœdd„Zedœdd„Zedœdd „Ze
d!œd"d#„Zd$S)&Ú Checkpointerz^
    A checkpointer that can save/load model as well as extra checkpointable
    objects.
    ÚT)Ú save_to_disk)ÚmodelÚsave_dirr ÚcheckpointablescKsBt|ttfƒr|j}||_t |¡|_t t    ¡|_
||_ ||_ dS)a
        Args:
            model (nn.Module): model.
            save_dir (str): a directory to save and find checkpoints.
            save_to_disk (bool): if True, save checkpoint to disk, otherwise
                disable saving for this checkpointer.
            checkpointables (object): any checkpointable objects, i.e., objects
                that have the `state_dict()` and `load_state_dict()` method. For
                example, it can be used like
                `Checkpointer(model, "dir", optimizer=optimizer)`.
        N) Ú
isinstancerrÚmoduler ÚcopyrÚloggingÚ    getLoggerÚ__name__Úloggerr r )Úselfr r r r©rú./utils/checkpoint.pyÚ__init__s  zCheckpointer.__init__)ÚnameÚkwargsc        KsÆ|jr |jsdSi}|j ¡|d<x"|j ¡D]\}}| ¡||<q.W| |¡d |¡}tj     
|j|¡}tj      |¡|ks‚t |ƒ‚|j  d |¡¡t |d¡}t ||¡WdQRX| |¡dS)z¬
        Dump model and checkpointables to a file.
        Args:
            name (str): name of the file.
            kwargs (dict): extra arbitrary data to save.
        Nr z{}.pthzSaving checkpoint to {}Úwb)r r r Ú
state_dictrÚitemsÚupdateÚformatÚosÚpathÚjoinÚbasenameÚAssertionErrorrÚinforÚopenÚtorchÚsaveÚtag_last_checkpoint)    rrrÚdataÚkeyÚobjr$Ú    save_fileÚfrrrr)5s 
 
zCheckpointer.save)r"cCs²|s|j d¡iS|j d |¡¡tj |¡sVt |¡}tj |¡sVtd |¡ƒ‚|     |¡}| 
|¡xB|j   ¡D]4\}}||krv|j d ||¡¡|  | |¡¡qvW|S)aÐ
        Load from the given checkpoint. When path points to network file, this
        function has to be called on all ranks.
        Args:
            path (str): path or url to the checkpoint. If empty, will not load
                anything.
        Returns:
            dict:
                extra data loaded from the checkpoint that has not been
                processed. For example, those saved with
                :meth:`.save(**extra_data)`.
        z0No checkpoint found. Training model from scratchzLoading checkpoint from {}zCheckpoint {} not found!zLoading {} from {})rr&r r!r"ÚisfilerÚget_local_pathr%Ú
_load_fileÚ _load_modelrrÚload_state_dictÚpop)rr"Ú
checkpointr,r-rrrÚloadMs  
 
 
zCheckpointer.loadcCstj |jd¡}t |¡S)za
        Returns:
            bool: whether a checkpoint exists in the target directory.
        Úlast_checkpoint)r!r"r#r rÚexists)rr.rrrÚhas_checkpointoszCheckpointer.has_checkpointc    Cs^tj |jd¡}y(t |d¡}| ¡ ¡}WdQRXWntk
rLdSXtj |j|¡S)z[
        Returns:
            str: The latest checkpoint file in target directory.
        r8ÚrNr
)    r!r"r#r rr'ÚreadÚstripÚIOError)rr.r/Z
last_savedrrrÚget_checkpoint_filewsz Checkpointer.get_checkpoint_filecs‡fdd„t ˆj¡Dƒ}|S)z}
        Returns:
            list: All available checkpoint files (.pth files) in target
                directory.
        cs<g|]4}t tj ˆj|¡¡r| d¡rtj ˆj|¡‘qS)z.pth)rr0r!r"r#r Úendswith)Ú.0Úfile)rrrú
<listcomp>sz9Checkpointer.get_all_checkpoint_files.<locals>.<listcomp>)rÚlsr )rZall_model_checkpointsr)rrÚget_all_checkpoint_files†s
z%Checkpointer.get_all_checkpoint_files)Úresume)r"rFcCs|r| ¡r| ¡}| |¡S)a©
        If `resume` is True, this method attempts to resume from the last
        checkpoint, if exists. Otherwise, load checkpoint from the given path.
        This is useful when restarting an interrupted training job.
        Args:
            path (str): path to the checkpoint.
            resume (bool): if True, resume from the last checkpoint if it exists.
        Returns:
            same as :meth:`load`.
        )r:r?r7)rr"rFrrrÚresume_or_load”s zCheckpointer.resume_or_load)Úlast_filename_basenamec    Cs6tj |jd¡}t |d¡}| |¡WdQRXdS)z…
        Tag the last checkpoint.
        Args:
            last_filename_basename (str): the basename of the last filename.
        r8ÚwN)r!r"r#r rr'Úwrite)rrHr.r/rrrr*£sz Checkpointer.tag_last_checkpoint)r/cCstj|t d¡dS)a
        Load a checkpoint file. Can be overwritten by subclasses to support
        different formats.
        Args:
            f (str): a locally mounted file path.
        Returns:
            dict: with keys "model" and optionally others that are saved by
                the checkpointer dict["model"] must be a dict which maps strings
                to torch.Tensor or numpy arrays.
        Úcpu)Ú map_location)r(r7Údevice)rr/rrrr2­s zCheckpointer._load_file)r6cCsÎ| d¡}| |¡t|dƒ|j ¡}x`t| ¡ƒD]P}||kr6t||jƒ}t||jƒ}||kr6|j     
d  |||¡¡| |¡q6W|jj |dd}|j r²|j     t|j ƒ¡|jrÊ|j     t|jƒ¡dS)z~
        Load weights from a checkpoint.
        Args:
            checkpoint (Any): checkpoint contains the weights.
        r zmodule.zA'{}' has shape {} in the checkpoint but {} in the model! Skipped.F)ÚstrictN)r5Ú_convert_ndarray_to_tensorÚ_strip_prefix_if_presentr rÚlistÚkeysÚtupleÚshaperÚwarningr r4Ú missing_keysr&Úget_missing_parameters_messageÚunexpected_keysÚ!get_unexpected_parameters_message)rr6Zcheckpoint_state_dictZmodel_state_dictÚkZ shape_modelZshape_checkpointÚ incompatiblerrrr3ºs*
 
 
 
 
 zCheckpointer._load_model)rcCshxbt| ¡ƒD]R}||}t|tjƒsFt|tjƒsFtd |t    |ƒ¡ƒ‚t|tjƒst 
|¡||<qWdS)z«
        In-place convert all numpy arrays in the state_dict to torch tensor.
        Args:
            state_dict (dict): a state-dict to be loaded to the model.
        z,Unsupported type found in checkpoint! {}: {}N) rQrRrÚnpÚndarrayr(ÚTensorÚ
ValueErrorr ÚtypeÚ
from_numpy)rrrZÚvrrrrOãs    
 z'Checkpointer._convert_ndarray_to_tensorN)r
)rÚ
__module__Ú __qualname__Ú__doc__ÚnnÚModuleÚstrÚboolÚobjectrÚdictr)r7r:r?rErGr*r2rr3rOrrrrr    s"
 )r    c@sDeZdZdZd eeedœdd„Zeedœdd„Zeed    œd
d „Z    dS) ÚPeriodicCheckpointerzÔ
    Save checkpoints periodically. When `.step(iteration)` is called, it will
    execute `checkpointer.save` on the given checkpointer, if iteration is a
    multiple of period or if `max_iter` is reached.
    N)Ú checkpointerÚperiodÚmax_itercCs||_t|ƒ|_||_dS)a<
        Args:
            checkpointer (Any): the checkpointer object used to save
            checkpoints.
            period (int): the period to save checkpoint.
            max_iter (int): maximum number of iterations. When it is reached,
                a checkpoint named "model_final" will be saved.
        N)rmÚintrnro)rrmrnrorrrrs    
zPeriodicCheckpointer.__init__)Ú    iterationrcKsbt|ƒ}d|i}| |¡|d|jdkrB|jjd |¡f|Ž||jdkr^|jjd|ŽdS)a    
        Perform the appropriate action at the given iteration.
        Args:
            iteration (int): the current iteration, ranged in [0, max_iter-1].
            kwargs (Any): extra data to save, same as in
                :meth:`Checkpointer.save`.
        rqrrz model_{:07d}Ú model_finalN)rr)rprrnrmr)r ro)rrqrZadditional_staterrrÚsteps
zPeriodicCheckpointer.step)rrcKs|jj|f|ŽdS)a
        Same argument as :meth:`Checkpointer.save`.
        Use this method to manually save checkpoints outside the schedule.
        Args:
            name (str): file name.
            kwargs (Any): extra data to save, same as in
                :meth:`Checkpointer.save`.
        N)rmr))rrrrrrr) s    zPeriodicCheckpointer.save)N)
rrcrdrerrprrsrhr)rrrrrlús rl)rRcCs,t|ƒ}d}|d dd„| ¡Dƒ¡7}|S)zý
    Get a logging-friendly message to report parameter names (keys) that are in
    the model but not found in a checkpoint.
    Args:
        keys (list[str]): List of keys that were not found in the checkpoint.
    Returns:
        str: message.
    z1Some model parameters are not in the checkpoint:
Ú
css(|] \}}dt|t|ƒdƒVqdS)z  ÚblueN)rÚ _group_to_str)rArZrbrrrú    <genexpr>8sz1get_missing_parameters_message.<locals>.<genexpr>)Ú_group_checkpoint_keysr#r)rRÚgroupsÚmsgrrrrW,s
    rWcCs,t|ƒ}d}|d dd„| ¡Dƒ¡7}|S)zú
    Get a logging-friendly message to report parameter names (keys) that are in
    the checkpoint but not found in the model.
    Args:
        keys (list[str]): List of keys that were not found in the model.
    Returns:
        str: message.
    z:The checkpoint contains parameters not used by the model:
rtcss(|] \}}dt|t|ƒdƒVqdS)z  ZmagentaN)rrv)rArZrbrrrrwIsz4get_unexpected_parameters_message.<locals>.<genexpr>)rxr#r)rRryrzrrrrY=s     rY)rÚprefixcs¸t| ¡ƒ}t‡fdd„|Dƒƒs&dSx*|D]"}|tˆƒd…}| |¡||<q,Wy
|j}Wntk
rpYnDXx@t| ¡ƒD]0}t|ƒdkr’q€|tˆƒd…}| |¡||<q€WdS)z¡
    Strip the prefix in metadata, if any.
    Args:
        state_dict (OrderedDict): a state-dict to be loaded to the model.
        prefix (str): prefix.
    c3s$|]}t|ƒdkp| ˆ¡VqdS)rN)ÚlenÚ
startswith)rAr,)r{rrrwWsz+_strip_prefix_if_present.<locals>.<genexpr>Nr)ÚsortedrRÚallr|r5Ú    _metadataÚAttributeErrorrQ)rr{rRr,ZnewkeyÚmetadatar)r{rrPOs 
 
 rPcCsfttƒ}xX|D]P}| d¡}|dkrF|d|…||dd…g}}n
|g}}|| |¡qW|S)a.
    Group keys based on common prefixes. A prefix is the string up to the final
    "." in each key.
    Args:
        keys (list[str]): list of parameter names, i.e. keys in the model
            checkpoint dict.
    Returns:
        dict[list]: keys with common prefixes are grouped into lists.
    Ú.rNr)rrQÚrfindÚextend)rRryr,ÚposÚheadÚtailrrrrxps
 
 
"
rx)ÚgroupcCs:t|ƒdkrdSt|ƒdkr(d|dSdd |¡dS)z¼
    Format a group of parameter name suffixes into a loggable string.
    Args:
        group (list[str]): list of parameter name suffixes.
    Returns:
        str: formated string.
    rr
rrƒz.{z, Ú})r|r#)r‰rrrrv…s
   rv)Ú collectionsrrr!rÚtypingrÚnumpyr\r(Útorch.nnrfZ    termcolorrZtorch.nn.parallelrrÚfile_iorrjr    rlrQrWrYÚ OrderedDictrhrPrxrvrrrrÚ<module>s&     g2!