Search is not available for this dataset
text
stringlengths
75
104k
def training_loop(self): """Context manager wrapping the training loop, updates step counters.""" if not self.restarting: self._write_counters(self._local_step_at_start, self._global_step) tf.logging.info( "Training %s up to %d, %d to go", self.model_mode, self.target_local_step, self...
def _read_words(filename): """Reads words from a file.""" with tf.gfile.GFile(filename, "r") as f: if sys.version_info[0] >= 3: return f.read().replace("\n", " %s " % EOS).split() else: return f.read().decode("utf-8").replace("\n", " %s " % EOS).split()
def _build_vocab(filename, vocab_path, vocab_size): """Reads a file to build a vocabulary of `vocab_size` most common words. The vocabulary is sorted by occurrence count and has one word per line. Originally from: https://github.com/tensorflow/models/blob/master/tutorials/rnn/ptb/reader.py Args: file...
def _get_token_encoder(vocab_dir, vocab_name, filename): """Reads from file and returns a `TokenTextEncoder` for the vocabulary.""" vocab_path = os.path.join(vocab_dir, vocab_name) if not tf.gfile.Exists(vocab_path): _build_vocab(filename, vocab_path, 10000) return text_encoder.TokenTextEncoder(vocab_path)
def _maybe_download_corpus(tmp_dir, vocab_type): """Download and unpack the corpus. Args: tmp_dir: directory containing dataset. vocab_type: which vocabulary are we using. Returns: The list of names of files. """ filename = os.path.basename(PTB_URL) compressed_filepath = generator_utils.maybe_...
def resize(att_mat, max_length=None): """Normalize attention matrices and reshape as necessary.""" for i, att in enumerate(att_mat): # Add extra batch dim for viz code to work. if att.ndim == 3: att = np.expand_dims(att, axis=0) if max_length is not None: # Sum across different attention val...
def _get_attention(inp_text, out_text, enc_atts, dec_atts, encdec_atts): """Compute representation of the attention ready for the d3 visualization. Args: inp_text: list of strings, words to be displayed on the left of the vis out_text: list of strings, words to be displayed on the right of the vis enc_...
def decode(tokens): """Decode a list of tokens to a unicode string. Args: tokens: a list of Unicode strings Returns: a unicode string """ token_is_alnum = [t[0] in _ALPHANUMERIC_CHAR_SET for t in tokens] ret = [] for i, token in enumerate(tokens): if i > 0 and token_is_alnum[i - 1] and token_...
def _read_filepattern(filepattern, max_lines=None, split_on_newlines=True): """Reads files matching a wildcard pattern, yielding the contents. Args: filepattern: A wildcard pattern matching one or more files. max_lines: If set, stop reading after reading this many lines. split_on_newlines: A boolean. I...
def corpus_token_counts( text_filepattern, corpus_max_lines, split_on_newlines=True): """Read the corpus and compute a dictionary of token counts. Args: text_filepattern: A pattern matching one or more files. corpus_max_lines: An integer; maximum total lines to read. split_on_newlines: A boolean. I...
def vocab_token_counts(text_filepattern, max_lines): """Read a vocab file and return a dictionary of token counts. Reads a two-column CSV file of tokens and their frequency in a dataset. The tokens are presumed to be generated by encode() or the equivalent. Args: text_filepattern: A pattern matching one o...
def _make_example(input_ids, problem, input_feature_name="inputs"): """Make a tf.train.Example for the problem. features[input_feature_name] = input_ids Also fills in any other required features with dummy values. Args: input_ids: list<int>. problem: Problem. input_feature_name: name of feature f...
def make_grpc_request_fn(servable_name, server, timeout_secs): """Wraps function to make grpc requests with runtime args.""" stub = _create_stub(server) def _make_grpc_request(examples): """Builds and sends request to TensorFlow model server.""" request = predict_pb2.PredictRequest() request.model_sp...
def make_cloud_mlengine_request_fn(credentials, model_name, version): """Wraps function to make CloudML Engine requests with runtime args.""" def _make_cloud_mlengine_request(examples): """Builds and sends requests to Cloud ML Engine.""" api = discovery.build("ml", "v1", credentials=credentials) parent...
def predict(inputs_list, problem, request_fn): """Encodes inputs, makes request to deployed TF model, and decodes outputs.""" assert isinstance(inputs_list, list) fname = "inputs" if problem.has_inputs else "targets" input_encoder = problem.feature_info[fname].encoder input_ids_list = [ _encode(inputs, ...
def next_frame_basic_recurrent(): """Basic 2-frame recurrent model with stochastic tower.""" hparams = basic_stochastic.next_frame_basic_stochastic_discrete() hparams.filter_double_steps = 2 hparams.hidden_size = 64 hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 4 hparams.concat_inte...
def create_teacher_experiment(run_config, hparams, argv): """Creates experiment function.""" tf.logging.info("training teacher") tf.logging.set_verbosity(tf.logging.INFO) trainer_lib.set_random_seed(FLAGS.random_seed) usr_dir.import_usr_dir(FLAGS.t2t_usr_dir) t2t_trainer.maybe_log_registry_and_exit() if ...
def tabbed_parsing_token_generator(data_dir, tmp_dir, train, prefix, source_vocab_size, target_vocab_size): """Generate source and target data from a single file.""" filename = "parsing_{0}.pairs".format("train" if train else "dev") source_vocab = generator_utils.get_or_generate...
def tabbed_parsing_character_generator(tmp_dir, train): """Generate source and target data from a single file.""" character_vocab = text_encoder.ByteTextEncoder() filename = "parsing_{0}.pairs".format("train" if train else "dev") pair_filepath = os.path.join(tmp_dir, filename) return text_problems.text2text_g...
def _make_list(predictions, targets): """Helper: make predictions and targets lists, check they match on length.""" # Our models sometimes return predictions in lists, make it a list always. # TODO(lukaszkaiser): make abstractions for nested structures and refactor. if not isinstance(predictions, (list, tuple)...
def masked_mean(inputs, targets, mask_id=None): """Mean of the inputs but counting only those where targets != mask_id.""" inputs = [x.astype(np.float32) for x in inputs] # We assume all elements in the list contribute equally. # TODO(lukaszkaiser): remove this assumption (e.g., when masks differ). length = l...
def accuracy(batch, model_predictions): """Calculate accuracy.""" _, targets = batch model_predictions, targets = _make_list(model_predictions, targets) correct = [] for (prediction, target) in zip(model_predictions, targets): predicted_class = np.argmax(prediction, axis=-1) correct.append(np.equal(pr...
def neg_log_perplexity(batch, model_predictions): """Calculate negative log perplexity.""" _, targets = batch model_predictions, targets = _make_list(model_predictions, targets) xent = [] for (prediction, target) in zip(model_predictions, targets): hot_target = layers.one_hot(target, prediction.shape[-1])...
def loss(params, batch, model_predict, rng): """Calculate loss.""" inputs, targets = batch predictions = model_predict(inputs, params, rng=rng) predictions, targets = _make_list(predictions, targets) xent = [] for (pred, target) in zip(predictions, targets): xent.append(np.sum(pred * layers.one_hot(targ...
def restore_state(output_dir): """Restore State.""" params_file = os.path.join(output_dir, "model.pkl") if not gfile.exists(params_file): return State(step=None, params=None, history=trax_history.History()) with gfile.GFile(params_file, "rb") as f: (params, step, history) = pickle.load(f) log("Model ...
def save_state(state, output_dir, keep=False): """Save State and optionally gin config.""" params_file = os.path.join(output_dir, "model.pkl") with gfile.GFile(params_file, "wb") as f: pickle.dump((state.params, state.step, state.history), f) if keep: params_file = os.path.join(output_dir, "model_{}.pkl...
def evaluate_train_and_eval(step, inputs, predict_fun, eval_steps, rng, train_sw=None, eval_sw=None, history=None): """Evalaute on train and eval data, and log metrics.""" step_log(step, "Evaluation") train_metrics, eval_metrics = [ evaluate( # pylint: disable=g-complex-comprehe...
def evaluate(inputs_stream, predict_fun, metric_funs, rng): """Evaluate. Args: inputs_stream: iterable of inputs to evaluate on. predict_fun: function from inputs to predictions. params should already be partially applied. metric_funs: dict from metric name to metric function, which takes inputs ...
def log_metrics(metrics, summ_writer, log_prefix, step, history=None): """Log metrics to summary writer and history.""" rjust_len = max([len(name) for name in metrics]) for name, value in six.iteritems(metrics): step_log(step, "%s %s | % .8f" % ( log_prefix.ljust(5), name.rjust(rjust_len), value)) ...
def get_random_number_generator_and_set_seed(seed=None): """Get a JAX random number generator and set random seed everywhere.""" random.seed(seed) # While python random accepts None as seed and uses time/os seed then, # some other functions expect integers so we create one here. if seed is None: seed = ra...
def epochs(steps=None, epoch_steps=1): """Iterator over epochs until steps is reached. 1-indexed. Args: steps: int, total number of steps. Infinite if None. epoch_steps: int, number of steps per epoch. Can also be an iterable<int> to enable variable length epochs. Yields: (epoch: int, epoch id...
def _jit_predict_fun(model_predict, num_devices): """Use jit on model_predict if required.""" def predict(x, params=(), rng=None): """Predict function jited and parallelized as requested.""" # On one device, jit and run. if num_devices == 1: return backend.jit(model_predict)(x, params, rng=rng) ...
def _jit_update_fun(predict_fun, loss_fun, optimizer, lr_fun, num_devices): """Get jit-ed update function for loss, optimizer, learning rate function.""" if num_devices == 1: # TODO(lukaszkaiser): remove branch when not needed. def single_update(i, opt_state, batch, rng): rng, subrng = jax_random.split(r...
def _reshape_by_device_single(x, num_devices): """Reshape x into a shape [num_devices, ...].""" x_shape = list(x.shape) batch_size = x_shape[0] batch_size_per_device = batch_size // num_devices # We require that num_devices divides batch_size evenly. if batch_size_per_device * num_devices != batch_size: ...
def reshape_by_device(x, num_devices): """Reshape possibly nested x into a shape [num_devices, ...].""" return layers.nested_map( x, lambda x: _reshape_by_device_single(x, num_devices))
def train(output_dir, model=gin.REQUIRED, loss_fun=loss, inputs=trax_inputs.inputs, optimizer=trax_opt.adam, lr_schedule=lr.MultifactorSchedule, train_steps=1000, save_steps=None, eval_steps=10, eval_frequency=100, num_d...
def _compute_fans(shape): """Computes the number of input and output units for a weight shape. Args: shape: Integer shape tuple or TF tensor shape. Returns: A tuple of scalars (fan_in, fan_out). """ if len(shape) < 1: # Just to avoid errors for constants. fan_in = fan_out = 1 elif len(shape) ...
def get(identifier, value=None): """Getter for loading from strings; returns value if can't load.""" if value is None: value = identifier if identifier is None: return None elif isinstance(identifier, dict): try: return deserialize(identifier) except ValueError: return value elif i...
def add_time_step(self, **create_time_step_kwargs): """Creates a time-step and appends it to the list. Args: **create_time_step_kwargs: Forwarded to time_step.TimeStep.create_time_step. """ ts = time_step.TimeStep.create_time_step(**create_time_step_kwargs) assert isinstance(ts, time_...
def change_last_time_step(self, **replace_time_step_kwargs): """Replace the last time-steps with the given kwargs.""" # Pre-conditions: self._time_steps shouldn't be empty. assert self._time_steps self._time_steps[-1] = self._time_steps[-1].replace( **replace_time_step_kwargs)
def reward(self): """Returns a tuple of sum of raw and processed rewards.""" raw_rewards, processed_rewards = 0, 0 for ts in self.time_steps: # NOTE: raw_reward and processed_reward are None for the first time-step. if ts.raw_reward is not None: raw_rewards += ts.raw_reward if ts.p...
def _complete_trajectory(self, trajectory, index): """Completes the given trajectory at the given index.""" assert isinstance(trajectory, Trajectory) # This *should* be the case. assert trajectory.last_time_step.action is None # Add to completed trajectories. self._completed_trajectories.appe...
def reset(self, indices, observations): """Resets trajectories at given indices and populates observations. Reset can either be called right at the beginning, when there are no time-steps, or to reset a currently active trajectory. If resetting a currently active trajectory then we save it in self...
def complete_all_trajectories(self): """Essentially same as reset, but we don't have observations.""" for index in range(self.batch_size): trajectory = self._trajectories[index] assert trajectory.is_active self._complete_trajectory(trajectory, index)
def step(self, observations, raw_rewards, processed_rewards, dones, actions): """Record the information obtained from taking a step in all envs. Records (observation, rewards, done) in a new time-step and actions in the current time-step. If any trajectory gets done, we move that trajectory to com...
def num_time_steps(self): """Returns the number of time-steps in completed and incomplete trajectories.""" num_time_steps = sum(t.num_time_steps for t in self.trajectories) return num_time_steps + self.num_completed_time_steps
def observations_np(self, boundary=20): """Pads the observations in all the trajectories and returns them. Args: boundary: integer, Observations will be padded to (n * boundary) + 1 where n is an integer. Returns: a tuple(padded_observations, time_steps), with shapes: padded_ob...
def _generate_examples(tmp_dir, dataset_split): """Generate squad examples. Args: tmp_dir: a string dataset_split: problem.DatasetSplit.TRAIN or problem.DatasetSplit.EVAL Yields: dictionaries representing examples """ if dataset_split == problem.DatasetSplit.TRAIN: file_name = _TRAINING_SET ...
def self_attention_layer(hparams, prefix): """Create self-attention layer based on hyperparameters.""" return transformer_layers.SelfAttention( num_heads=hparams.get(prefix + "num_heads"), num_memory_heads=hparams.get(prefix + "num_memory_heads"), key_value_size=hparams.d_kv, shared_kv=hpara...
def local_self_attention_layer(hparams, prefix): """Create self-attention layer based on hyperparameters.""" return transformer_layers.LocalSelfAttention( num_heads=hparams.get(prefix + "num_heads"), num_memory_heads=hparams.get(prefix + "num_memory_heads"), radius=hparams.local_attention_radius, ...
def layer_stack_from_hparams(hparams, prefix): """Create a layer stack based on the hyperparameter values.""" layers = hparams.get(prefix + "layers") return transformer.LayerStack( [layers_registry[l](hparams, prefix) for l in layers], dropout_rate=hparams.layer_prepostprocess_dropout, norm_epsi...
def mtf_unitransformer_base(): """Hyperparameters for single-stack Transformer.""" hparams = mtf_transformer2_base() hparams.add_hparam("autoregressive", True) # HYPERPARAMETERS FOR THE SINGLE LAYER STACK hparams.add_hparam("layers", ["self_att", "drd"] * 6) # number of heads in multihead attention hparam...
def mtf_bitransformer_base(): """Machine translation base configuration.""" hparams = mtf_transformer2_base() hparams.max_length = 256 hparams.shared_embedding = True # HYPERPARAMETERS FOR THE LAYER STACKS hparams.add_hparam("encoder_layers", ["self_att", "drd"] * 6) hparams.add_hparam("decoder_layers", [...
def mtf_bitransformer_tiny(): """Small encoder-decoder model for testing.""" hparams = mtf_bitransformer_base() hparams.batch_size = 2 hparams.mesh_shape = "" hparams.d_model = 128 hparams.encoder_layers = ["self_att", "drd"] * 2 hparams.decoder_layers = ["self_att", "enc_att", "drd"] * 2 hparams.num_he...
def mtf_unitransformer_all_layers_tiny(): """Test out all the layers on local CPU.""" hparams = mtf_unitransformer_tiny() hparams.moe_num_experts = 4 hparams.moe_expert_x = 4 hparams.moe_expert_y = 4 hparams.moe_hidden_size = 512 hparams.layers = ["self_att", "local_self_att", "moe_1d", "moe_2d", "drd"] ...
def mtf_bitransformer_all_layers_tiny(): """Test out all the layers on local CPU.""" hparams = mtf_bitransformer_tiny() hparams.moe_num_experts = 4 hparams.moe_expert_x = 4 hparams.moe_expert_y = 4 hparams.moe_hidden_size = 512 hparams.encoder_layers = [ "self_att", "local_self_att", "moe_1d", "moe_...
def mtr_lm_dense(sz): """Series of architectures for language modeling. We assume infinite training data, so no dropout necessary. You can use languagemodel_wiki_noref_v32k_l1k. (1 epoch = ~46000 steps). TODO(noam): find a large enough dataset for these experiments. Args: sz: an integer Returns: ...
def mtr_lm_v1(): """Model incorporating mixture-of-experts, local and global attention. ~6B parameters 32 experts in 3 hierarchichal moe layers. Returns: a hparams """ hparams = mtr_lm_dense(0) hparams.layers = (["local_self_att", "local_self_att", "drd", "self_att", "drd", "lo...
def mtr_tr_dense(sz): """Series of machine translation models. All models are trained on sequences of 256 tokens. You can use the dataset translate_enfr_wmt32k_packed. 154000 steps = 3 epochs. Args: sz: an integer Returns: a hparams """ n = 2 ** sz hparams = mtf_bitransformer_base() hpar...
def mtr_tr_dense_local(sz): """With local self-attention in the decoder.""" hparams = mtr_tr_dense(sz) hparams.decoder_layers = ["local_self_att", "enc_att", "drd"] * 6 hparams.local_attention_radius = 32 return hparams
def recurrent_transformer_decoder( decoder_input, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, hparams, name="decoder", nonpadding=None, save_weights_to=None, make_image_summary=True): """Recurrent decoder function.""" x = decoder_input attention...
def vqa_recurrent_self_attention_base(): """VQA attention baseline hparams.""" hparams = universal_transformer.universal_transformer_base() hparams.batch_size = 1024 hparams.use_fixed_batch_size = True hparams.weight_decay = 0. hparams.clip_grad_norm = 0. # use default initializer # hparams.initializer ...
def batch_norm_relu(inputs, is_training, relu=True): """Block of batch norm and relu.""" inputs = mtf.layers.batch_norm( inputs, is_training, BATCH_NORM_DECAY, epsilon=BATCH_NORM_EPSILON, init_zero=(not relu)) if relu: inputs = mtf.relu(inputs) return inputs
def bottleneck_block(inputs, filters, is_training, strides, projection_shortcut=None, row_blocks_dim=None, col_blocks_dim=None): """Bottleneck block variant for residual networks with BN after...
def block_layer(inputs, filters, blocks, strides, is_training, name, row_blocks_dim=None, col_blocks_dim=None): """Creates one layer of blocks for the ResNet model. Args: inputs: `Tensor` of size `[b...
def mtf_resnet_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.no_data_parallelism = True hparams.use_fixed_batch_size = True hparams.batch_size = 32 hparams.max_length = 3072 hparams.hidden_size = 256 hparams.label_smoothing = 0.0 # 8-way model-parallelism hpa...
def mtf_resnet_tiny(): """Catch bugs locally...""" hparams = mtf_resnet_base() hparams.num_layers = 2 hparams.hidden_size = 64 hparams.filter_size = 64 hparams.batch_size = 16 # data parallelism and model-parallelism hparams.col_blocks = 1 hparams.mesh_shape = "batch:2" hparams.layout = "batch:batch...
def mtf_resnet_single(): """Small single parameters.""" hparams = mtf_resnet_tiny() hparams.mesh_shape = "" hparams.layout = "" hparams.hidden_size = 32 hparams.filter_size = 32 hparams.batch_size = 1 hparams.num_encoder_layers = 1 hparams.num_layers = 1 hparams.block_length = 16 return hparams
def mtf_resnet_base_single(): """Small single parameters.""" hparams = mtf_resnet_base() hparams.num_layers = 6 hparams.filter_size = 256 hparams.block_length = 128 hparams.mesh_shape = "" hparams.layout = "" return hparams
def mtf_resnet_base_cifar(): """Data parallel CIFAR parameters.""" hparams = mtf_resnet_base() hparams.mesh_shape = "batch:32" hparams.layoyt = "batch:batch" hparams.batch_size = 8 hparams.num_layers = 12 hparams.block_length = 256 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.learnin...
def universal_transformer_encoder(encoder_input, encoder_self_attention_bias, hparams, name="encoder", nonpadding=None, save_weights_to=None, ...
def universal_transformer_layer(x, hparams, ffn_unit, attention_unit, pad_remover=None): """Core function applying the universal transformer layer. Args: x: input hparams: model h...
def get_ut_layer(x, hparams, ffn_unit, attention_unit, pad_remover=None): """Provides the function that is used in universal transforemr steps. Args: x: input hparams: model hyper-parameters ffn_unit: feed-forward unit attention_un...
def transformer_encoder_ffn_unit(x, hparams, nonpadding_mask=None, pad_remover=None): """Applies a feed-forward function which is parametrised for encoding. Args: x: input hparams: model hyper-parameters ...
def transformer_encoder_attention_unit(x, hparams, encoder_self_attention_bias, attention_dropout_broadcast_dims, save_weights_to=None, ...
def transformer_decoder_attention_unit(x, hparams, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, ...
def universal_transformer_basic(layer_inputs, step, hparams, ffn_unit, attention_unit): """Basic Universal Transformer. This model is pretty similar to the vanilla transformer in which weights are shared between layer...
def universal_transformer_highway(layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None): """Universal Transformer with highway connection. It transforms the st...
def universal_transformer_depthwise_attention(layer_inputs, step, hparams, ffn_unit, attention_unit): """universal_transformer with depth-wise attention. It uses an attention me...
def universal_transformer_with_gru_as_transition_function( layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None): """Universal Transformer which uses a gru as transition function. It's kind of like having a gru, filliped vertically next to the Universal Transformer that controls the flow o...
def universal_transformer_with_lstm_as_transition_function( layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None): """Universal Transformer which uses a lstm as transition function. It's kind of like having a lstm, filliped vertically next to the Universal Transformer that controls the flo...
def universal_transformer_act(x, hparams, ffn_unit, attention_unit): """ACT based models. Implementations of all act models are based on craffel@'s cl/160711592. (1) Basic AUT based on remainder-distribution ACT (position-wise). (2) AUT with global halting probability (not position-wise). (3) AUT with rando...
def _ffn_layer_multi_inputs(inputs_list, hparams, ffn_layer_type="dense", name="ffn", kernel_initializer=None, bias_initializer=None, activation=None, ...
def fill_memory_slot(memory, value, index): """Fills the memory slot at a particular index with the given value. Args: memory: a 4-d tensor [memory_size, batch, length, channel] containing the state of all steps value: a 3-d tensor [batch, length, channel] as the sate index: integer in [0, memory...
def add_depth_embedding(x): """Add n-dimensional embedding as the depth embedding (timing signal). Adds embeddings to represent the position of the step in the recurrent tower. Args: x: a tensor with shape [max_step, batch, length, depth] Returns: a Tensor the same shape as x. """ x_shape = com...
def step_preprocess(x, step, hparams): """Preprocess the input at the beginning of each step. Args: x: input tensor step: step hparams: model hyper-parameters Returns: preprocessed input. """ original_channel_size = common_layers.shape_list(x)[-1] if hparams.add_position_timing_signal: ...
def add_position_timing_signal(x, step, hparams): """Add n-dimensional embedding as the position (horizontal) timing signal. Args: x: a tensor with shape [batch, length, depth] step: step hparams: model hyper parameters Returns: a Tensor with the same shape as x. """ if not hparams.positio...
def add_step_timing_signal(x, step, hparams): """Add n-dimensional embedding as the step (vertical) timing signal. Args: x: a tensor with shape [batch, length, depth] step: step hparams: model hyper parameters Returns: a Tensor with the same shape as x. """ if hparams.recurrence_type == "ac...
def wet_records_from_file_obj(f, take_ownership=False): """Iterate through records in WET file object.""" while True: record = WETRecord.read(f) if record is None: break if not record.url: continue yield record if take_ownership: f.close()
def wet_records(wet_filepath): """Generate WETRecords from filepath.""" if wet_filepath.endswith('.gz'): fopen = gzip.open else: fopen = tf.gfile.GFile with fopen(wet_filepath) as f: for record in wet_records_from_file_obj(f): yield record
def filter_paragraph(p): """Simple filter to remove obviously bad paragraphs (bad text extraction). Note this needs to run very quickly as it is applied to every paragraph in the corpus, so nothing fancy! This whole method should be linear expected time in len(p). Args: p: string, paragraph Returns: ...
def timing(name=''): """Log start, end, and duration.""" start = datetime.datetime.now() timestamp = start.strftime('%H:%M') tf.logging.info('Starting job [%s] at %s', name, timestamp) yield end = datetime.datetime.now() timestamp = end.strftime('%H:%M') tf.logging.info('Finished job [%s] at %s', name, ...
def read(cls, f): """Read header from file. Headers end with length and then 1 blank line.""" url = None line = f.readline() if not line: # EOF return None while not line.startswith(cls.LENGTH_HEADER): if line.startswith(cls.URI_HEADER): url = line[len(cls.URI_HEADER):].st...
def read(cls, f): """Read WETRecord from file. Records end with 2 blank lines.""" header = WETHeader.read(f) if header is None: # EOF return None content = f.read(header.length) # Consume empty separators f.readline() f.readline() return cls(header.url, content)
def MLP(num_hidden_layers=2, hidden_size=512, activation_fn=layers.Relu, num_output_classes=10, mode="train"): """Multi-layer feed-forward neural network with non-linear activations.""" del mode cur_layers = [layers.Flatten()] for _ in range(num_hidden_layers): cur_layers += ...
def _verify_same_spaces(self): """Verifies that all the envs have the same observation and action space.""" # Pre-conditions: self._envs is initialized. if self._envs is None: raise ValueError("Environments not initialized.") if not isinstance(self._envs, list): tf.logging.warning("Not ch...
def initialize_environments(self, batch_size=1): """Initializes the environments and trajectories. Subclasses can override this if they don't want a default implementation which initializes `batch_size` environments, but must take care to initialize self._trajectories (this is checked in __init__ anywa...
def process_rewards(self, rewards): """Clips, rounds, and changes to integer type. Args: rewards: numpy array of raw (float) rewards. Returns: processed_rewards: numpy array of np.int64 """ min_reward, max_reward = self.reward_range # Clips at min and max reward. rewards = np...
def num_rewards(self): """Returns the number of distinct rewards. Returns: Returns None if the reward range is infinite or the processed rewards aren't discrete, otherwise returns the number of distinct rewards. """ # Pre-conditions: reward range is finite. # : processed ...
def _reset(self, indices): """Resets environments at indices shouldn't pre-process or record. Subclasses should override this to do the actual reset if something other than the default implementation is desired. Args: indices: list of indices of underlying envs to call reset on. Returns: ...