code stringlengths 17 6.64M |
|---|
def parse_args():
parser = argparse.ArgumentParser('Sample (with beam-search) from the session model')
parser.add_argument('--ignore-unk', action='store_false', help='Disables the generation of unknown words (<unk> tokens)')
parser.add_argument('model_prefix', help='Path to the model prefix (without _mode... |
def main():
args = parse_args()
state = prototype_state()
state_path = (args.model_prefix + '_state.pkl')
model_path = (args.model_prefix + '_model.npz')
with open(state_path) as src:
state.update(cPickle.load(src))
logging.basicConfig(level=getattr(logging, state['level']), format='%(... |
def prototype_state():
state = {}
state['seed'] = 1234
state['level'] = 'DEBUG'
state['oov'] = '<unk>'
state['end_sym_utterance'] = '</s>'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = 2
state['first_speaker_sym'] = 3
state['second_speaker_sym'] = 4
state['th... |
def prototype_test():
state = prototype_state()
state['train_dialogues'] = './tests/data/ttrain.dialogues.pkl'
state['test_dialogues'] = './tests/data/ttest.dialogues.pkl'
state['valid_dialogues'] = './tests/data/tvalid.dialogues.pkl'
state['dictionary'] = './tests/data/ttrain.dict.pkl'
state[... |
def prototype_test_variational():
state = prototype_state()
state['train_dialogues'] = './tests/data/ttrain.dialogues.pkl'
state['test_dialogues'] = './tests/data/ttest.dialogues.pkl'
state['valid_dialogues'] = './tests/data/tvalid.dialogues.pkl'
state['dictionary'] = './tests/data/ttrain.dict.pkl... |
def prototype_twitter_HRED_NormOp_ClusterExp1():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['dictionary'] = '.... |
def prototype_twitter_HRED_NormOp_ClusterExp2():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['dictionary'] = '.... |
def prototype_twitter_HRED_NormOp_ClusterExp3():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['dictionary'] = '.... |
def prototype_twitter_HRED_NormOp_ClusterExp4():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['dictionary'] = '.... |
def prototype_twitter_HRED_NormOp_ClusterExp5():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['dictionary'] = '.... |
def prototype_twitter_GaussOnly_VHRED_NormOp_ClusterExp1():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['dictio... |
def prototype_twitter_GaussOnly_VHRED_NormOp_ClusterExp2():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['dictio... |
def prototype_twitter_GaussOnly_VHRED_NormOp_ClusterExp3():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['dictio... |
def prototype_twitter_GaussOnly_VHRED_NormOp_ClusterExp4():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['dictio... |
def prototype_twitter_GaussOnly_VHRED_NormOp_ClusterExp5():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['dictio... |
def prototype_twitter_GaussPiecewise_VHRED_NormOp_ClusterExp1():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['d... |
def prototype_twitter_GaussPiecewise_VHRED_NormOp_ClusterExp2():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['d... |
def prototype_twitter_GaussPiecewise_VHRED_NormOp_ClusterExp3():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['d... |
def prototype_twitter_GaussPiecewise_VHRED_NormOp_ClusterExp4():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['d... |
def prototype_twitter_GaussPiecewise_VHRED_NormOp_ClusterExp5():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['d... |
def prototype_twitter_GaussPiecewise_VHRED_NormOp_ClusterExp6():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['d... |
def prototype_twitter_GaussPiecewise_VHRED_NormOp_ClusterExp7():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['d... |
def prototype_twitter_GaussPiecewise_VHRED_NormOp_ClusterExp8():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['d... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Baseline_Exp1():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_spea... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Baseline_Exp2():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_spea... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp1():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym']... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp2():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym']... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp3():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym']... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp4():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym']... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp5():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym']... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp6():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym']... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp7():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym']... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp8():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym']... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp9():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym']... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp10():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym'... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp11():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym'... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp12():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym'... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp13():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym'... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp14():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym'... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp15():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym'... |
class AtariDreamerAgent(DreamerAgent):
def __init__(self, ModelCls=AtariDreamerModel, **kwargs):
super().__init__(ModelCls=ModelCls, **kwargs)
def make_env_to_model_kwargs(self, env_spaces):
return dict(image_shape=env_spaces.observation.shape, action_shape=env_spaces.action.shape, action_di... |
class DMCDreamerAgent(DreamerAgent):
def __init__(self, ModelCls=AtariDreamerModel, **kwargs):
super().__init__(ModelCls=ModelCls, **kwargs)
def make_env_to_model_kwargs(self, env_spaces):
return dict(image_shape=env_spaces.observation.shape, output_size=env_spaces.action.shape[0], action_sh... |
class DreamerAgent(RecurrentAgentMixin, BaseAgent):
def __init__(self, ModelCls=AgentModel, train_noise=0.4, eval_noise=0, expl_type='additive_gaussian', expl_min=0.1, expl_decay=7000, model_kwargs=None, initial_model_state_dict=None):
self.train_noise = train_noise
self.eval_noise = eval_noise
... |
def initialize_replay_buffer(self, examples, batch_spec, async_=False):
'Initializes a sequence replay buffer with single frame observations'
example_to_buffer = SamplesToBuffer(observation=examples['observation'], action=examples['action'], reward=examples['reward'], done=examples['done'])
replay_kwargs ... |
def samples_to_buffer(samples):
'Defines how to add data from sampler into the replay buffer. Called\n in optimize_agent() if samples are provided to that method. In\n asynchronous mode, will be called in the memory_copier process.'
return SamplesToBuffer(observation=samples.env.observation, action=sam... |
class ActionRepeat(EnvWrapper):
def __init__(self, env, amount=1):
super().__init__(env)
self.amount = amount
def step(self, action):
done = False
total_reward = 0
current_step = 0
while ((current_step < self.amount) and (not done)):
(obs, reward, ... |
class DeepMindControl(Env):
def __init__(self, name, size=(64, 64), camera=None):
(domain, task) = name.split('_', 1)
if (domain == 'cup'):
domain = 'ball_in_cup'
if isinstance(domain, str):
self._env = suite.load(domain, task)
else:
assert (tas... |
class AtariTrajInfo(TrajInfo):
'TrajInfo class for use with Atari Env, to store raw game score separate\n from clipped reward signal.'
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.GameScore = 0
def step(self, observation, action, reward, done, agent_info, env_info):
... |
class AtariEnv(Env):
"An efficient implementation of the classic Atari RL envrionment using the\n Arcade Learning Environment (ALE).\n\n Output `env_info` includes:\n * `game_score`: raw game score, separate from reward clipping.\n * `traj_done`: special signal which signals game-over or timeo... |
class NormalizeActions(EnvWrapper):
def __init__(self, env):
super().__init__(env)
self._mask = np.logical_and(np.isfinite(env.action_space.low), np.isfinite(env.action_space.high))
self._low = np.where(self._mask, env.action_space.low, (- 1))
self._high = np.where(self._mask, env... |
class OneHotAction(EnvWrapper):
def __init__(self, env):
assert (isinstance(env.action_space, gym.spaces.Discrete) or isinstance(env.action_space, IntBox))
super().__init__(env)
self._dtype = np.float32
@property
def action_space(self):
shape = (self.env.action_space.n,)
... |
class TimeLimit(EnvWrapper):
def __init__(self, env, duration):
super().__init__(env)
self._duration = duration
self._step = None
def step(self, action):
assert (self._step is not None), 'Must reset environment.'
(obs, reward, done, info) = self.env.step(action)
... |
class EnvWrapper(Env):
def __init__(self, env: Env):
self.env = env
def __getattr__(self, name):
if name.startswith('_'):
raise AttributeError("attempted to get missing private attribute '{}'".format(name))
return getattr(self.env, name)
def step(self, action):
... |
def make_wapper(base_class, wrapper_classes: Sequence=None, wrapper_kwargs: Sequence[Dict]=None):
'\n Creates the correct factory method with wrapper support.\n This would get passed as the EnvCls argument in the sampler.\n\n Examples:\n The following code would make a factory method for atari with ac... |
def build_and_train(slot_affinity_code, log_dir, run_ID, config_key):
affinity = affinity_from_code(slot_affinity_code)
config = configs[config_key]
variant = load_variant(log_dir)
config = update_config(config, variant)
sampler = CpuSampler(EnvCls=AtariEnv, env_kwargs=config['env'], CollectorCls=... |
def build_and_train(slot_affinity_code, log_dir, run_ID, config_key):
affinity = affinity_from_code(slot_affinity_code)
config = configs[config_key]
variant = load_variant(log_dir)
config = update_config(config, variant)
sampler = GpuSampler(EnvCls=AtariEnv, env_kwargs=config['env'], CollectorCls=... |
class ActionDecoder(nn.Module):
def __init__(self, action_size, feature_size, hidden_size, layers, dist='tanh_normal', activation=nn.ELU, min_std=0.0001, init_std=5, mean_scale=5):
super().__init__()
self.action_size = action_size
self.feature_size = feature_size
self.hidden_size ... |
class AgentModel(nn.Module):
def __init__(self, action_shape, stochastic_size=30, deterministic_size=200, hidden_size=200, image_shape=(3, 64, 64), action_hidden_size=200, action_layers=3, action_dist='one_hot', reward_shape=(1,), reward_layers=3, reward_hidden=300, value_shape=(1,), value_layers=3, value_hidden... |
class AtariDreamerModel(AgentModel):
def forward(self, observation: torch.Tensor, prev_action: torch.Tensor=None, prev_state: RSSMState=None):
(lead_dim, T, B, img_shape) = infer_leading_dims(observation, 3)
observation = ((observation.reshape((T * B), *img_shape).type(self.dtype) / 255.0) - 0.5)... |
class DenseModel(nn.Module):
def __init__(self, feature_size: int, output_shape: tuple, layers: int, hidden_size: int, dist='normal', activation=nn.ELU):
super().__init__()
self._output_shape = output_shape
self._layers = layers
self._hidden_size = hidden_size
self._dist =... |
class SampleDist():
def __init__(self, dist: torch.distributions.Distribution, samples=100):
self._dist = dist
self._samples = samples
@property
def name(self):
return 'SampleDist'
def __getattr__(self, name):
return getattr(self._dist, name)
def mean(self):
... |
class ObservationEncoder(nn.Module):
def __init__(self, depth=32, stride=2, shape=(3, 64, 64), activation=nn.ReLU):
super().__init__()
self.convolutions = nn.Sequential(nn.Conv2d(shape[0], (1 * depth), 4, stride), activation(), nn.Conv2d((1 * depth), (2 * depth), 4, stride), activation(), nn.Conv... |
class ObservationDecoder(nn.Module):
def __init__(self, depth=32, stride=2, activation=nn.ReLU, embed_size=1024, shape=(3, 64, 64)):
super().__init__()
self.depth = depth
self.shape = shape
(c, h, w) = shape
conv1_kernel_size = 6
conv2_kernel_size = 6
conv3... |
def conv_out(h_in, padding, kernel_size, stride):
return int((((((h_in + (2.0 * padding)) - (kernel_size - 1.0)) - 1.0) / stride) + 1.0))
|
def output_padding(h_in, conv_out, padding, kernel_size, stride):
return ((((h_in - ((conv_out - 1) * stride)) + (2 * padding)) - (kernel_size - 1)) - 1)
|
def conv_out_shape(h_in, padding, kernel_size, stride):
return tuple((conv_out(x, padding, kernel_size, stride) for x in h_in))
|
def output_padding_shape(h_in, conv_out, padding, kernel_size, stride):
return tuple((output_padding(h_in[i], conv_out[i], padding, kernel_size, stride) for i in range(len(h_in))))
|
def stack_states(rssm_states: list, dim):
return RSSMState(torch.stack([state.mean for state in rssm_states], dim=dim), torch.stack([state.std for state in rssm_states], dim=dim), torch.stack([state.stoch for state in rssm_states], dim=dim), torch.stack([state.deter for state in rssm_states], dim=dim))
|
def get_feat(rssm_state: RSSMState):
return torch.cat((rssm_state.stoch, rssm_state.deter), dim=(- 1))
|
def get_dist(rssm_state: RSSMState):
return td.independent.Independent(td.Normal(rssm_state.mean, rssm_state.std), 1)
|
class TransitionBase(nn.Module):
def __init__(self):
super().__init__()
def forward(self, prev_action, prev_state):
':return: next state'
raise NotImplementedError
|
class RepresentationBase(nn.Module):
def __init__(self):
super().__init__()
def forward(self, obs_embed, prev_action, prev_state):
':return: next state'
raise NotImplementedError
|
class RollOutModule(nn.Module):
def __init__(self):
super().__init__()
def forward(self, steps, obs_embed, prev_action, prev_state):
raise NotImplementedError
|
class RSSMTransition(TransitionBase):
def __init__(self, action_size, stochastic_size=30, deterministic_size=200, hidden_size=200, activation=nn.ELU, distribution=td.Normal):
super().__init__()
self._action_size = action_size
self._stoch_size = stochastic_size
self._deter_size = d... |
class RSSMRepresentation(RepresentationBase):
def __init__(self, transition_model: RSSMTransition, obs_embed_size, action_size, stochastic_size=30, deterministic_size=200, hidden_size=200, activation=nn.ELU, distribution=td.Normal):
super().__init__()
self._transition_model = transition_model
... |
class RSSMRollout(RollOutModule):
def __init__(self, representation_model: RSSMRepresentation, transition_model: RSSMTransition):
super().__init__()
self.representation_model = representation_model
self.transition_model = transition_model
def forward(self, steps: int, obs_embed: torc... |
def get_log_dir(experiment_name):
yyyymmdd = datetime.datetime.today().strftime('%Y%m%d')
log_dir = osp.join(LOG_DIR, 'local', yyyymmdd, experiment_name)
return log_dir
|
def log_exps_tree(exp_dir, log_dirs, runs_per_setting):
os.makedirs(exp_dir, exist_ok=True)
with open(osp.join(exp_dir, 'experiments_tree.txt'), 'w') as f:
f.write(f'''Experiment manager process ID: {os.getpid()}.
''')
f.write(f'''Number of settings (experiments) to run: {len(log_dirs)} ({(ru... |
def log_num_launched(exp_dir, n, total):
with open(osp.join(exp_dir, 'num_launched.txt'), 'w') as f:
f.write(f'''Experiments launched so far: {n} out of {total}.
''')
|
def launch_experiment(script, run_slot, affinity_code, log_dir, variant, run_ID, args):
'Launches one learning run using ``subprocess.Popen()`` to call the\n python script. Calls the script as:\n ``python {script} {slot_affinity_code} {log_dir} {run_ID} {*args}``\n If ``affinity_code["all_cpus"]`` is pr... |
def run_experiments(script, affinity_code, experiment_title, runs_per_setting, variants, log_dirs, common_args=None, runs_args=None, data_dir=None):
"Call in a script to run a set of experiments locally on a machine. Uses\n the ``launch_experiment()`` function for each individual run, which is a\n call to ... |
def video_summary(tag, video, step=None, fps=20):
writer: SummaryWriter = logger.get_tf_summary_writer()
writer.add_video(tag=tag, vid_tensor=video, global_step=step, fps=fps)
|
def get_parameters(modules: Iterable[Module]):
'\n Given a list of torch modules, returns a list of their parameters.\n :param modules: iterable of modules\n :returns: a list of parameters\n '
model_parameters = []
for module in modules:
model_parameters += list(module.parameters())
... |
class FreezeParameters():
def __init__(self, modules: Iterable[Module]):
"\n Context manager to locally freeze gradients.\n In some cases with can speed up computation because gradients aren't calculated for these listed modules.\n example:\n ```\n with FreezeParameters... |
def build_and_train(log_dir, game='pong', run_ID=0, cuda_idx=None, eval=False, save_model='last', load_model_path=None):
params = (torch.load(load_model_path) if load_model_path else {})
agent_state_dict = params.get('agent_state_dict')
optimizer_state_dict = params.get('optimizer_state_dict')
action_... |
def build_and_train(log_dir, game='cartpole_balance', run_ID=0, cuda_idx=None, eval=False, save_model='last', load_model_path=None):
params = (torch.load(load_model_path) if load_model_path else {})
agent_state_dict = params.get('agent_state_dict')
optimizer_state_dict = params.get('optimizer_state_dict')... |
@pytest.mark.parametrize('dist', ['tanh_normal', 'one_hot', 'relaxed_one_hot', 'not_implemented_dist'])
def test_action_decoder(dist):
batch_size = 4
action_size = 10
feature_size = 20
hidden_size = 40
layers = 5
try:
action_decoder = ActionDecoder(action_size, feature_size, hidden_siz... |
@pytest.mark.parametrize('dist', ['tanh_normal', 'one_hot', 'relaxed_one_hot'])
def test_agent(dist):
batch_size = 1
action_shape = (2,)
deterministic_size = 200
obs_shape = (3, 64, 64)
agent_model = AgentModel(action_shape, deterministic_size=deterministic_size, image_shape=obs_shape, action_dist... |
@pytest.mark.parametrize('dist', ['normal', 'binary'])
def test_dense_model(dist):
shape = (1,)
units = 20
feature_size = 20
layers = 5
batch_size = 2
features = torch.randn((batch_size, feature_size))
try:
dense = DenseModel(feature_size, shape, layers, units, dist)
except Not... |
def test_dist():
batch_size = 4
dist_size = 3
samples = 10
mean = torch.randn(batch_size, dist_size)
std = torch.rand(batch_size, dist_size)
dist = torch.distributions.Normal(mean, std)
transform = TanhBijector()
sign = transform.sign
dist = torch.distributions.TransformedDistribut... |
def test_observation_encoder(shape=(3, 64, 64)):
encoder = ObservationEncoder()
batch_size = 2
(c, h, w) = shape
image_obs = torch.randn(batch_size, c, h, w)
with torch.no_grad():
embedding: torch.Tensor = encoder(image_obs)
assert (embedding.size(0) == batch_size)
assert (embeddin... |
def test_observation_decoder(shape=(3, 64, 64)):
decoder = ObservationDecoder()
batch_size = 2
(c, h, w) = shape
embedding = torch.randn(batch_size, 1024)
with torch.no_grad():
obs_dist: torch.distributions.Normal = decoder(embedding)
obs_sample: torch.Tensor = obs_dist.sample()
as... |
@pytest.mark.parametrize('shape', [(3, 64, 64), (4, 104, 64)])
def test_observation(shape):
batch_size = 2
(c, h, w) = shape
encoder = ObservationEncoder(shape=shape)
decoder = ObservationDecoder(embed_size=encoder.embed_size, shape=shape)
image_obs = torch.randn(batch_size, c, h, w)
with torc... |
def test_observation_reconstruction(shape=(4, 104, 64)):
batch_size = 2
(c, h, w) = shape
depth = 32
stride = 2
activation = torch.nn.ReLU
conv1 = torch.nn.Conv2d(c, (1 * depth), 6, stride)
conv1_shape = conv_out_shape((h, w), 0, 6, 2)
conv1_pad = output_padding_shape((h, w), conv1_sha... |
def test_rssm():
action_size = 10
obs_embed_size = 100
stochastic_size = 30
deterministic_size = 200
batch_size = 4
transition_model = RSSMTransition(action_size, stochastic_size, deterministic_size)
representation_model = RSSMRepresentation(transition_model, obs_embed_size, action_size, s... |
def test_rollouts():
action_size = 10
obs_embed_size = 100
stochastic_size = 30
deterministic_size = 200
batch_size = 4
time_steps = 10
transition_model = RSSMTransition(action_size, stochastic_size, deterministic_size)
representation_model = RSSMRepresentation(transition_model, obs_em... |
def test_freeze_parameters():
linear_module_1 = nn.Linear(4, 3)
linear_module_2 = nn.Linear(3, 2)
input_tensor = torch.randn(4)
with FreezeParameters([linear_module_2]):
output_tensor = linear_module_2(linear_module_1(input_tensor))
assert (output_tensor.grad_fn is not None)
input_tens... |
def test_get_parameters():
linear_module_1 = nn.Linear(4, 3)
linear_module_2 = nn.Linear(3, 2)
params = get_parameters([linear_module_1])
assert (len(params) == 2)
params = get_parameters([linear_module_1, linear_module_2])
assert (len(params) == 4)
|
def restrict_gpu_memory(per_process_gpu_memory_fraction: float=0.9):
import os
import tensorflow as tf
import keras
thread_count = os.environ.get('OMP_NUM_THREADS')
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=per_process_gpu_memory_fraction)
config = (tf.ConfigProto(gpu_options... |
class DataDirectories():
def __init__(self, data_directory: Path=(home_directory() / 'speechless-data')):
self.data_directory = data_directory
self.corpus_base_directory = (data_directory / 'corpus')
self.spectrogram_cache_base_directory = (data_directory / 'spectrogram-cache')
se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.