code
stringlengths
17
6.64M
class WaitPrint(threading.Thread): def __init__(self, t, message): super().__init__() self.t = t self.message = message self.running = True def stop(self): self.running = False def run(self): for _ in range(int((self.t // 0.1))): time.sleep(0....
def show_running(func): @wraps(func) def g(*args, **kargs): x = WaitPrint(2, '{}({})... '.format(func.__name__, ', '.join(([repr(x) for x in args] + ['{}={}'.format(key, repr(value)) for (key, value) in kargs.items()])))) x.start() t = time.perf_counter() r = func(*args, **kar...
def cached_dirpklgz(dirname): '\n Cache a function with a directory\n ' def decorator(func): '\n The actual decorator\n ' @lru_cache(maxsize=None) @wraps(func) def wrapper(*args): '\n The wrapper of the function\n ' ...
def test_so3_rfft(b_in, b_out, device): x = torch.randn((2 * b_in), (2 * b_in), (2 * b_in), dtype=torch.float, device=device) from s2cnn.soft.so3_fft import so3_rfft y1 = so3_rfft(x, b_out=b_out) from s2cnn import so3_rft, so3_soft_grid import lie_learn.spaces.S3 as S3 weights = torch.tensor(S...
def test_inverse(f, g, b_in, b_out, device, complex): if complex: x = torch.randn((2 * b_in), (2 * b_in), (2 * b_in), 2, dtype=torch.float, device=device) else: x = torch.randn((2 * b_in), (2 * b_in), (2 * b_in), dtype=torch.float, device=device) x = g(f(x, b_out=b_out), b_out=b_in) y ...
def test_inverse2(f, g, b_in, b_out, device): x = torch.randn(((b_in * ((4 * (b_in ** 2)) - 1)) // 3), 2, dtype=torch.float, device=device) x = g(f(x, b_out=b_out), b_out=b_in) y = g(f(x, b_out=b_out), b_out=b_in) assert ((x - y).abs().max().item() < (0.0001 * y.abs().mean().item()))
def compare_cpu_gpu(f, x): z1 = f(x.cpu()) z2 = f(x.cuda()).cpu() q = ((z1 - z2).abs().max().item() / z1.std().item()) assert (q < 0.0001)
class ConveRTModelConfig(NamedTuple): num_embed_hidden: int = 512 feed_forward1_hidden: int = 2048 feed_forward2_hidden: int = 1024 num_attention_project: int = 64 vocab_size: int = 25000 num_encoder_layers: int = 6 dropout_rate: float = 0.0 n: int = 121 relative_attns: list = [3, ...
class ConveRTTrainConfig(NamedTuple): sp_model_path: str = os.path.join(dirname, 'data/en.wiki.bpe.vs25000.model') dataset_path: str = os.path.join(dirname, 'data/sample-dataset.json') test_dataset_path: str = 'data/sample-dataset.json' model_save_dir: str = 'lightning_logs/checkpoints/' log_dir: ...
class LossFunction(nn.Module): @staticmethod def cosine_similarity_matrix(context_embed: torch.Tensor, reply_embed: torch.Tensor) -> torch.Tensor: assert (context_embed.size(0) == reply_embed.size(0)) cosine_similarity = torch.matmul(context_embed, reply_embed.T) return cosine_similar...
@dataclass class EncoderInputFeature(): input_ids: torch.Tensor attention_mask: torch.Tensor position_ids: torch.Tensor input_lengths: torch.Tensor def pad_sequence(self, seq_len: int): self.input_ids = pad(self.input_ids, [0, (seq_len - self.input_ids.size(0))], 'constant', 0) se...
@dataclass class EmbeddingPair(): context: EncoderInputFeature reply: EncoderInputFeature
class DataModule(pl.LightningDataModule): def __init__(self): super().__init__() self.input_attributes = ['input_ids', 'attention_mask', 'position_ids', 'input_lengths'] def batching_input_features(self, encoder_inputs: List[EncoderInputFeature]) -> EncoderInputFeature: max_seq_len =...
class DatasetInstance(NamedTuple): context: List[str] response: str
def load_instances_from_reddit_json(dataset_path: str) -> List[DatasetInstance]: instances: List[DatasetInstance] = [] with open(dataset_path) as f: for line in f: x = json.loads(line) context_keys = sorted([key for key in x.keys() if ('context' in key)]) instance =...
class RedditData(torch.utils.data.Dataset): def __init__(self, instances: List[DatasetInstance], sp_processor: SentencePieceProcessor, truncation_length: int): self.sp_processor = sp_processor self.instances = instances self.truncation_length = truncation_length def __len__(self): ...
class LearningRateDecayCallback(pl.Callback): def __init__(self, config, lr_decay=True): super().__init__() self.lr_warmup_end = config.lr_warmup_end self.lr_warmup_start = config.lr_warmup_start self.learning_rate = config.learning_rate self.warmup_batch = config.warmup_b...
def set_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed)
def find_subword_params(model): 'Long winded helper fn to return Subword Embedding Params for clipping, as they are the only parameters that\n are gradient clipped in the paper, only calculated once after model instantiation, but before training' embeds = set() for (mn, m) in model.named_modules(): ...
class SingleContextConvert(pl.LightningModule): def __init__(self, model_config: ConveRTModelConfig, train_config: ConveRTTrainConfig): super().__init__() self.model_config = model_config self.train_config = train_config self.transformer_layers = TransformerLayers(model_config) ...
def _parse_args(): 'Parse command-line arguments.' parser = argparse.ArgumentParser() parser.add_argument('--progress_bar_refresh_rate', type=int, default=1) parser.add_argument('--row_log_interval', type=int, default=1) args = parser.parse_args() return args
def main(**kwargs): set_seed(1) train_config = ConveRTTrainConfig() model_config = ConveRTModelConfig() tokenizer = SentencePieceProcessor() args = _parse_args() tokenizer.Load(train_config.sp_model_path) train_instances = load_instances_from_reddit_json(train_config.dataset_path) RD =...
@pytest.fixture def config(): return ConveRTTrainConfig()
@pytest.fixture def tokenizer() -> SentencePieceProcessor: tokenizer = SentencePieceProcessor() tokenizer.Load(config.sp_model_path) return tokenizer
def test_load_instances_from_reddit_json(config): instances = load_instances_from_reddit_json(config.dataset_path) assert (len(instances) == 1000)
class TestModelTraining(unittest.TestCase): 'Check can overfit small batch etc. without issues' def test_fast_dev_run(self): t = time() try: main(fast_dev_run=True) except: self.fail('Obvious Training Problem!') time_taken = (time() - t) self.as...
@pytest.fixture def model_config(): return ConveRTModelConfig()
@pytest.fixture def train_config(): return ConveRTTrainConfig(train_batch_size=64, split_size=8, learning_rate=2e-05)
def test_circulant_t(): assert (circulant_mask(50, 47).sum().item() == 2494) try: circulant_mask(47, 50) circulant_mask(47, 47) circulant_mask(47, 45) except ExceptionType: self.fail('ciculant_t Failed')
def test_SubwordEmbedding(train_config, model_config): embedding = SubwordEmbedding(model_config) input_token_ids = torch.randint(high=model_config.vocab_size, size=(train_config.train_batch_size, SEQ_LEN)) positional_input = torch.randint(high=model_config.vocab_size, size=(train_config.train_batch_size,...
def test_SelfAttention(model_config, train_config): attention = SelfAttention(model_config, relative_attention) query = torch.rand(train_config.train_batch_size, SEQ_LEN, model_config.num_embed_hidden) attn_mask = torch.ones(query.size()[:(- 1)], dtype=torch.float) output = attention(query, attn_mask)...
def test_FeedForward1(train_config, model_config): ff1 = FeedForward1(model_config.num_embed_hidden, model_config.feed_forward1_hidden, model_config.dropout_rate) embed = torch.rand(train_config.train_batch_size, SEQ_LEN, model_config.num_embed_hidden) output = ff1(embed) assert (output.size() == embe...
def test_SharedInnerBlock(train_config, model_config): from random import randrange SIB = SharedInnerBlock(model_config, model_config.relative_attns[randrange(6)]) embed = torch.rand(train_config.train_batch_size, SEQ_LEN, model_config.num_embed_hidden) attn_mask = torch.ones(embed.size()[:(- 1)], dty...
def test_MultiheadAttention(train_config, model_config): MHA = MultiheadAttention(model_config) embed = torch.rand(train_config.train_batch_size, SEQ_LEN, model_config.num_embed_hidden) attn_mask = torch.ones(embed.size()[:(- 1)], dtype=torch.float) assert ((model_config.num_embed_hidden % MHA.num_att...
def test_TransformerLayers(model_config): TL = TransformerLayers(model_config) path = str(((Path(__file__).parents[1].resolve() / 'data') / 'batch_context.pickle')) with open(path, 'rb') as input_file: encoder_input = pickle.load(input_file) print(type(encoder_input)) embedding = SubwordEm...
def test_FeedForward2(model_config, train_config): embed = torch.rand(train_config.train_batch_size, SEQ_LEN, (model_config.num_embed_hidden * model_config.num_attention_heads)) attn_mask = torch.ones(embed.size()[:(- 1)], dtype=torch.float) FF2 = FeedForward2(model_config) assert (FF2(embed, attn_mas...
def wave_frontend(x, is_training): 'Function implementing the front-end proposed by Lee et al. 2017.\n Lee, et al. "Sample-level Deep Convolutional Neural Networks for Music\n Auto-tagging Using Raw Waveforms."\n arXiv preprint arXiv:1703.01789 (2017).\n\n - \'x\': placeholder whith the input...
def spec_frontend(x, is_training, config, num_filt): "Function implementing the proposed spectrogram front-end.\n\n - 'route_out': is the output of the front-end, and therefore the input of\n this function.\n - 'is_training': placeholder indicating weather it is training or test\n phase, for d...
def backend(route_out, is_training, config, num_units): "Function implementing the proposed back-end.\n\n - 'route_out': is the output of the front-end, and therefore the input of\n this function.\n - 'is_training': placeholder indicating weather it is training or test\n phase, for dropout or ...
def build_model(x, is_training, config): "Function implementing an example of how to build a model with the\n functions above.\n\n - 'x': placeholder whith the input.\n - 'is_training': placeholder indicating weather it is training or test\n phase, for dropout or batch norm.\n - 'config': d...
def extract_audioset_features(ids, id2audio_path, id2label): first_audio = True for i in ids: if first_audio: input_data = vggish_input.wavfile_to_examples(id2audio_path[i]) ground_truth = np.repeat(id2label[i], input_data.shape[0], axis=0) identifiers = np.repeat(i...
def select(x, config, is_training, reuse=False): if (config['model_number'] == 2): return vgg_bn(x, config, is_training, 10, reuse) elif (config['model_number'] == 12): return vgg_bn(log_learn(x), config, is_training, 10, reuse) raise RuntimeError("ERROR: Model {} can't be found!".format(c...
def vgg_bn(x, config, is_training, output_filters, reuse=False): with tf.variable_scope('vggish', reuse=reuse): NUMBER_FILTERS = 128 print(('VGG with batchnorm! #filters: ' + str(NUMBER_FILTERS))) print(('Input: ' + str(x.get_shape))) bn_input = tf.layers.batch_normalization(x, tra...
def log_learn(x): with tf.variable_scope('log_learn'): ta = tf.Variable(tf.constant(7, dtype=tf.float32), name='ta', trainable=True) ba = tf.Variable(tf.constant(1, dtype=tf.float32), name='ba', trainable=True) alpha = tf.exp(ta, name='alpha') beta = tf.log((1 + tf.exp(ba)), name='...
def model_number(x, is_training, config): if (config['model_number'] == 0): print('\nMODEL: SB-CNN') print('-----------------------------------\n') return sb_cnn(x, is_training, config) elif (config['model_number'] == 1): print('\nMODEL: SB-CNN | BN input') print('-----...
def log_learn(x): with tf.variable_scope('log_learn'): ta = tf.Variable(tf.constant(7, dtype=tf.float32), name='ta', trainable=True) ba = tf.Variable(tf.constant(1, dtype=tf.float32), name='ba', trainable=True) alpha = tf.exp(ta, name='alpha') beta = tf.log((1 + tf.exp(ba)), name='...
def vgg(x, is_training, config, num_filters): with tf.variable_scope('vggish'): print(('[SMALL FILTERS] Input: ' + str(x.get_shape))) input_layer = tf.expand_dims(x, 3) bn_input = tf.layers.batch_normalization(input_layer, training=is_training, axis=(- 1)) conv1 = tf.layers.conv2d(...
def timbre(x, is_training, config, num_filters): with tf.variable_scope('timbre'): print(('[CNN SINGLE] Input: ' + str(x.get_shape))) input_layer = tf.expand_dims(x, 3) bn_input = tf.layers.batch_normalization(input_layer, training=is_training, axis=(- 1)) conv1 = tf.layers.conv2d(...
def sb_cnn_core(input_, is_training, config): print(input_.get_shape) conv1 = tf.layers.conv2d(inputs=input_, filters=24, kernel_size=[5, 5], padding='valid', activation=tf.nn.relu, name='1CNN', kernel_initializer=tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG', uniform=True)) pr...
def sb_cnn(x, is_training, config): print(('Input: ' + str(x.get_shape))) input_layer = tf.expand_dims(x, 3) return sb_cnn_core(input_layer, is_training, config)
def sb_cnn_bn(x, is_training, config): print(('Input: ' + str(x.get_shape))) input_layer = tf.expand_dims(x, 3) print(input_layer.get_shape) bn_input = tf.layers.batch_normalization(input_layer, training=is_training, axis=(- 1)) return sb_cnn_core(bn_input, is_training, config)
def compute_audio_repr(audio_file, audio_repr_file): if (config['type'] == 'audioset'): audio_repr = vggish_input.wavfile_to_examples(audio_file) print(audio_repr.shape) else: (audio, sr) = librosa.load(audio_file, sr=config['resample_sr']) if (config['type'] == 'waveform'): ...
def do_process(files, index): try: [id, audio_file, audio_repr_file] = files[index] if (not os.path.exists(audio_repr_file[:(audio_repr_file.rfind('/') + 1)])): path = Path(audio_repr_file[:(audio_repr_file.rfind('/') + 1)]) path.mkdir(parents=True, exist_ok=True) l...
def process_files(files): if DEBUG: print('WARNING: Parallelization is not used!') for index in range(0, len(files)): do_process(files, index) else: Parallel(n_jobs=config['num_processing_units'])((delayed(do_process)(files, index) for index in range(0, len(files))))
def eval(config, ids, id2audio_repr_path, support_set, id2gt, id2label, tf_vars, vis_vars): [id_string, save_latents, track_accuracies, printing, transfer_learning, model_folder] = vis_vars if transfer_learning: [sess, x, q, log_p_y, emb_q, emb_prototypes] = tf_vars pack = [config, 'overlap_sa...
def fetch_data(classes_vector, label2selectedIDs, id2audio_repr_path, id2gt, config, transfer_learning=False): set_dic = {} gt_dic = {} id_dic = {} minimum_number_of_patches = np.inf total_number_of_patches = 0 for c in classes_vector: preprocess_batch_size = np.min([len(label2selected...
def compute_mean_std(index_file, percentage_index_file): fgt = open(((config_file.DATA_FOLDER + config['audio_representation_folder']) + index_file)) num_lines = sum((1 for line in open(((config_file.DATA_FOLDER + config['audio_representation_folder']) + index_file)))) tmp = np.array([]) count = 0 ...
def eval(config, ids, id2audio_repr_path, support_set, id2gt, id2label, tf_vars, vis_vars): [id_string, save_latents, track_accuracies, printing, transfer_learning, model_folder] = vis_vars if transfer_learning: [sess, x, q, log_p_y, emb_q, emb_prototypes] = tf_vars pack = [config, 'overlap_sa...
def fetch_data(classes_vector, label2selectedIDs, id2audio_repr_path, id2gt, config, transfer_learning=False): set_dic = {} gt_dic = {} id_dic = {} minimum_number_of_patches = np.inf total_number_of_patches = 0 for c in classes_vector: preprocess_batch_size = np.min([len(label2selected...
def eval(config, ids, id2audio_repr_path, support_set, id2gt, id2label, tf_vars, vis_vars): [id_string, save_latents, track_accuracies, printing, transfer_learning, model_folder] = vis_vars if transfer_learning: [sess, x, q, log_p_y, emb_q, emb_prototypes] = tf_vars pack = [config, 'overlap_sa...
def fetch_data(classes_vector, label2selectedIDs, id2audio_repr_path, id2gt, config, transfer_learning=False): set_dic = {} gt_dic = {} id_dic = {} minimum_number_of_patches = np.inf total_number_of_patches = 0 for c in classes_vector: preprocess_batch_size = np.min([len(label2selected...
def euclidean_distance(a, b): (N, D) = (tf.shape(a)[0], tf.shape(a)[1]) M = tf.shape(b)[0] a = tf.tile(tf.expand_dims(a, axis=1), (1, M, 1)) b = tf.tile(tf.expand_dims(b, axis=0), (N, 1, 1)) return tf.reduce_mean(tf.square((a - b)), axis=2)
def cosine_distance(a, b): norm_a = tf.nn.l2_normalize(a, axis=1) norm_b = tf.nn.l2_normalize(b, axis=1) prod = tf.matmul(norm_a, norm_b, adjoint_b=True) return (1 - prod)
def get_epoch_time(): return int((datetime.now() - datetime(1970, 1, 1)).total_seconds())
def label2onehot_exp(label, experiment_classes): onehot = np.zeros(len(experiment_classes)) position = int(np.squeeze(np.where((label == np.array(experiment_classes))))) onehot[position] = 1 return onehot
def label2onehot(label, length): onehot = np.zeros(length) onehot[label] = 1 return onehot
def onehot2label(gt): label = np.int(np.squeeze(np.where((np.array(gt) == max(gt))))) return label
def count_params(trainable_variables): return np.sum([np.prod(v.get_shape().as_list()) for v in trainable_variables])
def load_id2label(gt_file): ids = [] fgt = open(gt_file) id2label = dict() for line in fgt.readlines(): (id, gt) = line.strip().split('\t') id2label[id] = onehot2label(eval(gt)) ids.append(id) return (ids, id2label)
def load_id2gt(gt_file): ids = [] fgt = open(gt_file) id2gt = dict() for line in fgt.readlines(): (id, gt) = line.strip().split('\t') id2gt[id] = eval(gt) ids.append(id) return (ids, id2gt)
def load_label2ids(id2label): label2ids = {} for (id, label) in id2label.items(): if (label in label2ids): label2ids[label].append(id) else: label2ids[label] = [id] return label2ids
def load_id2audiopath(index_file): f = open(index_file) id2audiopath = dict() for line in f.readlines(): (id, path) = line.strip().split('\t') id2audiopath[id] = path return id2audiopath
def load_id2audioReprPath(index_file): audioReprPaths = [] fspec = open(index_file) id2audioReprPath = dict() for line in fspec.readlines(): (id, path, _) = line.strip().split('\t') id2audioReprPath[id] = path audioReprPaths.append(path) return (audioReprPaths, id2audioRepr...
def load_id2length(index_file): f = open(index_file) id2length = dict() for line in f.readlines(): (id, length) = line.strip().split('\t') id2length[id] = int(length) return id2length
def accuracy_with_aggergated_predictions(pred_array, id_array, ids, id2label): y_pred = [] y_true = [] for id in ids: try: avg = np.mean(pred_array[np.where((id_array == id))], axis=0) idx_prediction = int(np.where((avg == max(avg)))[0][0]) y_pred.append(idx_pre...
def few_shot_data_preparation(all_ids_train, all_ids_test, classes_vector, label2ids_train, label2ids_test, config): if (config['n_shot'] == np.inf): ids_train = all_ids_train ids_test = all_ids_test print('Train IDs: ALL!') label2selectedIDs = {} for c in classes_vector: ...
def audioset_model(input_signal, reuse=False): slim = tf.contrib.slim with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_initializer=tf.truncated_normal_initializer(stddev=vggish_params.INIT_STDDEV), biases_initializer=tf.zeros_initializer(), activation_fn=tf.nn.relu, trainable=True), slim.arg_s...
def waveform_to_examples(data, sample_rate): 'Converts audio waveform into an array of examples for VGGish.\n\n Args:\n data: np.array of either one dimension (mono) or two dimensions\n (multi-channel, with the outer dimension representing channels).\n Each sample is generally expected to lie in the...
def wavfile_to_examples(wav_file): 'Convenience wrapper around waveform_to_examples() for a common WAV format.\n\n Args:\n wav_file: String path to a file, or a file-like object. The file\n is assumed to contain WAV audio data with signed 16-bit PCM samples.\n\n Returns:\n See waveform_to_examples.\n ...
def define_vggish_slim(training=False): "Defines the VGGish TensorFlow model.\n\n All ops are created in the current default graph, under the scope 'vggish/'.\n\n The input is a placeholder named 'vggish/input_features' of type float32 and\n shape [batch_size, num_frames, num_bands] where batch_size is variabl...
def load_vggish_slim_checkpoint(session, checkpoint_path): 'Loads a pre-trained VGGish-compatible checkpoint.\n\n This function can be used as an initialization function (referred to as\n init_fn in TensorFlow documentation) which is called in a Session after\n initializating all variables. When used as an ini...
class BaseAgent(object): '\n Class for the basic agent objects.\n To define your own agent, subclass this class and implement the functions below.\n ' def __init__(self, env, policy, logger, storage, device, num_checkpoints): '\n env: (gym.Env) environment following the openAI Gym API...
class PPO(BaseAgent): def __init__(self, env, policy, logger, storage, device, n_checkpoints, n_steps=128, n_envs=8, epoch=3, mini_batch_per_epoch=8, mini_batch_size=(32 * 8), gamma=0.99, lmbda=0.95, learning_rate=0.00025, grad_clip_norm=0.5, eps_clip=0.2, value_coef=0.5, entropy_coef=0.01, normalize_adv=True, n...
class NoopResetEnv(gym.Wrapper): def __init__(self, env, noop_max=30): 'Sample initial states by taking random number of no-ops on reset.\n No-op is assumed to be action 0.\n ' gym.Wrapper.__init__(self, env) self.noop_max = noop_max self.override_num_noops = None ...
class FireResetEnv(gym.Wrapper): def __init__(self, env): 'Take action on reset for environments that are fixed until firing.' gym.Wrapper.__init__(self, env) assert (env.unwrapped.get_action_meanings()[1] == 'FIRE') assert (len(env.unwrapped.get_action_meanings()) >= 3) def ...
class EpisodicLifeEnv(gym.Wrapper): def __init__(self, env): 'Make end-of-life == end-of-episode, but only reset on true game over.\n Done by DeepMind for the DQN and co. since it helps value estimation.\n ' gym.Wrapper.__init__(self, env) self.lives = 0 self.was_rea...
class MaxAndSkipEnv(gym.Wrapper): def __init__(self, env, skip=4): 'Return only every `skip`-th frame' gym.Wrapper.__init__(self, env) self._obs_buffer = np.zeros(((2,) + env.observation_space.shape), dtype=np.uint8) self._skip = skip def step(self, action): 'Repeat a...
class ClipRewardEnv(gym.RewardWrapper): def __init__(self, env): gym.RewardWrapper.__init__(self, env) def reward(self, reward): 'Bin reward to {+1, 0, -1} by its sign.' return np.sign(reward) def step(self, act): 'Bin reward to {+1, 0, -1} by its sign.' (s, rew,...
class WarpFrame(gym.ObservationWrapper): def __init__(self, env, width=84, height=84, grayscale=True, dict_space_key=None): '\n Warp frames to 84x84 as done in the Nature paper and later work.\n If the environment uses dictionary observations, `dict_space_key` can be specified which indicat...
class FrameStack(gym.Wrapper): def __init__(self, env, k): 'Stack k last frames.\n Returns lazy array, which is much more memory efficient.\n See Also\n --------\n baselines.common.atari_wrappers.LazyFrames\n ' gym.Wrapper.__init__(self, env) self.k = k ...
class ScaledFloatFrame(gym.ObservationWrapper): def __init__(self, env): gym.ObservationWrapper.__init__(self, env) self.observation_space = gym.spaces.Box(low=0, high=1, shape=env.observation_space.shape, dtype=np.float32) def observation(self, observation): return (np.array(observa...
class LazyFrames(object): def __init__(self, frames): "This object ensures that common frames between the observations are only stored once.\n It exists purely to optimize memory usage which can be huge for DQN's 1M frames replay\n buffers.\n This object should only be converted to n...
class TransposeFrame(gym.ObservationWrapper): def __init__(self, env): gym.ObservationWrapper.__init__(self, env) obs_shape = self.observation_space.shape self.observation_space = gym.spaces.Box(low=0, high=1, shape=(obs_shape[2], obs_shape[0], obs_shape[1]), dtype=np.float32) def ob...
def wrap_deepmind(env, episode_life=True, preprocess=True, max_and_skip=True, clip_rewards=True, no_op_reset=True, history_length=4, scale=True, transpose=True): 'Configure environment for DeepMind-style Atari.' if no_op_reset: env = NoopResetEnv(env, noop_max=30) if max_and_skip: env = Ma...
def worker(worker_id, env, master_end, worker_end): master_end.close() while True: (cmd, data) = worker_end.recv() if (cmd == 'step'): (ob, reward, done, info) = env.step(data) if done: ob = env.reset() worker_end.send((ob, reward, done, info...
class ParallelEnv(object): '\n This class\n ' def __init__(self, num_processes, env): self.nenvs = num_processes self.waiting = False self.closed = False self.workers = [] self.observation_space = env.observation_space self.action_space = env.action_space...
class Logger(object): def __init__(self, n_envs, logdir): self.start_time = time.time() self.n_envs = n_envs self.logdir = logdir self.episode_rewards = [] for _ in range(n_envs): self.episode_rewards.append([]) self.episode_len_buffer = deque(maxlen=40...
def set_global_seeds(seed): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True
def set_global_log_levels(level): gym.logger.set_level(level)
def orthogonal_init(module, gain=nn.init.calculate_gain('relu')): if (isinstance(module, nn.Linear) or isinstance(module, nn.Conv2d)): nn.init.orthogonal_(module.weight.data, gain) nn.init.constant_(module.bias.data, 0) return module