* joshim5 changes (width and height to WarpFrame wrapper) * match network output with action distribution via a linear layer only if necessary (#167) * support color vs. grayscale option in WarpFrame wrapper (#166) * support color vs. grayscale option in WarpFrame wrapper * Support color in other wrappers * Updated per Peters suggestions * fixing test failures * ppo2 with microbatches (#168) * pass microbatch_size to the model during construction * microbatch fixes and test (#169) * microbatch fixes and test * tiny cleanup * added assertions to the test * vpg-related fix * Peterz joshim5 subclass ppo2 model (#170) * microbatch fixes and test * tiny cleanup * added assertions to the test * vpg-related fix * subclassing the model to make microbatched version of model WIP * made microbatched model a subclass of ppo2 Model * flake8 complaint * mpi-less ppo2 (resolving merge conflict) * flake8 and mpi4py imports in ppo2/model.py * more un-mpying * merge master * updates to the benchmark viewer code + autopep8 (#184) * viz docs and syntactic sugar wip * update viewer yaml to use persistent volume claims * move plot_util to baselines.common, update links * use 1Tb hard drive for results viewer * small updates to benchmark vizualizer code * autopep8 * autopep8 * any folder can be a benchmark * massage games image a little bit * fixed --preload option in app.py * remove preload from run_viewer.sh * remove pdb breakpoints * update bench-viewer.yaml * fixed bug (#185) * fixed bug it's wrong to do the else statement, because no other nodes would start. * changed the fix slightly * Refactor her phase 1 (#194) * add monitor to the rollout envs in her RUN BENCHMARKS her * Slice -> Slide in her benchmarks RUN BENCHMARKS her * run her benchmark for 200 epochs * dummy commit to RUN BENCHMARKS her * her benchmark for 500 epochs RUN BENCHMARKS her * add num_timesteps to her benchmark to be compatible with viewer RUN BENCHMARKS her * add num_timesteps to her benchmark to be compatible with viewer RUN BENCHMARKS her * add num_timesteps to her benchmark to be compatible with viewer RUN BENCHMARKS her * disable saving of policies in her benchmark RUN BENCHMARKS her * run fetch benchmarks with ppo2 and ddpg RUN BENCHMARKS Fetch * run fetch benchmarks with ppo2 and ddpg RUN BENCHMARKS Fetch * launcher refactor wip * wip * her works on FetchReach * her runner refactor RUN BENCHMARKS Fetch1M * unit test for her * fixing warnings in mpi_average in her, skip test_fetchreach if mujoco is not present * pickle-based serialization in her * remove extra import from subproc_vec_env.py * investigating differences in rollout.py * try with old rollout code RUN BENCHMARKS her * temporarily use DummyVecEnv in cmd_util.py RUN BENCHMARKS her * dummy commit to RUN BENCHMARKS her * set info_values in rollout worker in her RUN BENCHMARKS her * bug in rollout_new.py RUN BENCHMARKS her * fixed bug in rollout_new.py RUN BENCHMARKS her * do not use last step because vecenv calls reset and returns obs after reset RUN BENCHMARKS her * updated buffer sizes RUN BENCHMARKS her * fixed loading/saving via joblib * dust off learning from demonstrations in HER, docs, refactor * add deprecation notice on her play and plot files * address comments by Matthias * 1.5 months of codegen changes (#196) * play with resnet * feed_dict version * coinrun prob and more stats * fixes to get_choices_specs & hp search * minor prob fixes * minor fixes * minor * alternative version of rl_algo stuff * pylint fixes * fix bugs, move node_filters to soup * changed how get_algo works * change how get_algo works, probably broke all tests * continue previous refactor * get eval_agent running again * fixing tests * fix tests * fix more tests * clean up cma stuff * fix experiment * minor changes to eval_agent to make ppo_metal use gpu * make dict space work * modify mac makefile to use conda * recurrent layers * play with bn and resnets * minor hp changes * minor * got rid of use_fb argument and jtft (joint-train-fine-tune) functionality built test phase directly into AlgoProb * make new rl algos generateable * pylint; start fixing tests * fixing tests * more test fixes * pylint * fix search * work on search * hack around infinite loop caused by scan * algo search fixes * misc changes for search expt * enable annealing, overriding options of Op * pylint fixes * identity op * achieve use_last_output through masking so it automatically works in other distributions * fix tests * minor * discrete * use_last_output to be just a preference, not a hard constraint * pred delay, pruning * require nontrivial inputs * aliases for get_sm * add probname to probs * fixes * small fixes * fix tests * fix tests * fix tests * minor * test scripts * dualgru network improvements * minor * work on mysterious bugs * rcall gpu-usage command for kube * use cache dir that’s not in code folder, so that it doesn’t get removed by rcall code rsync * add power mode to gpu usage * make sure train/test actually different * remove VR for now * minor fixes * simplify soln_db * minor * big refactor of mpi eda * improve mpieda for multitask * - get rid of timelimit hack - add __del__ to cleanup SubprocVecEnv * get multitask working better * fixes * working on atari, various * annotate ops with whether they’re parametrized * minor * gym version * rand atari prob * minor * SolnDb bugfix and name change * pyspy script * switch conv layers * fix roboschool/bullet3 * nenvs assertion * fix rand atari * get rid of blanket exception catching fix soln_db bug * fix rand_atari * dynamic routing as cmdline arg * slight modifications to test_mpi_map and pyspy-all * max_tries argument for run_until_successs * dedup option in train_mle * simplify soln_db * increase atari horizon for 1 experiment * start implementing reward increment * ent multiplier * create cc dsl other misc fixes * cc ops * q_func -> qs in rl_algos_cc.py * fix PredictDistr * rl_ops_cc fixes, MakeAction op * augment algo agent to support cc stuff * work on ddpg experiments * fix blocking temporarily change logger * allow layer scaling * pylint fixes * spawn_method * isolate ddpg hacks * improve pruning * use spawn for subproc * remove use of python -c in rcall * fix pylint warning * fix static * maybe fix local backend * switch to DummyVecEnv * making some fixes via pylint * pylint fixes * fixing tests * fix tests * fix tests * write scaffolding for SSL in Codegen * logger fix * fix error * add EMA op to sl_ops * save many changes * save * add upsampler * add sl ops, enhance state machine * get ssl search working — some gross hacking * fix session/graph issue * fix importing * work on mle * - scale embeddings in gru model - better exception handling in sl_prob - use emas for test/val - use non-contrib batch_norm layer * improve logging * option to average before dumping in logger * default arguments, etc * new ddpg and identity test * concat fix * minor * move realistic ssl stuff to third-party (underscore to dash) * fixes * remove realistic_ssl_evaluation * pylint fixes * use gym master * try again * pass around args without gin * fix tests * separate line to install gym * rename failing tests that should be ignored * add data aug * ssl improvements * use fixed time limit * try to fix baselines tests * add score_floor, max_walltime, fiddle with lr decay * realistic_ssl * autopep8 * various ssl - enable blocking grad for simplification - kl - multiple final prediction * fix pruning * misc ssl stuff * bring back linear schedule, don’t use allgather for collecting stats (i’ve been getting nondeterministic errors from the old code) * save/load weights in SSL, big stepsize * cleanup SslProb * fix * get rid of kl coef * fix simplification, lower lr * search over hps * minor fixes * minor * static analysis * move files and rename things for improved consistency. still broken, and just saving before making nontrivial changes * various * make tests pass * move coinrun_train to codegen since it depends on codegen * fixes * pylint fixes * improve tests fix some things * improve tests * lint * fix up db_info.py, tests * mostly restore master version of envs directory, except for makefile changes * fix tests * improve printing * minor fixes * fix fixmes * pruning test * fixes * lint * write new test that makes tf graphs of random algos; fix some bugs it caught * add —delete flag to rcall upload-code command * lint * get cifar10 lazily for testing purposes * disable codegen ci tests for now * clean up rl_ops * rename spec classes * td3 with identity test * identity tests without gin files * remove gin.configurable from AlgoAgent * comments about reduction in rl_ops_cc * address @pzhokhov comments * fix tests * more linting * better tests * clean up filtering a bit * fix concat * delayed logger configuration (#208) * delayed logger configuration * fix typo * setters and getters for Logger.DEFAULT as well * do away with fancy property stuff - unable to get it to work with class level methods * grammar and spaces * spaces * use get_current function instead of reading Logger.CURRENT * autopep8 * disable mpi in subprocesses (#213) * lazy_mpi load * cleanups * more lazy mpi * don't pretend that class is a module, just use it as a class * mass-replace mpi4py imports * flake8 * fix previous lazy_mpi imports * silly recursion * try os.environ hack * better prefix test, work with mpich * restored MPI imports * removed commented import in test_with_mpi * restored codegen from master * remove lazy mpi * restored changes from rl-algs * remove extra files * address Chris' comments * use spawn for shmem vec env as well (#2) (#219) * lazy_mpi load * cleanups * more lazy mpi * don't pretend that class is a module, just use it as a class * mass-replace mpi4py imports * flake8 * fix previous lazy_mpi imports * silly recursion * try os.environ hack * better prefix test, work with mpich * restored MPI imports * removed commented import in test_with_mpi * restored codegen from master * remove lazy mpi * restored changes from rl-algs * remove extra files * port mpi fix to shmem vec env * increase the mpi test default timeout * change humanoid hyperparameters, get rid of clip_Frac annealing, as it's apparently dangerous * remove clip_frac schedule from ppo2 * more timesteps in humanoid run * whitespace + RUN BENCHMARKS * baselines: export vecenvs from folder (#221) * baselines: export vecenvs from folder * put missing function back in * add missing imports * more imports * longer mpi timeout? * make default logger configuration the same as call to logger.configure() (#222) * Vecenv refactor (#223) * update karl util * restore pvi flag * change rcall auto cpu behavior, move gin.configurable, add os.makedirs * vecenv refactor * aux buf index fix * add num aux obs * reset level with enter * restore high difficulty flag * bugfix * restore train_coinrun.py * tweaks * renaming * renaming * better arguments handling * more options * options cleanup * game data refactor * more options * args for train_procgen * add close handler to interactive base class * use debug build if debug=True, fix range on aux_obs * add ProcGenEnv to __init__.py, add missing imports to procgen.py * export RemoveDictWrapper and build, update train_procgen.py, move assets download into env creation and replace init_assets_and_build with just build * fix formatting issues * only call global init once * fix path in setup.py * revert part of makefile * ignore IDE files and folders * vec remove dict * export VecRemoveDictObs * remove RemoveDictWrapper * remove IDE files * move shared .h and .cpp files to common folder, update build to use those, dedupe env.cpp * fix missing header * try unified build function * remove old scripts dir * add comment on build * upload libenv with render fixes * tell qthreads to die when we unload the library * pyglet.app.run is garbage * static fixes * whoops * actually vsync is on * cleanup * cleanup * extern C for libenv interface * parse util rcall arg * high difficulty fix * game type enums * ProcGenEnv subclasses * game type cleanup * unrecognized key * unrecognized game type * parse util reorg * args management * typo fix * GinParser * arg tweaks * tweak * restore start_level/num_levels setting * fix create_procgen_env interface * build fix * procgen args in init signature * fix * build fix * fix logger usage in ppo_metal/run_retro * removed unnecessary OrderedDict requirement in subproc_vec_env * flake8 fix * allow for non-mpi tests * mpi test fixes * flake8; removed special logic for discrete spaces in dummy_vec_env * remove forked argument in front of tests - does not play nicely with subprocvecenv in spawned processes; analog of forked in ddpg/test_smoke * Everyrl initial commit & a few minor baselines changes (#226) * everyrl initial commit * add keep_buf argument to VecMonitor * logger changes: set_comm and fix to mpi_mean functionality * if filename not provided, don't create ResultsWriter * change variable syncing function to simplify its usage. now you should initialize from all mpi processes * everyrl coinrun changes * tf_distr changes, bugfix * get_one * bring back get_next to temporarily restore code * lint fixes * fix test * rename profile function * rename gaussian * fix coinrun training script * change random seeding to work with new gym version (#231) * change random seeding to work with new gym version * move seeding to seed() method * fix mnistenv * actually try some of the tests before pushing * more deterministic fixed seq * misc changes to vecenvs and run.py for benchmarks (#236) * misc changes to vecenvs and run.py for benchmarks * dont seed global gen * update more references to assert_venvs_equal * Rl19 (#232) * everyrl initial commit * add keep_buf argument to VecMonitor * logger changes: set_comm and fix to mpi_mean functionality * if filename not provided, don't create ResultsWriter * change variable syncing function to simplify its usage. now you should initialize from all mpi processes * everyrl coinrun changes * tf_distr changes, bugfix * get_one * bring back get_next to temporarily restore code * lint fixes * fix test * rename profile function * rename gaussian * fix coinrun training script * rl19 * remove everyrl dir which appeared in the merge for some reason * readme * fiddle with ddpg * make ddpg work * steps_total argument * gpu count * clean up hyperparams and shape math * logging + saving * configuration stuff * fixes, smoke tests * fix stats * make load_results return dicts -- easier to create the same kind of objects with some other mechanism for passing to downstream functions * benchmarks * fix tests * add dqn to tests, fix it * minor * turned annotated transformer (pytorch) into a script * more refactoring * jax stuff * cluster * minor * copy & paste alec code * sign error * add huber, rename some parameters, snapshotting off by default * remove jax stuff * minor * move maze env * minor * remove trailing spaces * remove trailing space * lint * fix test breakage due to gym update * rename function * move maze back to codegen * get recurrent ppo working * enable both lstm and gru * script to print table of benchmark results * various * fix dqn * add fixup initializer, remove lastrew * organize logging stats * fix silly bug * refactor models * fix mpi usage * check sync * minor * change vf coef, hps * clean up slicing in ppo * minor fixes * caching transformer * docstrings * xf fixes * get rid of 'B' and 'BT' arguments * minor * transformer example * remove output_kind from base class until we have a better idea how to use it * add comments, revert maze stuff * flake8 * codegen lint * fix codegen tests * responded to peter's comments * lint fixes * minor changes to baselines (#243) * minor changes to baselines * fix spaces reference * remove flake8 disable comments and fix import * okay maybe don't add spec to vec_env * Merge branch 'master' of github.com:openai/games the commit. * flake8 complaints in baselines/her
499 lines
14 KiB
Python
499 lines
14 KiB
Python
import os
|
|
import sys
|
|
import shutil
|
|
import os.path as osp
|
|
import json
|
|
import time
|
|
import datetime
|
|
import tempfile
|
|
from collections import defaultdict
|
|
from contextlib import contextmanager
|
|
|
|
DEBUG = 10
|
|
INFO = 20
|
|
WARN = 30
|
|
ERROR = 40
|
|
|
|
DISABLED = 50
|
|
|
|
class KVWriter(object):
|
|
def writekvs(self, kvs):
|
|
raise NotImplementedError
|
|
|
|
class SeqWriter(object):
|
|
def writeseq(self, seq):
|
|
raise NotImplementedError
|
|
|
|
class HumanOutputFormat(KVWriter, SeqWriter):
|
|
def __init__(self, filename_or_file):
|
|
if isinstance(filename_or_file, str):
|
|
self.file = open(filename_or_file, 'wt')
|
|
self.own_file = True
|
|
else:
|
|
assert hasattr(filename_or_file, 'read'), 'expected file or str, got %s'%filename_or_file
|
|
self.file = filename_or_file
|
|
self.own_file = False
|
|
|
|
def writekvs(self, kvs):
|
|
# Create strings for printing
|
|
key2str = {}
|
|
for (key, val) in sorted(kvs.items()):
|
|
if isinstance(val, float):
|
|
valstr = '%-8.3g' % (val,)
|
|
else:
|
|
valstr = str(val)
|
|
key2str[self._truncate(key)] = self._truncate(valstr)
|
|
|
|
# Find max widths
|
|
if len(key2str) == 0:
|
|
print('WARNING: tried to write empty key-value dict')
|
|
return
|
|
else:
|
|
keywidth = max(map(len, key2str.keys()))
|
|
valwidth = max(map(len, key2str.values()))
|
|
|
|
# Write out the data
|
|
dashes = '-' * (keywidth + valwidth + 7)
|
|
lines = [dashes]
|
|
for (key, val) in sorted(key2str.items(), key=lambda kv: kv[0].lower()):
|
|
lines.append('| %s%s | %s%s |' % (
|
|
key,
|
|
' ' * (keywidth - len(key)),
|
|
val,
|
|
' ' * (valwidth - len(val)),
|
|
))
|
|
lines.append(dashes)
|
|
self.file.write('\n'.join(lines) + '\n')
|
|
|
|
# Flush the output to the file
|
|
self.file.flush()
|
|
|
|
def _truncate(self, s):
|
|
maxlen = 30
|
|
return s[:maxlen-3] + '...' if len(s) > maxlen else s
|
|
|
|
def writeseq(self, seq):
|
|
seq = list(seq)
|
|
for (i, elem) in enumerate(seq):
|
|
self.file.write(elem)
|
|
if i < len(seq) - 1: # add space unless this is the last one
|
|
self.file.write(' ')
|
|
self.file.write('\n')
|
|
self.file.flush()
|
|
|
|
def close(self):
|
|
if self.own_file:
|
|
self.file.close()
|
|
|
|
class JSONOutputFormat(KVWriter):
|
|
def __init__(self, filename):
|
|
self.file = open(filename, 'wt')
|
|
|
|
def writekvs(self, kvs):
|
|
for k, v in sorted(kvs.items()):
|
|
if hasattr(v, 'dtype'):
|
|
v = v.tolist()
|
|
kvs[k] = float(v)
|
|
self.file.write(json.dumps(kvs) + '\n')
|
|
self.file.flush()
|
|
|
|
def close(self):
|
|
self.file.close()
|
|
|
|
class CSVOutputFormat(KVWriter):
|
|
def __init__(self, filename):
|
|
self.file = open(filename, 'w+t')
|
|
self.keys = []
|
|
self.sep = ','
|
|
|
|
def writekvs(self, kvs):
|
|
# Add our current row to the history
|
|
extra_keys = list(kvs.keys() - self.keys)
|
|
extra_keys.sort()
|
|
if extra_keys:
|
|
self.keys.extend(extra_keys)
|
|
self.file.seek(0)
|
|
lines = self.file.readlines()
|
|
self.file.seek(0)
|
|
for (i, k) in enumerate(self.keys):
|
|
if i > 0:
|
|
self.file.write(',')
|
|
self.file.write(k)
|
|
self.file.write('\n')
|
|
for line in lines[1:]:
|
|
self.file.write(line[:-1])
|
|
self.file.write(self.sep * len(extra_keys))
|
|
self.file.write('\n')
|
|
for (i, k) in enumerate(self.keys):
|
|
if i > 0:
|
|
self.file.write(',')
|
|
v = kvs.get(k)
|
|
if v is not None:
|
|
self.file.write(str(v))
|
|
self.file.write('\n')
|
|
self.file.flush()
|
|
|
|
def close(self):
|
|
self.file.close()
|
|
|
|
|
|
class TensorBoardOutputFormat(KVWriter):
|
|
"""
|
|
Dumps key/value pairs into TensorBoard's numeric format.
|
|
"""
|
|
def __init__(self, dir):
|
|
os.makedirs(dir, exist_ok=True)
|
|
self.dir = dir
|
|
self.step = 1
|
|
prefix = 'events'
|
|
path = osp.join(osp.abspath(dir), prefix)
|
|
import tensorflow as tf
|
|
from tensorflow.python import pywrap_tensorflow
|
|
from tensorflow.core.util import event_pb2
|
|
from tensorflow.python.util import compat
|
|
self.tf = tf
|
|
self.event_pb2 = event_pb2
|
|
self.pywrap_tensorflow = pywrap_tensorflow
|
|
self.writer = pywrap_tensorflow.EventsWriter(compat.as_bytes(path))
|
|
|
|
def writekvs(self, kvs):
|
|
def summary_val(k, v):
|
|
kwargs = {'tag': k, 'simple_value': float(v)}
|
|
return self.tf.Summary.Value(**kwargs)
|
|
summary = self.tf.Summary(value=[summary_val(k, v) for k, v in kvs.items()])
|
|
event = self.event_pb2.Event(wall_time=time.time(), summary=summary)
|
|
event.step = self.step # is there any reason why you'd want to specify the step?
|
|
self.writer.WriteEvent(event)
|
|
self.writer.Flush()
|
|
self.step += 1
|
|
|
|
def close(self):
|
|
if self.writer:
|
|
self.writer.Close()
|
|
self.writer = None
|
|
|
|
def make_output_format(format, ev_dir, log_suffix=''):
|
|
os.makedirs(ev_dir, exist_ok=True)
|
|
if format == 'stdout':
|
|
return HumanOutputFormat(sys.stdout)
|
|
elif format == 'log':
|
|
return HumanOutputFormat(osp.join(ev_dir, 'log%s.txt' % log_suffix))
|
|
elif format == 'json':
|
|
return JSONOutputFormat(osp.join(ev_dir, 'progress%s.json' % log_suffix))
|
|
elif format == 'csv':
|
|
return CSVOutputFormat(osp.join(ev_dir, 'progress%s.csv' % log_suffix))
|
|
elif format == 'tensorboard':
|
|
return TensorBoardOutputFormat(osp.join(ev_dir, 'tb%s' % log_suffix))
|
|
else:
|
|
raise ValueError('Unknown format specified: %s' % (format,))
|
|
|
|
# ================================================================
|
|
# API
|
|
# ================================================================
|
|
|
|
def logkv(key, val):
|
|
"""
|
|
Log a value of some diagnostic
|
|
Call this once for each diagnostic quantity, each iteration
|
|
If called many times, last value will be used.
|
|
"""
|
|
get_current().logkv(key, val)
|
|
|
|
def logkv_mean(key, val):
|
|
"""
|
|
The same as logkv(), but if called many times, values averaged.
|
|
"""
|
|
get_current().logkv_mean(key, val)
|
|
|
|
def logkvs(d):
|
|
"""
|
|
Log a dictionary of key-value pairs
|
|
"""
|
|
for (k, v) in d.items():
|
|
logkv(k, v)
|
|
|
|
def dumpkvs():
|
|
"""
|
|
Write all of the diagnostics from the current iteration
|
|
"""
|
|
return get_current().dumpkvs()
|
|
|
|
def getkvs():
|
|
return get_current().name2val
|
|
|
|
|
|
def log(*args, level=INFO):
|
|
"""
|
|
Write the sequence of args, with no separators, to the console and output files (if you've configured an output file).
|
|
"""
|
|
get_current().log(*args, level=level)
|
|
|
|
def debug(*args):
|
|
log(*args, level=DEBUG)
|
|
|
|
def info(*args):
|
|
log(*args, level=INFO)
|
|
|
|
def warn(*args):
|
|
log(*args, level=WARN)
|
|
|
|
def error(*args):
|
|
log(*args, level=ERROR)
|
|
|
|
|
|
def set_level(level):
|
|
"""
|
|
Set logging threshold on current logger.
|
|
"""
|
|
get_current().set_level(level)
|
|
|
|
def set_comm(comm):
|
|
get_current().set_comm(comm)
|
|
|
|
def get_dir():
|
|
"""
|
|
Get directory that log files are being written to.
|
|
will be None if there is no output directory (i.e., if you didn't call start)
|
|
"""
|
|
return get_current().get_dir()
|
|
|
|
record_tabular = logkv
|
|
dump_tabular = dumpkvs
|
|
|
|
@contextmanager
|
|
def profile_kv(scopename):
|
|
logkey = 'wait_' + scopename
|
|
tstart = time.time()
|
|
try:
|
|
yield
|
|
finally:
|
|
get_current().name2val[logkey] += time.time() - tstart
|
|
|
|
def profile(n):
|
|
"""
|
|
Usage:
|
|
@profile("my_func")
|
|
def my_func(): code
|
|
"""
|
|
def decorator_with_name(func):
|
|
def func_wrapper(*args, **kwargs):
|
|
with profile_kv(n):
|
|
return func(*args, **kwargs)
|
|
return func_wrapper
|
|
return decorator_with_name
|
|
|
|
|
|
# ================================================================
|
|
# Backend
|
|
# ================================================================
|
|
|
|
def get_current():
|
|
if Logger.CURRENT is None:
|
|
_configure_default_logger()
|
|
|
|
return Logger.CURRENT
|
|
|
|
|
|
class Logger(object):
|
|
DEFAULT = None # A logger with no output files. (See right below class definition)
|
|
# So that you can still log to the terminal without setting up any output files
|
|
CURRENT = None # Current logger being used by the free functions above
|
|
|
|
def __init__(self, dir, output_formats, comm=None):
|
|
self.name2val = defaultdict(float) # values this iteration
|
|
self.name2cnt = defaultdict(int)
|
|
self.level = INFO
|
|
self.dir = dir
|
|
self.output_formats = output_formats
|
|
self.comm = comm
|
|
|
|
# Logging API, forwarded
|
|
# ----------------------------------------
|
|
def logkv(self, key, val):
|
|
self.name2val[key] = val
|
|
|
|
def logkv_mean(self, key, val):
|
|
oldval, cnt = self.name2val[key], self.name2cnt[key]
|
|
self.name2val[key] = oldval*cnt/(cnt+1) + val/(cnt+1)
|
|
self.name2cnt[key] = cnt + 1
|
|
|
|
def dumpkvs(self):
|
|
if self.comm is None:
|
|
d = self.name2val
|
|
else:
|
|
from baselines.common import mpi_util
|
|
d = mpi_util.mpi_weighted_mean(self.comm,
|
|
{name : (val, self.name2cnt.get(name, 1))
|
|
for (name, val) in self.name2val.items()})
|
|
if self.comm.rank != 0:
|
|
d['dummy'] = 1 # so we don't get a warning about empty dict
|
|
out = d.copy() # Return the dict for unit testing purposes
|
|
for fmt in self.output_formats:
|
|
if isinstance(fmt, KVWriter):
|
|
fmt.writekvs(d)
|
|
self.name2val.clear()
|
|
self.name2cnt.clear()
|
|
return out
|
|
|
|
def log(self, *args, level=INFO):
|
|
if self.level <= level:
|
|
self._do_log(args)
|
|
|
|
# Configuration
|
|
# ----------------------------------------
|
|
def set_level(self, level):
|
|
self.level = level
|
|
|
|
def set_comm(self, comm):
|
|
self.comm = comm
|
|
|
|
def get_dir(self):
|
|
return self.dir
|
|
|
|
def close(self):
|
|
for fmt in self.output_formats:
|
|
fmt.close()
|
|
|
|
# Misc
|
|
# ----------------------------------------
|
|
def _do_log(self, args):
|
|
for fmt in self.output_formats:
|
|
if isinstance(fmt, SeqWriter):
|
|
fmt.writeseq(map(str, args))
|
|
|
|
def configure(dir=None, format_strs=None, comm=None):
|
|
"""
|
|
If comm is provided, average all numerical stats across that comm
|
|
"""
|
|
if dir is None:
|
|
dir = os.getenv('OPENAI_LOGDIR')
|
|
if dir is None:
|
|
dir = osp.join(tempfile.gettempdir(),
|
|
datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f"))
|
|
assert isinstance(dir, str)
|
|
os.makedirs(dir, exist_ok=True)
|
|
|
|
log_suffix = ''
|
|
rank = 0
|
|
# check environment variables here instead of importing mpi4py
|
|
# to avoid calling MPI_Init() when this module is imported
|
|
for varname in ['PMI_RANK', 'OMPI_COMM_WORLD_RANK']:
|
|
if varname in os.environ:
|
|
rank = int(os.environ[varname])
|
|
if rank > 0:
|
|
log_suffix = "-rank%03i" % rank
|
|
|
|
if format_strs is None:
|
|
if rank == 0:
|
|
format_strs = os.getenv('OPENAI_LOG_FORMAT', 'stdout,log,csv').split(',')
|
|
else:
|
|
format_strs = os.getenv('OPENAI_LOG_FORMAT_MPI', 'log').split(',')
|
|
format_strs = filter(None, format_strs)
|
|
output_formats = [make_output_format(f, dir, log_suffix) for f in format_strs]
|
|
|
|
Logger.CURRENT = Logger(dir=dir, output_formats=output_formats, comm=comm)
|
|
log('Logging to %s'%dir)
|
|
|
|
def _configure_default_logger():
|
|
configure()
|
|
Logger.DEFAULT = Logger.CURRENT
|
|
|
|
def reset():
|
|
if Logger.CURRENT is not Logger.DEFAULT:
|
|
Logger.CURRENT.close()
|
|
Logger.CURRENT = Logger.DEFAULT
|
|
log('Reset logger')
|
|
|
|
@contextmanager
|
|
def scoped_configure(dir=None, format_strs=None, comm=None):
|
|
prevlogger = Logger.CURRENT
|
|
configure(dir=dir, format_strs=format_strs, comm=comm)
|
|
try:
|
|
yield
|
|
finally:
|
|
Logger.CURRENT.close()
|
|
Logger.CURRENT = prevlogger
|
|
|
|
# ================================================================
|
|
|
|
def _demo():
|
|
info("hi")
|
|
debug("shouldn't appear")
|
|
set_level(DEBUG)
|
|
debug("should appear")
|
|
dir = "/tmp/testlogging"
|
|
if os.path.exists(dir):
|
|
shutil.rmtree(dir)
|
|
configure(dir=dir)
|
|
logkv("a", 3)
|
|
logkv("b", 2.5)
|
|
dumpkvs()
|
|
logkv("b", -2.5)
|
|
logkv("a", 5.5)
|
|
dumpkvs()
|
|
info("^^^ should see a = 5.5")
|
|
logkv_mean("b", -22.5)
|
|
logkv_mean("b", -44.4)
|
|
logkv("a", 5.5)
|
|
dumpkvs()
|
|
info("^^^ should see b = -33.3")
|
|
|
|
logkv("b", -2.5)
|
|
dumpkvs()
|
|
|
|
logkv("a", "longasslongasslongasslongasslongasslongassvalue")
|
|
dumpkvs()
|
|
|
|
|
|
# ================================================================
|
|
# Readers
|
|
# ================================================================
|
|
|
|
def read_json(fname):
|
|
import pandas
|
|
ds = []
|
|
with open(fname, 'rt') as fh:
|
|
for line in fh:
|
|
ds.append(json.loads(line))
|
|
return pandas.DataFrame(ds)
|
|
|
|
def read_csv(fname):
|
|
import pandas
|
|
return pandas.read_csv(fname, index_col=None, comment='#')
|
|
|
|
def read_tb(path):
|
|
"""
|
|
path : a tensorboard file OR a directory, where we will find all TB files
|
|
of the form events.*
|
|
"""
|
|
import pandas
|
|
import numpy as np
|
|
from glob import glob
|
|
import tensorflow as tf
|
|
if osp.isdir(path):
|
|
fnames = glob(osp.join(path, "events.*"))
|
|
elif osp.basename(path).startswith("events."):
|
|
fnames = [path]
|
|
else:
|
|
raise NotImplementedError("Expected tensorboard file or directory containing them. Got %s"%path)
|
|
tag2pairs = defaultdict(list)
|
|
maxstep = 0
|
|
for fname in fnames:
|
|
for summary in tf.train.summary_iterator(fname):
|
|
if summary.step > 0:
|
|
for v in summary.summary.value:
|
|
pair = (summary.step, v.simple_value)
|
|
tag2pairs[v.tag].append(pair)
|
|
maxstep = max(summary.step, maxstep)
|
|
data = np.empty((maxstep, len(tag2pairs)))
|
|
data[:] = np.nan
|
|
tags = sorted(tag2pairs.keys())
|
|
for (colidx,tag) in enumerate(tags):
|
|
pairs = tag2pairs[tag]
|
|
for (step, value) in pairs:
|
|
data[step-1, colidx] = value
|
|
return pandas.DataFrame(data, columns=tags)
|
|
|
|
if __name__ == "__main__":
|
|
_demo()
|