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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
U
©r_¤?ã@sÊddlZddlZddlZddlZddlZddlmZddlmZddl    Z    ddl
m Z ddl m Z ddd    d
d gZgZd d„ZGd d„dƒZGdd„deƒZGdd    „d    eƒZGdd
„d
eƒZGdd „d ƒZdS)éN)Ú defaultdict)Úcontextmanageré)Ú PathManager)Ú HistoryBufferÚget_event_storageÚ
JSONWriterÚTensorboardXWriterÚCommonMetricPrinterÚ EventStoragecCsttƒstdƒ‚tdS)z¢
    Returns:
        The :class:`EventStorage` object that's currently being used.
        Throws an error if no :class:`EventStorage` is currently enabled.
    zOget_event_storage() has to be called inside a 'with EventStorage(...)' context!éÿÿÿÿ)ÚlenÚ_CURRENT_STORAGE_STACKÚAssertionError©rrú./utils/events.pyrs ÿþc@s eZdZdZdd„Zdd„ZdS)Ú EventWriterz`
    Base class for writers that obtain events from :class:`EventStorage` and process them.
    cCst‚dS©N)ÚNotImplementedError©ÚselfrrrÚwrite)szEventWriter.writecCsdSrrrrrrÚclose,szEventWriter.closeN)Ú__name__Ú
__module__Ú __qualname__Ú__doc__rrrrrrr$src@s*eZdZdZd
dd„Zdd„Zdd„Zd    S) ra
    Write scalars to a json file.
    It saves scalars as one json per line (instead of a big json) for easy parsing.
    Examples parsing such a json file:
    ::
        $ cat metrics.json | jq -s '.[0:2]'
        [
          {
            "data_time": 0.008433341979980469,
            "iteration": 20,
            "loss": 1.9228371381759644,
            "loss_box_reg": 0.050025828182697296,
            "loss_classifier": 0.5316952466964722,
            "loss_mask": 0.7236229181289673,
            "loss_rpn_box": 0.0856662318110466,
            "loss_rpn_cls": 0.48198649287223816,
            "lr": 0.007173333333333333,
            "time": 0.25401854515075684
          },
          {
            "data_time": 0.007216215133666992,
            "iteration": 40,
            "loss": 1.282649278640747,
            "loss_box_reg": 0.06222952902317047,
            "loss_classifier": 0.30682939291000366,
            "loss_mask": 0.6970193982124329,
            "loss_rpn_box": 0.038663312792778015,
            "loss_rpn_cls": 0.1471673548221588,
            "lr": 0.007706666666666667,
            "time": 0.2490077018737793
          }
        ]
        $ cat metrics.json | jq '.loss_mask'
        0.7126231789588928
        0.689423680305481
        0.6776131987571716
        ...
    écCst |d¡|_||_d|_dS)zý
        Args:
            json_file (str): path to the json file. New data will be appended if the file exists.
            window_size (int): the window size of median smoothing for the scalars whose
                `smoothing_hint` are True.
        Úar N)rÚopenÚ _file_handleÚ _window_sizeÚ _last_write)rZ    json_fileÚ window_sizerrrÚ__init__XszJSONWriter.__init__c    CsÆtƒ}ttƒ}| |j¡ ¡D]$\}\}}||jkr6q||||<qt| ¡ƒ}t    |ƒ|_| ¡D]*\}}||d<|j
  t j |ddd¡qb|j
 ¡zt |j
 ¡¡Wntk
rÀYnXdS)NÚ    iterationT)Z    sort_keysÚ
)rrÚdictÚlatest_with_smoothing_hintr!Úitemsr"ÚsortedÚkeysÚmaxr rÚjsonÚdumpsÚflushÚosÚfsyncÚfilenoÚAttributeError)    rÚstorageÚto_saveÚkÚvÚiterZ    all_itersÚitrZscalars_per_iterrrrrcs 
 
 
zJSONWriter.writecCs|j ¡dSr)r rrrrrrxszJSONWriter.closeN)r)rrrrr$rrrrrrr0s'
c@s2eZdZdZd eedœdd„Zdd„Zdd    „Zd
S) r    z2
    Write all scalars to a tensorboard file.
    r)Úlog_dirr#cKs*||_ddlm}||f|Ž|_d|_dS)a 
        Args:
            log_dir (str): the directory to save the output events
            window_size (int): the scalars will be median-smoothed by this window size
            kwargs: other arguments passed to `torch.utils.tensorboard.SummaryWriter(...)`
        r)Ú SummaryWriterr N)r!Ztorch.utils.tensorboardr;Ú_writerr")rr:r#Úkwargsr;rrrr$s zTensorboardXWriter.__init__c
CsÀtƒ}|j}| |j¡ ¡D]0\}\}}||jkr|j |||¡t||ƒ}q||_t|j    ƒdkrŒ|j    D]\}}}|j 
|||¡qh|  ¡t|j ƒdkr¼|j D]}    |jj f|    Žq | ¡dS)Nr)rr"r(r!r)r<Ú
add_scalarr,r Ú    _vis_dataZ    add_imageÚ clear_imagesÚ _histogramsZadd_histogram_rawÚclear_histograms)
rr4Znew_last_writer6r7r8Úimg_nameÚimgÚstep_numÚparamsrrrrŽs
 
zTensorboardXWriter.writecCst|dƒr|j ¡dS)Nr<)Úhasattrr<rrrrrr¨s
zTensorboardXWriter.closeN)r)    rrrrÚstrÚintr$rrrrrrr    |s c@s eZdZdZdd„Zdd„ZdS)r
aU
    Print **common** metrics to the terminal, including
    iteration time, ETA, memory, all losses, and the learning rate.
    It also applies smoothing using a window of 20 elements.
    It's meant to print common metrics in common ways.
    To print something in more customized ways, please implement a similar printer by yourself.
    cCst t¡|_||_d|_dS)zƒ
        Args:
            max_iter (int): the maximum number of iterations to train.
                Used to compute ETA.
        N)ÚloggingÚ    getLoggerrÚloggerÚ    _max_iterr")rÚmax_iterrrrr$¶s zCommonMetricPrinter.__init__c
Csætƒ}|j}z| d¡ d¡}Wntk
r8d}YnXd}zP| d¡ ¡}| d¡ d¡|j|}|jd|ddt    t
j t |ƒdƒ}Wnttk
rd}|j dk    rðt ¡|j d    ||j d
}||j|}t    t
j t |ƒdƒ}|t ¡f|_ YnXzd  | d ¡ ¡¡}Wntk
r6d }YnXtj ¡rXtj ¡dd}    nd}    |j dj|rxd|›dnd|d dd„| ¡ ¡Dƒ¡|dk    rªd |¡nd|dk    rÀd |¡nd||    dk    rØd |    ¡ndd¡dS)NÚ    data_timerÚtimeéèÚ eta_secondsF©Úsmoothing_hint)Úsecondsrrz{:.2e}ÚlrzN/Ag@zA {eta}iter: {iter}  {losses}  {time}{data_time}lr: {lr}  {memory}zeta: z  ÚcSs*g|]"\}}d|krd || d¡¡‘qS)Úlossz
{}: {:.4g}r)ÚformatÚmedian)Ú.0r6r7rrrÚ
<listcomp>ìsþz-CommonMetricPrinter.write.<locals>.<listcomp>ztime: {:.4f}  zdata_time: {:.4f}  zmax_mem: {:.0f}M)Úetar8ÚlossesrPrOrVÚmemory)rr8ÚhistoryÚavgÚKeyErrorZ
global_avgrZrMÚ
put_scalarrHÚdatetimeÚ    timedeltarIr"rPÚ perf_counterrYÚlatestÚtorchÚcudaÚ is_availableÚmax_memory_allocatedrLÚinfoÚjoinÚ    historiesr))
rr4r%rOZ
eta_stringZ    iter_timerRZestimate_iter_timerVZ
max_mem_mbrrrrÀsV
 
 ÿ
 
þÿóÿzCommonMetricPrinter.writeN)rrrrr$rrrrrr
­s
c@sºeZdZdZd,dd„Zdd„Zd-dd    „Zdd
œd d „Zd.dd„Zdd„Z    dd„Z
dd„Z d/dd„Z dd„Z dd„Zedd„ƒZedd „ƒZd!d"„Zd#d$„Zed%d&„ƒZd'd(„Zd)d*„Zd+S)0r z§
    The user-facing class that provides metric storage functionalities.
    In the future we may add support for storing / logging other types of data if needed.
    rcCs2ttƒ|_i|_i|_||_d|_g|_g|_dS)zX
        Args:
            start_iter (int): the iteration number to start with
        rWN)    rrÚ_historyÚ_smoothing_hintsÚ_latest_scalarsÚ_iterÚ_current_prefixr?rA)rZ
start_iterrrrr$s
zEventStorage.__init__cCs|j |||jf¡dS)a:
        Add an `img_tensor` associated with `img_name`, to be shown on
        tensorboard.
        Args:
            img_name (str): The name of the image to put into tensorboard.
            img_tensor (torch.Tensor or numpy.array): An `uint8` or `float`
                Tensor of shape `[channel, height, width]` where `channel` is
                3. The image format should be RGB. The elements in img_tensor
                can either have values in [0, 1] (float32) or [0, 255] (uint8).
                The `img_tensor` will be visualized in tensorboard.
        N)r?Úappendrr)rrCZ
img_tensorrrrÚ    put_image s zEventStorage.put_imageTcCst|j|}|j|}t|ƒ}| ||j¡||jf|j|<|j |¡}|dk    rf||ksptd     |¡ƒ‚n
||j|<dS)a
        Add a scalar `value` to the `HistoryBuffer` associated with `name`.
        Args:
            smoothing_hint (bool): a 'hint' on whether this scalar is noisy and should be
                smoothed when logged. The hint will be accessible through
                :meth:`EventStorage.smoothing_hints`.  A writer may ignore the hint
                and apply custom smoothing rule.
                It defaults to True because most scalars we save need to be smoothed to
                provide any useful signal.
        Nz2Scalar {} was put with a different smoothing_hint!)
rsroÚfloatÚupdaterrrqrpÚgetrrY)rÚnameÚvaluerTr`Z existing_hintrrrrcs
 
 ÿþzEventStorage.put_scalarrScKs&| ¡D]\}}|j|||dqdS)z©
        Put multiple scalars from keyword arguments.
        Examples:
            storage.put_scalars(loss=my_loss, accuracy=my_accuracy, smoothing_hint=True)
        rSN)r)rc)rrTr=r6r7rrrÚ put_scalars4szEventStorage.put_scalarsrQc     Cs–| ¡ ¡| ¡ ¡}}tj||d}tj|||dtjd}t|||t|ƒt    | 
