lib.py 12.3 KB
Newer Older
J
Jeff Wang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2017 VisualDL Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =======================================================================

O
Oraoto 已提交
16
from __future__ import absolute_import
Y
Yan Chunwei 已提交
17
import sys
18
import time
走神的阿圆's avatar
走神的阿圆 已提交
19
import os
走神的阿圆's avatar
走神的阿圆 已提交
20 21
import io
import csv
走神的阿圆's avatar
走神的阿圆 已提交
22
from functools import partial
S
superjom 已提交
23
import numpy as np
24
from visualdl.server.log import logger
走神的阿圆's avatar
走神的阿圆 已提交
25
from visualdl.io import bfile
26
from visualdl.utils.string_util import encode_tag, decode_tag
走神的阿圆's avatar
走神的阿圆 已提交
27
from visualdl.component import components
28

S
superjom 已提交
29

走神的阿圆's avatar
走神的阿圆 已提交
30 31
MODIFY_PREFIX = {}
MODIFIED_RUNS = []
走神的阿圆's avatar
走神的阿圆 已提交
32 33
EMBEDDING_NAME = {}
embedding_names = []
走神的阿圆's avatar
走神的阿圆 已提交
34 35


走神的阿圆's avatar
走神的阿圆 已提交
36 37 38 39
def s2ms(timestamp):
    return timestamp * 1000 if timestamp < 2000000000 else timestamp


40
def get_components(log_reader):
41 42 43
    components = log_reader.components(update=True)
    components.add('graph')
    return list(components)
S
superjom 已提交
44

S
superjom 已提交
45

46
def get_runs(log_reader):
走神的阿圆's avatar
走神的阿圆 已提交
47 48 49 50 51 52 53
    runs = []
    for item in log_reader.runs():
        if item in log_reader.tags2name:
            runs.append(log_reader.tags2name[item])
        else:
            runs.append(item)
    return runs
54 55


56 57
def get_tags(log_reader):
    return log_reader.tags()
S
superjom 已提交
58 59


60 61 62 63 64 65 66 67 68
def get_logs(log_reader, component):
    all_tag = log_reader.data_manager.get_reservoir(component).keys
    tags = {}
    for item in all_tag:
        index = item.rfind('/')
        run = item[0:index]
        tag = encode_tag(item[index + 1:])
        if run in tags.keys():
            tags[run].append(tag)
69
        else:
70
            tags[run] = [tag]
走神的阿圆's avatar
走神的阿圆 已提交
71 72 73
        if run not in log_reader.tags2name.keys():
            log_reader.tags2name[run] = run
            log_reader.name2tags[run] = run
走神的阿圆's avatar
走神的阿圆 已提交
74 75 76 77 78 79 80
    fake_tags = {}
    for key, value in tags.items():
        if key in log_reader.tags2name:
            fake_tags[log_reader.tags2name[key]] = value
        else:
            fake_tags[key] = value

走神的阿圆's avatar
走神的阿圆 已提交
81 82 83 84 85
    run2tag = {'runs': [], 'tags': []}
    for run, tags in fake_tags.items():
        run2tag['runs'].append(run)
        run2tag['tags'].append(tags)

走神的阿圆's avatar
走神的阿圆 已提交
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
    run_prefix = os.getenv('VISUALDL_RUN_PREFIX')
    global MODIFY_PREFIX, MODIFIED_RUNS
    if component not in MODIFY_PREFIX:
        MODIFY_PREFIX.update({component: False})
    if run_prefix and not MODIFY_PREFIX[component]:
        MODIFY_PREFIX[component] = True
        temp_name2tags = log_reader.name2tags.copy()
        for key, value in temp_name2tags.items():
            if key in MODIFIED_RUNS:
                continue
            index = key.find(run_prefix)
            if index != -1:
                temp_key = key[index+len(run_prefix):]

                log_reader.name2tags.pop(key)
                log_reader.name2tags.update({temp_key: value})

                log_reader.tags2name.pop(value)
                log_reader.tags2name.update({value: temp_key})

                run2tag['runs'][run2tag['runs'].index(key)] = temp_key
            else:
                temp_key = key

            MODIFIED_RUNS.append(temp_key)

走神的阿圆's avatar
走神的阿圆 已提交
112
    return run2tag
113 114


走神的阿圆's avatar
走神的阿圆 已提交
115 116
for name in components.keys():
    exec("get_%s_tags=partial(get_logs, component='%s')" % (name, name))
117 118


119
def get_scalar(log_reader, run, tag):
走神的阿圆's avatar
走神的阿圆 已提交
120
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
121 122 123
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("scalar").get_items(
        run, decode_tag(tag))
走神的阿圆's avatar
走神的阿圆 已提交
124
    results = [[s2ms(item.timestamp), item.id, item.value] for item in records]
125
    return results
126 127


