code
stringlengths
17
6.64M
def plms_mixer(old_eps, order=1): cur_order = min(order, len(old_eps)) if (cur_order == 1): eps_prime = old_eps[(- 1)] elif (cur_order == 2): eps_prime = (((3 * old_eps[(- 1)]) - old_eps[(- 2)]) / 2) elif (cur_order == 3): eps_prime = ((((23 * old_eps[(- 1)]) - (16 * old_eps[(-...
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 %...
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'): kvs[k] = float(v) self.file.write((json.dumps(kvs) + '\n')) self.fi...
class CSVOutputFormat(KVWriter): def __init__(self, filename): self.file = open(filename, 'w+t') self.keys = [] self.sep = ',' def writekvs(self, kvs): extra_keys = list((kvs.keys() - self.keys)) extra_keys.sort() if extra_keys: self.keys.extend(ex...
class TensorBoardOutputFormat(KVWriter): "\n Dumps key/value pairs into TensorBoard's numeric format.\n " 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) imp...
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...
def logkv(key, val): '\n Log a value of some diagnostic\n Call this once for each diagnostic quantity, each iteration\n If called many times, last value will be used.\n ' get_current().logkv(key, val)
def logkv_mean(key, val): '\n The same as logkv(), but if called many times, values averaged.\n ' get_current().logkv_mean(key, val)
def logkvs(d): '\n Log a dictionary of key-value pairs\n ' for (k, v) in d.items(): logkv(k, v)
def dumpkvs(): '\n Write all of the diagnostics from the current iteration\n ' return get_current().dumpkvs()
def getkvs(): return get_current().name2val
def log(*args, level=INFO): "\n Write the sequence of args, with no separators, to the console and output files (if you've configured an output file).\n " 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): '\n Set logging threshold on current logger.\n ' get_current().set_level(level)
def set_comm(comm): get_current().set_comm(comm)
def get_dir(): "\n Get directory that log files are being written to.\n will be None if there is no output directory (i.e., if you didn't call start)\n " return get_current().get_dir()
@contextmanager def profile_kv(scopename): logkey = ('wait_' + scopename) tstart = time.time() try: (yield) finally: get_current().name2val[logkey] += (time.time() - tstart)
def profile(n): '\n Usage:\n @profile("my_func")\n def my_func(): code\n ' 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
def get_current(): if (Logger.CURRENT is None): _configure_default_logger() return Logger.CURRENT
class Logger(object): DEFAULT = None CURRENT = None def __init__(self, dir, output_formats, comm=None): self.name2val = defaultdict(float) self.name2cnt = defaultdict(int) self.level = INFO self.dir = dir self.output_formats = output_formats self.comm = com...
def get_rank_without_mpi_import(): for varname in ['PMI_RANK', 'OMPI_COMM_WORLD_RANK']: if (varname in os.environ): return int(os.environ[varname]) return 0
def mpi_weighted_mean(comm, local_name2valcount): '\n Copied from: https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/common/mpi_util.py#L110\n Perform a weighted average over dicts that are each on a different node\n Input: local_name2valcount: dict mapping key -...
def configure(dir=None, format_strs=None, comm=None, log_suffix=''): '\n If comm is provided, average all numerical stats across that comm\n ' if (dir is None): dir = os.getenv('OPENAI_LOGDIR') if (dir is None): dir = osp.join(tempfile.gettempdir(), datetime.datetime.now().strftime('...
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 normal_kl(mean1, logvar1, mean2, logvar2): '\n Compute the KL divergence between two gaussians.\n\n Shapes are automatically broadcasted, so batches can be compared to\n scalars, among other use cases.\n ' tensor = None for obj in (mean1, logvar1, mean2, logvar2): if isinstance(obj...
def approx_standard_normal_cdf(x): '\n A fast approximation of the cumulative distribution function of the\n standard normal.\n ' return (0.5 * (1.0 + th.tanh((np.sqrt((2.0 / np.pi)) * (x + (0.044715 * th.pow(x, 3)))))))
def discretized_gaussian_log_likelihood(x, *, means, log_scales): '\n Compute the log-likelihood of a Gaussian distribution discretizing to a\n given image.\n\n :param x: the target images. It is assumed that this was uint8 values,\n rescaled to the range [-1, 1].\n :param means: the Gaus...
def space_timesteps(num_timesteps, section_counts): '\n Create a list of timesteps to use from an original diffusion process,\n given the number of timesteps we want to take from equally-sized portions\n of the original process.\n\n For example, if there\'s 300 timesteps and the section counts are [10...
class SpacedDiffusion(GaussianDiffusion): '\n A diffusion process which can skip steps in a base diffusion process.\n\n :param use_timesteps: a collection (sequence or set) of timesteps from the\n original diffusion process to retain.\n :param kwargs: the kwargs to create the bas...
class _WrappedModel(): def __init__(self, model, timestep_map, rescale_timesteps, original_num_steps): self.model = model self.timestep_map = timestep_map self.rescale_timesteps = rescale_timesteps self.original_num_steps = original_num_steps def __call__(self, x, ts, **kwarg...
def diffusion_defaults(): '\n Defaults for image and classifier training.\n ' return dict(learn_sigma=False, diffusion_steps=1000, noise_schedule='linear', timestep_respacing='', use_kl=False, predict_xstart=False, rescale_timesteps=False, rescale_learned_sigmas=False)
def classifier_defaults(): '\n Defaults for classifier models.\n ' return dict(image_size=64, classifier_use_fp16=False, classifier_width=128, classifier_depth=2, classifier_attention_resolutions='32,16,8', classifier_use_scale_shift_norm=True, classifier_resblock_updown=True, classifier_pool='attention...
def model_and_diffusion_defaults(): '\n Defaults for image training.\n ' res = dict(image_size=64, num_channels=128, num_res_blocks=2, num_heads=4, num_heads_upsample=(- 1), num_head_channels=(- 1), attention_resolutions='16,8', channel_mult='', dropout=0.0, class_cond=False, use_checkpoint=False, use_s...
def classifier_and_diffusion_defaults(): res = classifier_defaults() res.update(diffusion_defaults()) return res
def create_model_and_diffusion(image_size, class_cond, learn_sigma, num_channels, num_res_blocks, channel_mult, num_heads, num_head_channels, num_heads_upsample, attention_resolutions, dropout, diffusion_steps, noise_schedule, timestep_respacing, use_kl, predict_xstart, rescale_timesteps, rescale_learned_sigmas, use_...
def create_model(image_size, num_channels, num_res_blocks, channel_mult='', learn_sigma=False, class_cond=False, use_checkpoint=False, attention_resolutions='16', num_heads=1, num_head_channels=(- 1), num_heads_upsample=(- 1), use_scale_shift_norm=False, dropout=0, resblock_updown=False, use_fp16=False, use_new_atten...
def create_classifier_and_diffusion(image_size, classifier_use_fp16, classifier_width, classifier_depth, classifier_attention_resolutions, classifier_use_scale_shift_norm, classifier_resblock_updown, classifier_pool, learn_sigma, diffusion_steps, noise_schedule, timestep_respacing, use_kl, predict_xstart, rescale_tim...
def create_classifier(image_size, classifier_use_fp16, classifier_width, classifier_depth, classifier_attention_resolutions, classifier_use_scale_shift_norm, classifier_resblock_updown, classifier_pool): if (image_size == 512): channel_mult = (0.5, 1, 1, 2, 2, 4, 4) elif (image_size == 256): c...
def sr_model_and_diffusion_defaults(): res = model_and_diffusion_defaults() res['large_size'] = 256 res['small_size'] = 64 arg_names = inspect.getfullargspec(sr_create_model_and_diffusion)[0] for k in res.copy().keys(): if (k not in arg_names): del res[k] return res
def sr_create_model_and_diffusion(large_size, small_size, class_cond, learn_sigma, num_channels, num_res_blocks, num_heads, num_head_channels, num_heads_upsample, attention_resolutions, dropout, diffusion_steps, noise_schedule, timestep_respacing, use_kl, predict_xstart, rescale_timesteps, rescale_learned_sigmas, use...
def sr_create_model(large_size, small_size, num_channels, num_res_blocks, learn_sigma, class_cond, use_checkpoint, attention_resolutions, num_heads, num_head_channels, num_heads_upsample, use_scale_shift_norm, dropout, resblock_updown, use_fp16): _ = small_size if (large_size == 512): channel_mult = (...
def create_gaussian_diffusion(*, steps=1000, learn_sigma=False, sigma_small=False, noise_schedule='linear', use_kl=False, predict_xstart=False, rescale_timesteps=False, rescale_learned_sigmas=False, timestep_respacing=''): betas = gd.get_named_beta_schedule(noise_schedule, steps) if use_kl: loss_type ...
def add_dict_to_argparser(parser, default_dict): for (k, v) in default_dict.items(): v_type = type(v) if (v is None): v_type = str elif isinstance(v, bool): v_type = str2bool parser.add_argument(f'--{k}', default=v, type=v_type)
def args_to_dict(args, keys): return {k: getattr(args, k) for k in keys}
def str2bool(v): '\n https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse\n ' if isinstance(v, bool): return v if (v.lower() in ('yes', 'true', 't', 'y', '1')): return True elif (v.lower() in ('no', 'false', 'f', 'n', '0')): return False e...
class TrainLoop(): def __init__(self, *, model, diffusion, data, batch_size, microbatch, lr, ema_rate, log_interval, save_interval, resume_checkpoint, use_fp16=False, fp16_scale_growth=0.001, schedule_sampler=None, weight_decay=0.0, lr_anneal_steps=0): self.model = model self.diffusion = diffusio...
def parse_resume_step_from_filename(filename): "\n Parse filenames of the form path/to/modelNNNNNN.pt, where NNNNNN is the\n checkpoint's number of steps.\n " split = filename.split('model') if (len(split) < 2): return 0 split1 = split[(- 1)].split('.')[0] try: return int(...
def get_blob_logdir(): return logger.get_dir()
def find_resume_checkpoint(): return None
def find_ema_checkpoint(main_checkpoint, step, rate): if (main_checkpoint is None): return None filename = f'ema_{rate}_{step:06d}.pt' path = bf.join(bf.dirname(main_checkpoint), filename) if bf.exists(path): return path return None
def log_loss_dict(diffusion, ts, losses): for (key, values) in losses.items(): logger.logkv_mean(key, values.mean().item()) for (sub_t, sub_loss) in zip(ts.cpu().numpy(), values.detach().cpu().numpy()): quartile = int(((4 * sub_t) / diffusion.num_timesteps)) logger.logkv_me...
def main(): args = create_argparser().parse_args() dist_util.setup_dist() logger.configure() out_dir = os.path.join('symlink/output/', args.model_name, args.cond_name, args.method) if (dist.get_rank() == 0): print(out_dir) os.makedirs(out_dir, exist_ok=True) (config, model_conf...
def create_argparser(): defaults = dict(clip_denoised=True, num_samples=100, use_ddim=True, model_name='u256', method='ddim', cond_name='cond1', timestep_rp=25) defaults.update(model_and_diffusion_defaults()) defaults.update(classifier_defaults()) parser = argparse.ArgumentParser() add_dict_to_arg...
class BaseActorPolicy(object): '\n This is a policy wrapper for an actor, its functions need to be filled\n to load the policy such that it can be used by the robot to act in the\n environment.\n ' def __init__(self, identifier=None): '\n\n :param identifier: (str) defines the name...
class DummyActorPolicy(BaseActorPolicy): '\n This is a policy wrapper for a dummy actor, which uses the interface of\n the actor policy but is basically fed the actions externally, (i.e just\n using the interface of the actor policy but actions are calculated\n externally)\n ' def __init__(sel...
class GraspingPolicy(BaseActorPolicy): '\n This policy is expected to run @25 Hz, its a hand designed policy for\n picking and placing blocks of a specific size 6.5CM weighing 20grams\n for the best result tried.\n The policy outputs desired normalized end_effector_positions\n\n Description of phas...
class PickAndPlaceActorPolicy(BaseActorPolicy): def __init__(self): '\n This policy is expected to run @83.3 Hz.\n The policy expects normalized observations and it outputs\n desired joint positions.\n\n - This policy is trained with one goal positions only.\n ' ...
class PickingActorPolicy(BaseActorPolicy): def __init__(self): '\n This policy is expected to run @83.3 Hz.\n The policy expects normalized observations and it outputs\n desired joint positions.\n\n - This policy is trained with several goal heights.\n ' super(P...
class PushingActorPolicy(BaseActorPolicy): def __init__(self): '\n This policy is expected to run @83.3 Hz.\n The policy expects normalized observations and it outputs\n desired joint positions.\n\n - This policy is trained with several goals.\n ' super(PushingA...
class RandomActorPolicy(BaseActorPolicy): '\n This is a policy wrapper for a random actor.\n ' def __init__(self, low_bound, upper_bound): super(RandomActorPolicy, self).__init__(identifier='random_policy') self._low_bound = low_bound self._upper_bound = upper_bound retu...
class ReacherActorPolicy(BaseActorPolicy): def __init__(self): '\n This policy is expected to run @83.33 Hz.\n The policy expects normalized observations and it outputs\n desired joint positions.\n\n - This policy is trained with several goals.\n ' super(Reacher...
class Stacking2ActorPolicy(BaseActorPolicy): def __init__(self): '\n This policy is expected to run @83.3 Hz.\n The policy expects normalized observations and it outputs\n desired joint positions.\n\n - This policy is trained with several goal positions.\n ' sup...
class WorldConstants(): ROBOT_ID = 1 FLOOR_ID = 2 STAGE_ID = 3 FLOOR_HEIGHT = 0.011 ROBOT_HEIGHT = 0.34 ARENA_BB = np.array([[(- 0.15), (- 0.15), 0], [0.15, 0.15, 0.3]]) LINK_IDS = {'robot_finger_60_link_0': 1, 'robot_finger_60_link_1': 2, 'robot_finger_60_link_2': 3, 'robot_finger_60_link...
class Curriculum(object): def __init__(self, intervention_actors, actives): '\n This corresponds to a curriculum object where it takes in\n the intervention actor and when are they supposed to be activated.\n\n :param intervention_actors: (list) list of intervention actors\n :...
class TriFingerAction(object): def __init__(self, action_mode='joint_positions', normalize_actions=True): '\n This class is responsible for the robot action limits and its spaces.\n\n :param action_mode: (str) this can be "joint_positions", "joint_torques" or\n ...
class TriFingerObservations(object): def __init__(self, observation_mode='structured', normalize_observations=True, observation_keys=None, cameras=None, camera_indicies=np.array([0, 1, 2])): '\n This class represents the observation limits of the robot and takes\n care of the normalization ...
class TriFingerRobot(object): def __init__(self, action_mode, observation_mode, skip_frame, normalize_actions, normalize_observations, simulation_time, pybullet_client_full_id, pybullet_client_w_goal_id, pybullet_client_w_o_goal_id, revolute_joint_ids, finger_tip_ids, cameras=None, camera_indicies=np.array([0, 1...
class RigidObject(object): def __init__(self, pybullet_client_ids, name, size, initial_position, initial_orientation, mass, color, lateral_friction, spinning_friction, restitution, initial_linear_velocity, initial_angular_velocity, fixed_bool): '\n This is the base class of any rigid object whethe...
class Cuboid(RigidObject): def __init__(self, pybullet_client_ids, name, size=np.array([0.065, 0.065, 0.065]), initial_position=np.array([0.0, 0.0, 0.0425]), initial_orientation=np.array([0, 0, 0, 1]), mass=0.08, color=np.array([1, 0, 0]), initial_linear_velocity=np.array([0, 0, 0]), initial_angular_velocity=np....
class StaticCuboid(RigidObject): def __init__(self, pybullet_client_ids, name, size=np.array([0.065, 0.065, 0.065]), position=np.array([0.0, 0.0, 0.0425]), orientation=np.array([0, 0, 0, 1]), color=np.array([1, 0, 0]), lateral_friction=1): '\n\n :param pybullet_client_ids: (list) specifies the pyb...
class MeshObject(RigidObject): def __init__(self, pybullet_client_ids, name, filename, scale=np.array([0.01, 0.01, 0.01]), initial_position=np.array([0.0, 0.0, 0.0425]), initial_orientation=np.array([0, 0, 0, 1]), color=np.array([1, 0, 0]), mass=0.08, initial_linear_velocity=np.array([0, 0, 0]), initial_angular_...
class StageObservations(object): def __init__(self, rigid_objects, visual_objects, observation_mode='structured', normalize_observations=True, cameras=None, camera_indicies=np.array([0, 1, 2])): '\n\n :param rigid_objects: (dict) dict of rigid objects in the arena.\n :param visual_objects: ...
class Stage(object): def __init__(self, observation_mode, normalize_observations, pybullet_client_full_id, pybullet_client_w_goal_id, pybullet_client_w_o_goal_id, cameras, camera_indicies): '\n This class represents the stage object, where it handles all the arena\n functionalities includin...
class EvaluationPipeline(object): '\n This class provides functionalities to evaluate a trained policy on a set\n of protocols\n\n :param evaluation_protocols: (list) defines the protocols that will be\n evaluated in this pipleine.\n :param tracker_path: (causal_...
class FullyRandomProtocol(ProtocolBase): def __init__(self, name, variable_space='space_a_b'): '\n This specifies a fully random protocol, where an intervention is\n produced on every exposed variable by uniformly sampling the\n intervention space.\n\n :param name: (str) speci...
class ProtocolBase(object): '\n Base Protocol from which each EvaluationProtocol inherits. Default number\n of evaluation protocols is 200\n :param name: (str) name of the protocol\n ' def __init__(self, name): self.name = name self.num_evaluation_episodes_default = 200 se...
class ProtocolGenerator(ProtocolBase): def __init__(self, name, first_level_regex, second_level_regex, variable_space='space_a_b'): '\n This specifies a fully random protocol, where an intervention is\n produced on every exposed variable by uniformly sampling the\n intervention space...
def bar_plots(output_path, data): '\n\n :param output_path:\n :param data:\n :return:\n ' protocol_labels = data[0] experiment_labels = data[1] metric_labels = data[2] x = np.arange(len(protocol_labels)) colors = ['blue', 'orange', 'green'] for metric_label in data[3]: ...
def bar_plots_with_protocol_table(output_path, data, protocol_settings, task): '\n\n :param output_path:\n :param data:\n :param protocol_settings:\n :param task:\n :return:\n ' protocol_labels = data[0] protocol_ids = ['P{}'.format(i) for i in range(len(protocol_labels))] experiment...
def radar_factory(num_vars, frame='circle'): "\n Create a radar chart with `num_vars` axes.\n This function creates a RadarAxes projection and registers it.\n\n :param num_vars: (int) Number of variables for radar chart.\n :param frame: (str) Shape of frame surrounding axes, {'circle' | 'polygon'}.\n ...
def unit_poly_verts(theta): '\n Return vertices of polygon for subplot axes.\n This polygon is circumscribed by a unit circle centered at (0.5, 0.5)\n\n :param theta:\n :return:\n ' (x0, y0, r) = ([0.5] * 3) verts = [(((r * np.cos(t)) + x0), ((r * np.sin(t)) + y0)) for t in theta] retur...
def radar_plots(output_path, data): '\n\n :param output_path:\n :param data:\n :return:\n ' protocol_labels = data[0] experiment_labels = data[1] metric_labels = data[2] N = len(protocol_labels) theta = radar_factory(N, frame='circle') colors = ['#a6cee3', '#1f78b4', '#b2df8a',...
def aggregated_data_from_experiments(experiments, contains_err=False): "\n experiments: Is a dict of score dicts with each key being the scores of an experiments\n contains_err: If True, for each metric score a error is expected under the key metric_label + '_std'\n\n\n Returns: a structured list that ca...
def generate_visual_analysis(output_path, experiments): '\n saves bar plots as well as radar plots for quick comparisons of the\n policies passed.\n\n :param output_path: (str) specifies the output path for saving the plot\n results.\n :param experiments: (dict) specifies ...
class BaseInterventionActorPolicy(object): def __init__(self, **kwargs): '\n This class indicates the interface of an intervention actor\n\n :param kwargs: (params) parameters for the construction of the actor.\n ' return def initialize(self, env): '\n Thi...
class GoalInterventionActorPolicy(BaseInterventionActorPolicy): def __init__(self, **kwargs): '\n This class indicates the goal intervention actor, which an\n intervention actor that intervenes by sampling a new goal.\n\n :param kwargs: (params) parameters for the construction of the...
class JointsInterventionActorPolicy(BaseInterventionActorPolicy): def __init__(self, **kwargs): '\n This class indicates the joint intervention actor which intervenes on\n the joints of the robot in a random fashion.\n\n :param kwargs:\n ' super(JointsInterventionActor...
class PhysicalPropertiesInterventionActorPolicy(BaseInterventionActorPolicy): def __init__(self, group, **kwargs): '\n This intervention actor intervenes on physcial proporties such as\n friction, mass...etc\n\n :param group: (str) the object that the actor will intervene on.\n ...
class RandomInterventionActorPolicy(BaseInterventionActorPolicy): def __init__(self, **kwargs): '\n This is a random intervention actor which intervenes randomly on\n all available state variables except joint positions since its a\n trickier space.\n\n :param kwargs:\n ...
class RigidPoseInterventionActorPolicy(BaseInterventionActorPolicy): def __init__(self, positions=True, orientations=True, **kwargs): '\n This intervention actor intervenes on the pose of the blocks\n available in the arena.\n\n :param positions: (bool) True if interventions on posit...
class VisualInterventionActorPolicy(BaseInterventionActorPolicy): def __init__(self, **kwargs): '\n This intervention actor intervenes on all visual components of the\n robot, (i.e: colors).\n\n :param kwargs:\n ' super(VisualInterventionActorPolicy, self).__init__() ...
class DataLoader(): def __init__(self, episode_directory): '\n This initializes a data loader that loads recorded episodes using a\n causal_world.loggers.DataRecorder object.\n\n :param episode_directory: (str) directory where it holds all the\n ...
class DataRecorder(): def __init__(self, output_directory=None, rec_dumb_frequency=100): '\n This class logs the full histories of a world across multiple episodes\n\n :param output_directory: (str) specifies the output directory to save\n the episodes ...