¡ƒt    t 
|d¡ƒ|dd…  ¡|  ¡|j d    }|j  |¡dS)a9
        Create a histogram from a tensor.
        Args:
            hist_name (str): The name of the histogram to put into tensorboard.
            hist_tensor (torch.Tensor): A Tensor of arbitrary shape to be converted
                into a histogram.
            bins (int): Number of histogram bins.
        )Úbinsr)ÚstartÚendZstepsÚdtypeéN)    ÚtagÚminr,ÚnumÚsumZ sum_squaresZ bucket_limitsZ bucket_countsZ global_step)r‚Úitemr,rhÚhistcÚlinspaceÚfloat32r'r rvr„ÚtolistrrrArt)    rZ    hist_nameZ hist_tensorr|Zht_minZht_maxZ hist_countsZ
hist_edgesZ hist_paramsrrrÚ put_histogram=s    
÷ zEventStorage.put_histogramcCs(|j |d¡}|dkr$td |¡ƒ‚|S)zQ
        Returns:
            HistoryBuffer: the scalar history for name
        Nz#No history metric available for {}!)rorxrbrY)rryÚretrrrr`ZszEventStorage.historycCs|jS)ze
        Returns:
            dict[name -> HistoryBuffer]: the HistoryBuffer for all scalars
        )rorrrrrndszEventStorage.historiescCs|jS)z³
        Returns:
            dict[str -> (float, int)]: mapping from the name of each scalar to the most
                recent value and the iteration number its added.
        )rqrrrrrgkszEventStorage.latestrcCsFi}|j ¡D]2\}\}}|j|r4|j| |¡n||f||<q|S)a'
        Similar to :meth:`latest`, but the returned values
        are either the un-smoothed original latest value,
        or a median of the given window_size,
        depend on whether the smoothing_hint is True.
        This provides a default behavior that other writers can use.
        )rqr)rprorZ)rr#Úresultr6r7r9rrrr(ss þ