走神的阿圆's avatar
走神的阿圆 已提交
128 129 130 131 132 133 134 135 136 137 138 139
def get_scalar_data(log_reader, run, tag):
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
    log_reader.load_new_data()
    result = log_reader.get_log_data('scalar', run, tag)
    with io.StringIO() as fp:
        csv_writer = csv.writer(fp, delimiter='\t')
        csv_writer.writerow(['id', 'tag', 'timestamp', 'value'])
        csv_writer.writerows(result)
        result = fp.getvalue()
        return result


140
def get_image_tag_steps(log_reader, run, tag):
走神的阿圆's avatar
走神的阿圆 已提交
141
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
142 143 144 145 146
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("image").get_items(
        run, decode_tag(tag))
    result = [{
        "step": item.id,
走神的阿圆's avatar
走神的阿圆 已提交
147
        "wallTime": s2ms(item.timestamp)
148 149
    } for item in records]
    return result
150 151


152
def get_individual_image(log_reader, run, tag, step_index):
走神的阿圆's avatar
走神的阿圆 已提交
153
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
154 155 156 157
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("image").get_items(
        run, decode_tag(tag))
    return records[step_index].image.encoded_image_string
158 159


160
def get_audio_tag_steps(log_reader, run, tag):
走神的阿圆's avatar
走神的阿圆 已提交
161
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
162 163 164 165 166
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("audio").get_items(
        run, decode_tag(tag))
    result = [{
        "step": item.id,
走神的阿圆's avatar
走神的阿圆 已提交
167
        "wallTime": s2ms(item.timestamp)
168 169
    } for item in records]
    return result
170 171


172
def get_individual_audio(log_reader, run, tag, step_index):
走神的阿圆's avatar
走神的阿圆 已提交
173
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
174 175 176
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("audio").get_items(
        run, decode_tag(tag))
P
Peter Pan 已提交
177
    result = records[step_index].audio.encoded_audio_string
178
    return result
179 180


走神的阿圆's avatar
走神的阿圆 已提交
181
def get_pr_curve(log_reader, run, tag):
走神的阿圆's avatar
走神的阿圆 已提交
182
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
走神的阿圆's avatar
走神的阿圆 已提交
183 184 185 186 187 188 189 190
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("pr_curve").get_items(
        run, decode_tag(tag))
    results = []
    for item in records:
        pr_curve = item.pr_curve
        length = len(pr_curve.precision)
        num_thresholds = [float(v) / length for v in range(1, length + 1)]
走神的阿圆's avatar
走神的阿圆 已提交
191
        results.append([s2ms(item.timestamp),
走神的阿圆's avatar
走神的阿圆 已提交
192 193 194 195 196 197 198 199 200
                        item.id,
                        list(pr_curve.precision),
                        list(pr_curve.recall),
                        list(pr_curve.TP),
                        list(pr_curve.FP),
                        list(pr_curve.TN),
                        list(pr_curve.FN),
                        num_thresholds])
    return results
P
Peter Pan 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
 
    
def get_roc_curve(log_reader, run, tag):
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("roc_curve").get_items(
        run, decode_tag(tag))
    results = []
    for item in records:
        roc_curve = item.roc_curve
        length = len(roc_curve.tpr)
        num_thresholds = [float(v) / length for v in range(1, length + 1)]
        results.append([s2ms(item.timestamp),
                        item.id,
                        list(roc_curve.tpr),
                        list(roc_curve.fpr),
                        list(roc_curve.TP),
                        list(roc_curve.FP),
                        list(roc_curve.TN),
                        list(roc_curve.FN),
                        num_thresholds])
    return results
走神的阿圆's avatar
走神的阿圆 已提交
223 224 225


def get_pr_curve_step(log_reader, run, tag=None):
走神的阿圆's avatar
走神的阿圆 已提交
226
    fake_run = run
走神的阿圆's avatar
走神的阿圆 已提交
227
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
走神的阿圆's avatar
走神的阿圆 已提交
228
    run2tag = get_pr_curve_tags(log_reader)
走神的阿圆's avatar
走神的阿圆 已提交
229
    tag = run2tag['tags'][run2tag['runs'].index(fake_run)][0]
走神的阿圆's avatar
走神的阿圆 已提交
230 231 232
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("pr_curve").get_items(
        run, decode_tag(tag))
走神的阿圆's avatar
走神的阿圆 已提交
233
    results = [[s2ms(item.timestamp), item.id] for item in records]
走神的阿圆's avatar
走神的阿圆 已提交
234 235 236
    return results


P
Peter Pan 已提交
237 238 239 240 241 242 243 244 245 246 247 248
def get_roc_curve_step(log_reader, run, tag=None):
    fake_run = run
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
    run2tag = get_roc_curve_tags(log_reader)
    tag = run2tag['tags'][run2tag['runs'].index(fake_run)][0]
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("roc_curve").get_items(
        run, decode_tag(tag))
    results = [[s2ms(item.timestamp), item.id] for item in records]
    return results

  
走神的阿圆's avatar
走神的阿圆 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
def get_embeddings_list(log_reader):
    run2tag = get_logs(log_reader, 'embeddings')

    for run, _tags in zip(run2tag['runs'], run2tag['tags']):
        for tag in _tags:
            name = path = os.path.join(run, tag)
            if name in EMBEDDING_NAME:
                return embedding_names
            EMBEDDING_NAME.update({name: {'run': run, 'tag': tag}})
            records = log_reader.data_manager.get_reservoir("embeddings").get_items(
                run, decode_tag(tag))
            row_len = len(records[0].embeddings.embeddings)
            col_len = len(records[0].embeddings.embeddings[0].vectors)
            shape = [row_len, col_len]
            embedding_names.append({'name': name, 'shape': shape, 'path': path})
    return embedding_names


def get_embedding_labels(log_reader, name):
    run = EMBEDDING_NAME[name]['run']
    tag = EMBEDDING_NAME[name]['tag']
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("embeddings").get_items(
        run, decode_tag(tag))
    labels = []
    for item in records[0].embeddings.embeddings:
275 276 277 278 279
        labels.append(item.label)

    label_meta = records[0].embeddings.label_meta
    if label_meta:
        labels = [label_meta] + labels
走神的阿圆's avatar
走神的阿圆 已提交
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302

    with io.StringIO() as fp:
        csv_writer = csv.writer(fp, delimiter='\t')
        csv_writer.writerows(labels)
        labels = fp.getvalue()

    # labels = "\n".join(str(i) for i in labels)
    return labels


def get_embedding_tensors(log_reader, name):
    run = EMBEDDING_NAME[name]['run']
    tag = EMBEDDING_NAME[name]['tag']
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("embeddings").get_items(
        run, decode_tag(tag))
    vectors = []
    for item in records[0].embeddings.embeddings:
        vectors.append(item.vectors)
    vectors = np.array(vectors).flatten().astype(np.float32).tobytes()
    return vectors


303
def get_histogram(log_reader, run, tag):
走神的阿圆's avatar
走神的阿圆 已提交
304
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
305 306 307 308 309 310 311 312 313 314 315 316
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("histogram").get_items(
        run, decode_tag(tag))

    results = []
    for item in records:
        histogram = item.histogram
        hist = histogram.hist
        bin_edges = histogram.bin_edges
        histogram_data = []
        for index in range(len(hist)):
            histogram_data.append([bin_edges[index], bin_edges[index+1], hist[index]])
走神的阿圆's avatar
走神的阿圆 已提交
317
        results.append([s2ms(item.timestamp), item.id, histogram_data])
318 319 320 321

    return results


322 323 324
def get_graph(log_reader):
    result = b""
    if log_reader.model:
走神的阿圆's avatar
走神的阿圆 已提交
325 326
        with bfile.BFile(log_reader.model, 'rb') as bfp:
            result = bfp.read_file(log_reader.model)
327 328 329
    return result


330
def retry(ntimes, function, time2sleep, *args, **kwargs):
331
    """
332 333
    try to execute `function` `ntimes`, if exception catched, the thread will
    sleep `time2sleep` seconds.
334
    """
O
Oraoto 已提交
335
    for i in range(ntimes):
336 337
        try:
            return function(*args, **kwargs)
T
Thuan Nguyen 已提交
338
        except Exception:
339 340 341 342 343 344 345
            if i < ntimes-1:
                error_info = '\n'.join(map(str, sys.exc_info()))
                logger.error("Unexpected error: %s" % error_info)
                time.sleep(time2sleep)
            else:
                import traceback
                traceback.print_exc()
346

T
Thuan Nguyen 已提交
347

348 349 350 351 352 353 354 355 356
def cache_get(cache):
    def _handler(key, func, *args, **kwargs):
        data = cache.get(key)
        if data is None:
            logger.warning('update cache %s' % key)
            data = func(*args, **kwargs)
            cache.set(key, data)
            return data
        return data
T
Thuan Nguyen 已提交
357

358
    return _handler
J
Jeff Wang 已提交
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381


def simple_pca(x, dimension):
    """
    A simple PCA implementation to do the dimension reduction.
    """

    # Center the data.
    x -= np.mean(x, axis=0)

    # Computing the Covariance Matrix
    cov = np.cov(x, rowvar=False)

    # Get eigenvectors and eigenvalues from the covariance matrix
    eigvals, eigvecs = np.linalg.eig(cov)

    # Sort the eigvals from high to low
    order = np.argsort(eigvals)[::-1]

    # Drop the eigenvectors with low eigenvalues
    eigvecs = eigvecs[:, order[:dimension]]

    return np.dot(x, eigvecs)