z'EventStorage.latest_with_smoothing_hintcCs|jS)z•
        Returns:
            dict[name -> bool]: the user-provided hint on whether the scalar
                is noisy and needs smoothing.
        )rprrrrÚsmoothing_hintsƒszEventStorage.smoothing_hintscCs|jd7_dS)zþ
        User should call this function at the beginning of each iteration, to
        notify the storage of the start of a new iteration.
        The storage will then be able to associate the new data with the
        correct iteration number.
        rN©rrrrrrÚstep‹szEventStorage.stepcCs|jSrrŽrrrrr8”szEventStorage.itercCs|jSrrŽrrrrr%˜szEventStorage.iterationcCst |¡|Sr)rrtrrrrÚ    __enter__s
zEventStorage.__enter__cCstd|kst‚t ¡dS)Nr )rrÚpop)rÚexc_typeÚexc_valÚexc_tbrrrÚ__exit__¡szEventStorage.__exit__ccs&|j}| d¡d|_dV||_dS)z‘
        Yields:
            A context within which all the events added to this storage
            will be prefixed by the name scope.
        ú/N)rsÚrstrip)rryZ
old_prefixrrrÚ
name_scope¥szEventStorage.name_scopecCs
g|_dS)zˆ
        Delete all the stored images for visualization. This should be called
        after images are written to tensorboard.
        N)r?rrrrr@±szEventStorage.clear_imagescCs
g|_dS)z
        Delete all the stored histograms for visualization.
        This should be called after histograms are written to tensorboard.
        N)rArrrrrB¸szEventStorage.clear_histogramsN)r)T)rQ)r)rrrrr$rurcr{rŠr`rnrgr(rrÚpropertyr8r%rr•rr˜r@rBrrrrr ús,
 
    
 
 
    
 
 
)rdr-rJr0rPÚ collectionsrÚ
contextlibrrhÚfile_iorZhistory_bufferrÚ__all__rrrrr    r
r rrrrÚ<module>s,    û  L1M