text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_vis_data_from_string(self, sess, input_string): """Constructs the data needed for visualizing attentions. Args: sess: A tf.Session object. input_string: ...
encoded_inputs = self.encode(input_string) # Run inference graph to get the translation. out = sess.run(self.samples, { self.inputs: encoded_inputs, }) # Run the decoded translation through the training graph to get the # attention tensors. att_mats = sess.run(self.att_mats, { ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def glow_hparams(): """Glow Hparams."""
hparams = common_hparams.basic_params1() hparams.clip_grad_norm = None hparams.weight_decay = 0.0 hparams.learning_rate_constant = 3e-4 hparams.batch_size = 32 # can be prev_level, prev_step or normal. # see: glow_ops.merge_level_and_latent_dist hparams.add_hparam("level_scale", "prev_level") hparams...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift_and_pad(tensor, shift, axis=0): """Shifts and pads with zero along an axis. Example: shift_and_pad([1, 2, 3, 4], 2) --> [0, 0, 1, 2] shift_and_pad([1, ...
shape = tensor.shape rank = len(shape) assert 0 <= abs(axis) < rank length = int(shape[axis]) assert 0 <= abs(shift) < length paddings = [(0, 0)] * rank begin = [0] * rank size = [-1] * rank if shift > 0: paddings[axis] = (shift, 0) size[axis] = length - shift elif shift < 0: padding...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pixels_from_softmax(frame_logits, pure_sampling=False, temperature=1.0, gumbel_noise_factor=0.2): """Given frame_logits from a per-pixel softmax, generate co...
# If we're purely sampling, just sample each pixel. if pure_sampling or temperature == 0.0: return common_layers.sample_with_temperature(frame_logits, temperature) # Gumbel-sample from the pixel sofmax and average by pixel values. pixel_range = tf.to_float(tf.range(256)) for _ in range(len(frame_logits....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_frame_base(): """Common HParams for next_frame models."""
hparams = common_hparams.basic_params1() # Loss cutoff. hparams.add_hparam("video_modality_loss_cutoff", 0.01) # Additional resizing the frames before feeding them to model. hparams.add_hparam("preprocess_resize_frames", None) # How many data points to suffle. Ideally should be part of problem not model! ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_time_limit_wrapper(env): """Removes top level TimeLimit Wrapper. Removes TimeLimit Wrapper from top level if exists, throws error if any other TimeLim...
if isinstance(env, gym.wrappers.TimeLimit): env = env.env env_ = env while isinstance(env_, gym.Wrapper): if isinstance(env_, gym.wrappers.TimeLimit): raise ValueError("Can remove only top-level TimeLimit gym.Wrapper.") env_ = env_.env return env
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gym_env_wrapper(env, rl_env_max_episode_steps, maxskip_env, rendered_env, rendered_env_resize_to, sticky_actions): """Wraps a gym environment. see make_gym_e...
# rl_env_max_episode_steps is None or int. assert ((not rl_env_max_episode_steps) or isinstance(rl_env_max_episode_steps, int)) wrap_with_time_limit = ((not rl_env_max_episode_steps) or rl_env_max_episode_steps >= 0) if wrap_with_time_limit: env = remove_time_limit_wra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_gym_env(name, rl_env_max_episode_steps=-1, maxskip_env=False, rendered_env=False, rendered_env_resize_to=None, sticky_actions=False): """Create a gym en...
env = gym.make(name) return gym_env_wrapper(env, rl_env_max_episode_steps, maxskip_env, rendered_env, rendered_env_resize_to, sticky_actions)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_gym_env(class_entry_point, version="v0", kwargs=None): """Registers the class in Gym and returns the registered name and the env."""
split_on_colon = class_entry_point.split(":") assert len(split_on_colon) == 2 class_name = split_on_colon[1] # We have to add the version to conform to gym's API. env_name = "T2TEnv-{}-{}".format(class_name, version) gym.envs.register(id=env_name, entry_point=class_entry_point, kwargs=kwargs) tf.loggi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def step(self, action): """Repeat action, sum reward, and max over last observations."""
total_reward = 0.0 done = None for i in range(self._skip): obs, reward, done, info = self.env.step(action) if i == self._skip - 2: self._obs_buffer[0] = obs if i == self._skip - 1: self._obs_buffer[1] = obs total_reward += reward if done: break # No...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_errors(errors): """Log out and possibly reraise errors during import."""
if not errors: return log_all = True # pylint: disable=unused-variable err_msg = "T2T: skipped importing {num_missing} data_generators modules." print(err_msg.format(num_missing=len(errors))) for module, err in errors: err_str = str(err) if not _is_import_err_msg(err_str, module): print("F...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_hparams(hparams_set, hparams_overrides_str="", data_dir=None, problem_name=None, hparams_path=None): """Create HParams with data_dir and problem hpara...
hparams = registry.hparams(hparams_set) if hparams_path and tf.gfile.Exists(hparams_path): hparams = create_hparams_from_json(hparams_path, hparams) if data_dir: hparams.add_hparam("data_dir", data_dir) if hparams_overrides_str: tf.logging.info("Overriding hparams in %s with %s", hparams_set, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_hparams_from_json(json_path, hparams=None): """Loading hparams from json; can also start from hparams if specified."""
tf.logging.info("Loading hparams from existing json %s" % json_path) with tf.gfile.Open(json_path, "r") as f: hparams_values = json.load(f) # Prevent certain keys from overwriting the passed-in hparams. # TODO(trandustin): Remove this hack after registries are available to avoid # saving them as fu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_problem_hparams(hparams, problem_name_or_instance): """Add problem hparams for the problems."""
if isinstance(problem_name_or_instance, problem_lib.Problem): problem = problem_name_or_instance else: problem = registry.problem(problem_name_or_instance) p_hparams = problem.get_hparams(hparams) hparams.problem = problem hparams.problem_hparams = p_hparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_examples(tmp_dir, prop_train=0.09, prop_val=0.01): """Loads exampls from the tsv file. Args: tmp_dir: temp directory. prop_train: proportion of the trai...
infile = generator_utils.maybe_download(tmp_dir, _TAR, _URL) tf.logging.info('Loading examples') all_examples = [] for i, d in enumerate(csv.DictReader(gzip.open(infile), delimiter='\t')): if i % 100000 == 0: tf.logging.info('%d examples have been loaded....' % i) ex = {x: int(y) if y.isdigit()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_cifar(directory, url): """Download and extract CIFAR to directory unless it is there."""
filename = os.path.basename(url) path = generator_utils.maybe_download(directory, filename, url) tarfile.open(path, "r:gz").extractall(directory)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cifar_generator(cifar_version, tmp_dir, training, how_many, start_from=0): """Image generator for CIFAR-10 and 100. Args: cifar_version: string; one of "cifa...
if cifar_version == "cifar10": url = _CIFAR10_URL train_files = _CIFAR10_TRAIN_FILES test_files = _CIFAR10_TEST_FILES prefix = _CIFAR10_PREFIX image_size = _CIFAR10_IMAGE_SIZE label_key = "labels" elif cifar_version == "cifar100" or cifar_version == "cifar20": url = _CIFAR100_URL tr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rlmb_ppo_base(): """HParams for PPO base."""
hparams = _rlmb_base() ppo_params = dict( base_algo="ppo", base_algo_params="ppo_original_params", # Number of real environments to train on simultaneously. real_batch_size=1, # Number of simulated environments to train on simultaneously. simulated_batch_size=16, eval_batc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rlmb_dqn_base(): """rlmb_dqn_base params."""
hparams = _rlmb_base() simulated_rollout_length = 10 dqn_params = dict( base_algo="dqn", base_algo_params="dqn_original_params", real_batch_size=1, simulated_batch_size=16, dqn_agent_generates_trainable_dones=False, eval_batch_size=1, # Must be equal to dqn_time_limit fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rlmb_ppo_quick(): """Base setting but quicker with only 2 epochs."""
hparams = rlmb_ppo_base() hparams.epochs = 2 hparams.model_train_steps = 25000 hparams.ppo_epochs_num = 700 hparams.ppo_epoch_length = 50 return hparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rlmb_base_stochastic(): """Base setting with a stochastic next-frame model."""
hparams = rlmb_base() hparams.initial_epoch_train_steps_multiplier = 5 hparams.generative_model = "next_frame_basic_stochastic" hparams.generative_model_params = "next_frame_basic_stochastic" return hparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rlmb_long_stochastic_discrete_simulation_deterministic_starts(): """Long setting with stochastic discrete model & deterministic sim starts."""
hparams = rlmb_base_stochastic_discrete() hparams.generative_model_params = "next_frame_basic_stochastic_discrete_long" hparams.ppo_epochs_num = 1000 hparams.simulation_random_starts = False return hparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rlmb_base_sv2p(): """Base setting with sv2p as world model."""
hparams = rlmb_base() hparams.learning_rate_bump = 1.0 hparams.generative_model = "next_frame_sv2p" hparams.generative_model_params = "next_frame_sv2p_atari" return hparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rlmb_tiny_overrides(): """Parameters to override for tiny setting excluding agent-related hparams."""
return dict( epochs=1, num_real_env_frames=128, model_train_steps=2, max_num_noops=1, eval_max_num_noops=1, generative_model_params="next_frame_tiny", stop_loop_early=True, resize_height_factor=2, resize_width_factor=2, wm_eval_rollout_ratios=[1], rl_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rlmb_tiny_stochastic(): """Tiny setting with a stochastic next-frame model."""
hparams = rlmb_ppo_tiny() hparams.epochs = 1 # Too slow with 2 for regular runs. hparams.generative_model = "next_frame_basic_stochastic" hparams.generative_model_params = "next_frame_basic_stochastic" return hparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rlmb_tiny_recurrent(): """Tiny setting with a recurrent next-frame model."""
hparams = rlmb_ppo_tiny() hparams.epochs = 1 # Too slow with 2 for regular runs. hparams.generative_model = "next_frame_basic_recurrent" hparams.generative_model_params = "next_frame_basic_recurrent" return hparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rlmb_tiny_sv2p(): """Tiny setting with a tiny sv2p model."""
hparams = rlmb_ppo_tiny() hparams.generative_model = "next_frame_sv2p" hparams.generative_model_params = "next_frame_sv2p_tiny" hparams.grayscale = False return hparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rlmb_grid(rhp): """Grid over games and frames, and 5 runs each for variance."""
rhp.set_categorical("loop.game", ["breakout", "pong", "freeway"]) base = 100000 medium = base // 2 small = medium // 2 rhp.set_discrete("loop.num_real_env_frames", [base, medium, small]) # Dummy parameter to get 5 runs for each configuration rhp.set_discrete("model.moe_loss_coef", list(range(5)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_unscoped_hparams(scopes_and_hparams): """Merge multiple HParams into one with scopes."""
merged_values = {} for (scope, hparams) in scopes_and_hparams: for key, value in six.iteritems(hparams.values()): scoped_key = "%s.%s" % (scope, key) merged_values[scoped_key] = value return hparam.HParams(**merged_values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_scoped_hparams(scopes, merged_hparams): """Split single HParams with scoped keys into multiple."""
split_values = {scope: {} for scope in scopes} merged_values = merged_hparams.values() for scoped_key, value in six.iteritems(merged_values): scope = scoped_key.split(".")[0] key = scoped_key[len(scope) + 1:] split_values[scope][key] = value return [ hparam.HParams(**split_values[scope]) for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def training_loop_hparams_from_scoped_overrides(scoped_overrides, trial_id): """Create HParams suitable for training loop from scoped HParams. Args: scoped_overr...
trial_hp_overrides = scoped_overrides.values() # Create loop, model, and ppo base HParams loop_hp = create_loop_hparams() model_hp_name = trial_hp_overrides.get( "loop.generative_model_params", loop_hp.generative_model_params) model_hp = registry.hparams(model_hp_name).parse(FLAGS.hparams) base_algo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_keys_to_action(self): """Get mapping from keyboard keys to actions. Required by gym.utils.play in environment or top level wrapper. Returns: { Unicode co...
# Based on gym AtariEnv.get_keys_to_action() keyword_to_key = { "UP": ord("w"), "DOWN": ord("s"), "LEFT": ord("a"), "RIGHT": ord("d"), "FIRE": ord(" "), } keys_to_action = {} for action_id, action_meaning in enumerate(self.action_meanings): keys_tuple...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _player_step_tuple(self, envs_step_tuples): """Construct observation, return usual step tuple. Args: envs_step_tuples: tuples. Returns: Step tuple: ob, rewar...
ob_real, reward_real, _, _ = envs_step_tuples["real_env"] ob_sim, reward_sim, _, _ = envs_step_tuples["sim_env"] ob_err = absolute_hinge_difference(ob_sim, ob_real) ob_real_aug = self._augment_observation(ob_real, reward_real, self.cumulative_real_reward) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """Reset simulated and real environments."""
self._frame_counter = 0 ob_real = self.real_env.reset() # Initialize simulated environment with frames from real one. self.sim_env.add_to_initial_stack(ob_real) for _ in range(3): ob_real, _, _, _ = self.real_env.step(self.name_to_action_num["NOOP"]) self.sim_env.add_to_initial_stack(ob...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _player_step_tuple(self, envs_step_tuples): """Augment observation, return usual step tuple."""
ob, reward, done, info = envs_step_tuples["env"] ob = self._augment_observation(ob, reward, self.cumulative_reward) return ob, reward, done, info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_delta_deltas(filterbanks, name=None): """Compute time first and second-order derivative channels. Args: filterbanks: float32 tensor with shape [batch_siz...
delta_filter = np.array([2, 1, 0, -1, -2]) delta_delta_filter = scipy.signal.convolve(delta_filter, delta_filter, "full") delta_filter_stack = np.array( [[0] * 4 + [1] + [0] * 4, [0] * 2 + list(delta_filter) + [0] * 2, list(delta_delta_filter)], dtype=np.float32).T[:, None, None, :] delta_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_mel_filterbank_features( waveforms, sample_rate=16000, dither=1.0 / np.iinfo(np.int16).max, preemphasis=0.97, frame_length=25, frame_step=10, fft_leng...
# `stfts` is a complex64 Tensor representing the short-time Fourier # Transform of each signal in `signals`. Its shape is # [batch_size, ?, fft_unique_bins] # where fft_unique_bins = fft_length // 2 + 1 # Find the wave length: the largest index for which the value is !=0 # note that waveforms samples that...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def play_env_problem_randomly(env_problem, num_steps): """Plays the env problem by randomly sampling actions for `num_steps`."""
# Reset all environments. env_problem.reset() # Play all environments, sampling random actions each time. for _ in range(num_steps): # Sample batch_size actions from the action space and stack them. actions = np.stack([env_problem.action_space.sample() for _ in range( env_problem.batch_size)])...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_plaintext_random(plain_vocab, distribution, train_samples, length): """Generates samples of text from the provided vocabulary. Args: plain_vocab: vo...
if distribution is not None: assert len(distribution) == len(plain_vocab) train_indices = np.random.choice( range(len(plain_vocab)), (train_samples, length), p=distribution) return train_indices
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encipher_shift(plaintext, plain_vocab, shift): """Encrypt plain text with a single shift layer. Args: plaintext (list of list of Strings): a list of plain t...
ciphertext = [] cipher = ShiftEncryptionLayer(plain_vocab, shift) for _, sentence in enumerate(plaintext): cipher_sentence = [] for _, character in enumerate(sentence): encrypted_char = cipher.encrypt_character(character) cipher_sentence.append(encrypted_char) ciphertext.append(cipher_se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encipher_vigenere(plaintext, plain_vocab, key): """Encrypt plain text with given key. Args: plaintext (list of list of Strings): a list of plain text to enc...
ciphertext = [] # generate Vigenere table layers = [ ShiftEncryptionLayer(plain_vocab, i) for i in range(len(plain_vocab)) ] for i, sentence in enumerate(plaintext): cipher_sentence = [] for j, character in enumerate(sentence): key_idx = key[j % len(key)] encrypted_char = layers[ke...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def super_lm_moe(): """Add mixture of experts with ~1B params."""
hparams = super_lm_base() hparams.layers = ( ("n,att,m,d,a," "n,moe,m,d,a,") * 4 + "n,ffn,d") hparams.moe_num_experts = 32 hparams.moe_hidden_sizes = "1024" return hparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xmoe_tr_dense_2k(): """Series of architectural experiments on Translation. # run on 8-core setup 119M params, einsum=0.95e13 Returns: a hparams """
hparams = mtf_transformer2.mtf_bitransformer_base() hparams.encoder_layers = ["self_att", "drd"] * 4 hparams.decoder_layers = ["self_att", "enc_att", "drd"] * 4 hparams.batch_size = 64 hparams.shared_embedding_and_softmax_weights = True hparams.mesh_shape = "batch:8" return hparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xmoe_dense_4k(): """Series of architectural experiments on cheap language models. For all of these architectures, we run on languagemodel_lm1b8k_packed for 3...
hparams = mtf_transformer.mtf_transformer_base_lm() hparams.attention_dropout = 0.0 hparams.relu_dropout = 0.0 hparams.layer_prepostprocess_dropout = 0.0 # The following hparams are constant across all these experiments. hparams.batch_size = 128 hparams.d_model = 512 hparams.d_kv = 128 hparams.num_h...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xmoe_2d(): """Two-dimensional hierarchical mixture of 16 experts."""
hparams = xmoe_top_2() hparams.decoder_layers = ["att", "hmoe"] * 4 hparams.mesh_shape = "b0:2;b1:4" hparams.outer_batch_size = 4 hparams.layout = "outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0" hparams.moe_num_experts = [4, 4] return hparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xmoe2_dense(sz): """Series of architectural experiments on language modeling. Larger models than the ones above. All models are trained on sequences of 1024 ...
hparams = mtf_transformer.mtf_transformer_paper_lm(sz) hparams.attention_dropout = 0.0 hparams.relu_dropout = 0.0 hparams.layer_prepostprocess_dropout = 0.0 hparams.max_length = 1024 hparams.batch_size = 128 hparams.learning_rate_schedule = "rsqrt_decay*linear_decay" hparams.learning_rate_decay_steps =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xmoe2_v1(): """Model incorporating mixture-of-experts and local-attention. ~6B parameters 32 experts in 3 hierarchichal moe layers. Returns: a hparams """
hparams = xmoe2_dense(0) moe.set_default_moe_hparams(hparams) hparams.decoder_layers = ( ["local_att", "local_att", "drd", "att", "drd", "local_att", "local_att", "hmoe"] * 4)[:-1] hparams.d_ff = 2048 hparams.d_kv = 128 hparams.moe_hidden_size = 32768 hparams.mesh_shape = "b0:4;b1:8" hpara...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xmoe2_v1_x128(): """128 experts, ~25B params - Train for 131072 steps on 8x8."""
hparams = xmoe2_v1() hparams.moe_num_experts = [16, 8] hparams.outer_batch_size = 8 hparams.mesh_shape = "b0:8;b1:16" hparams.batch_size = 512 hparams.learning_rate_decay_steps = 16384 return hparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xmoe2_tiny(): """Test on local cpu."""
hparams = xmoe2_v1() hparams.decoder_layers = [ "local_att", "att", "compressed_att", "drd", "hmoe"] hparams.d_model = 128 hparams.moe_hidden_size = 512 hparams.outer_batch_size = 0 hparams.batch_size = 2 hparams.mesh_shape = "" hparams.activation_dtype = "float32" return hparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xmoe2_v1_l4k_compressed_c4(): """With compressed attention."""
hparams = xmoe2_v1_l4k() hparams.decoder_layers = [ "compressed_att" if l == "att" else l for l in hparams.decoder_layers] hparams.compression_factor = 4 return hparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wiki_2x2_base(): """Set of architectural experiments - language model on wikipedia on a 2x2. 1 epoch = ~180k steps at batch size 32 - we may never finish an ...
hparams = mtf_transformer.mtf_transformer_base_lm() hparams.shared_embedding_and_softmax_weights = False # no dropout - dataset is big enough to avoid overfitting. hparams.attention_dropout = 0.0 hparams.relu_dropout = 0.0 hparams.layer_prepostprocess_dropout = 0.0 hparams.max_length = 1024 # 4 sequenc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def denoise_z15(): """Replace tokens instead of masking."""
hparams = xmoe2_dense_0() hparams.decoder_type = "denoising" hparams.noising_spec_train = {"type": "random_zipfian", "prob": 0.15} hparams.noising_use_eval_during_train = 0.25 return hparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def denoise_v1_m15(): """Denoising experiment."""
hparams = xmoe2_v1() # no local attention # TODO(noam): non-masked version of local-attention hparams.decoder_layers = [ "att" if l == "local_att" else l for l in hparams.decoder_layers] hparams.decoder_type = "denoising" hparams.noising_spec_train = {"type": "mask", "prob": 0.15} return hparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_ngram_counter(ids, n): """Get a Counter with the ngrams of the given ID list. Args: ids: np.array or a list corresponding to a single sentence n: n-gram...
# Remove zero IDs used to pad the sequence. ids = [token_id for token_id in ids if token_id != 0] ngram_list = [tuple(ids[i:i + n]) for i in range(len(ids) + 1 - n)] ngrams = set(ngram_list) counts = collections.Counter() for ngram in ngrams: counts[ngram] = 1 return counts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_fbeta_score(true_positives, selected, relevant, beta=1): """Compute Fbeta score. Args: true_positives: Number of true positive ngrams. selected: Number ...
precision = 1 if selected > 0: precision = true_positives / selected if beta == 0: return precision recall = 1 if relevant > 0: recall = true_positives / relevant if precision > 0 and recall > 0: beta2 = beta * beta return (1 + beta2) * precision * recall / (beta2 * precision + recall) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_sari_score(source_ids, prediction_ids, list_of_targets, max_gram_size=4, beta_for_deletion=0): """Compute the SARI score for a single prediction and one ...
addition_scores = [] keep_scores = [] deletion_scores = [] for n in range(1, max_gram_size + 1): source_counts = _get_ngram_counter(source_ids, n) prediction_counts = _get_ngram_counter(prediction_ids, n) # All ngrams in the targets with count 1. target_counts = collections.Counter() # All ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_mnist(directory): """Download all MNIST files to directory unless they are there."""
for filename in [ _MNIST_TRAIN_DATA_FILENAME, _MNIST_TRAIN_LABELS_FILENAME, _MNIST_TEST_DATA_FILENAME, _MNIST_TEST_LABELS_FILENAME ]: generator_utils.maybe_download(directory, filename, _MNIST_URL + filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_mnist_images(filename, num_images): """Extract images from an MNIST file into a numpy array. Args: filename: The path to an MNIST images file. num_i...
with gzip.open(filename) as bytestream: bytestream.read(16) buf = bytestream.read(_MNIST_IMAGE_SIZE * _MNIST_IMAGE_SIZE * num_images) data = np.frombuffer(buf, dtype=np.uint8) data = data.reshape(num_images, _MNIST_IMAGE_SIZE, _MNIST_IMAGE_SIZE, 1) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_mnist_labels(filename, num_labels): """Extract labels from an MNIST file into integers. Args: filename: The path to an MNIST labels file. num_labels...
with gzip.open(filename) as bytestream: bytestream.read(8) buf = bytestream.read(num_labels) labels = np.frombuffer(buf, dtype=np.uint8).astype(np.int64) return labels
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_fashion_mnist(directory): """Download all FashionMNIST files to directory unless they are there."""
# Fashion mnist files have the same names as MNIST. # We must choose a separate name (by adding 'fashion-' prefix) in the tmp_dir. for filename in [ _MNIST_TRAIN_DATA_FILENAME, _MNIST_TRAIN_LABELS_FILENAME, _MNIST_TEST_DATA_FILENAME, _MNIST_TEST_LABELS_FILENAME ]: generator_utils.maybe_download...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fashion_mnist_generator(tmp_dir, training, how_many, start_from=0): """Image generator for FashionMNIST. Args: tmp_dir: path to temporary storage directory. ...
_get_fashion_mnist(tmp_dir) d = _FASHION_MNIST_LOCAL_FILE_PREFIX + ( _MNIST_TRAIN_DATA_FILENAME if training else _MNIST_TEST_DATA_FILENAME) l = _FASHION_MNIST_LOCAL_FILE_PREFIX + ( _MNIST_TRAIN_LABELS_FILENAME if training else _MNIST_TEST_LABELS_FILENAME) return mnist_common_generator(tmp_dir, trai...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_data(timeseries_length, timeseries_params): """Generates synthetic timeseries using input parameters. Each generated timeseries has timeseries_lengt...
x = range(timeseries_length) multi_timeseries = [] for p in timeseries_params: # Trend y1 = [p["m"] * i + p["b"] for i in x] # Period y2 = [p["A"] * p["fn"](i / p["freqcoeff"]) for i in x] # Noise y3 = np.random.normal(0, p["rndA"], timeseries_length).tolist() # Sum of Trend, Period ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_frame_basic_stochastic_discrete(): """Basic 2-frame conv model with stochastic discrete latent."""
hparams = basic_deterministic_params.next_frame_sampling() hparams.batch_size = 4 hparams.video_num_target_frames = 6 hparams.scheduled_sampling_mode = "prob_inverse_lin" hparams.scheduled_sampling_decay_steps = 40000 hparams.scheduled_sampling_max_prob = 1.0 hparams.dropout = 0.15 hparams.filter_doubl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_frame_stochastic_discrete_range(rhp): """Next frame stochastic discrete tuning grid."""
rhp.set_float("learning_rate_constant", 0.001, 0.01) rhp.set_float("dropout", 0.2, 0.6) rhp.set_int("filter_double_steps", 3, 5) rhp.set_discrete("hidden_size", [64, 96, 128]) rhp.set_discrete("bottleneck_bits", [32, 64, 128, 256]) rhp.set_discrete("video_num_target_frames", [4]) rhp.set_float("bottlenec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shapes(x): """Get a structure of shapes for a structure of nested arrays."""
def shape(x): try: return x.shape except Exception: # pylint: disable=broad-except return [] return nested_map(x, shape)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sizes(x): """Get a structure of sizes for a structure of nested arrays."""
def size(x): try: return x.size except Exception: # pylint: disable=broad-except return 0 return nested_map(x, size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_frame(stack, start=0): """Find the frame with the caller on the stack."""
# We want to find the first place where the layer was called # that is *not* an __init__ function of an inheriting layer. frame = inspect.getframeinfo(stack[start][0]) # If we are in an init, move on. if frame.function == '__init__': return _find_frame(stack, start + 1) return frame
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _shorten_file_path(line): """Shorten file path in error lines for more readable tracebacks."""
start = line.lower().find('file') if start < 0: return line first_quote = line.find('"', start) if first_quote < 0: return line second_quote = line.find('"', first_quote + 1) if second_quote < 0: return line path = line[first_quote + 1:second_quote] new_path = '/'.join(path.split('/')[-3:])...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _short_traceback(skip=3): """Cleaned-up form of traceback."""
counter, res = 0, [] # Skipping 3 lines by default: the top (useless) and self-call. lines = traceback.format_exc().splitlines()[skip:] for l in lines: res.append(_shorten_file_path(l)) if counter % 2 == 1: res.append('') counter += 1 # If we see a LayerError, the traceback has already be...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def layer(output_shape=None, new_parameters=None): """Create a layer class from a function."""
def layer_decorator(call): """Decorating the call function.""" def output_shape_fun(self, input_shape): if output_shape is None: return input_shape kwargs = self._init_kwargs # pylint: disable=protected-access return output_shape(input_shape, **kwargs) def new_parameters_fun(s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize(self, input_shape, rng): """Initialize the layer given an input shape and rng. Returns new_parameters(input_shape, rng) on the first call and () o...
try: # Re-using this layer, no new parameters. if not self._first_init: return () # First call of this layer, create parameters. self._first_init = False self._params = self.new_parameters(input_shape, rng) return self._params except Exception: name, trace = s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wiki_articles(shard_id, wikis_dir=None): """Generates WikipediaArticles from GCS that are part of shard shard_id."""
if not wikis_dir: wikis_dir = WIKI_CONTENT_DIR with tf.Graph().as_default(): dataset = tf.data.TFRecordDataset( cc_utils.readahead( os.path.join(wikis_dir, WIKI_CONTENT_FILE % shard_id)), buffer_size=16 * 1000 * 1000) def _parse_example(ex_ser): """Parse serialized Ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rank_reference_paragraphs(wiki_title, references_content, normalize=True): """Rank and return reference paragraphs by tf-idf score on title tokens."""
normalized_title = _normalize_text(wiki_title) title_tokens = _tokens_to_score( set(tokenizer.encode(text_encoder.native_to_unicode(normalized_title)))) ref_paragraph_info = [] doc_counts = collections.defaultdict(int) for ref in references_content: for paragraph in ref.split("\n"): normalize...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _encode_wiki_sections(sections, vocab): """Encodes sections with vocab. Returns ids and section boundaries."""
ids = [] section_boundaries = [] for i, section in enumerate(sections): if i > 0: # Skip including article title ids.extend(vocab.encode(_format_title(_normalize_text(section.title)))) ids.extend(vocab.encode(_normalize_text(section.text))) section_boundaries.append(len(ids)) return id...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_references_from_wets(wet_files, metadata_dir, out_dir, tmp_dir=None): """Extract references from WET files into sharded output files."""
# Setup output files shard_files = make_ref_shard_files(out_dir) num_refs = 0 for i, wet_file in enumerate(wet_files): num_refs_in_wet = 0 tf.logging.info("Processing file %d", i) # Read metadata file metadata_fname = os.path.join( metadata_dir, os.path.basename(wet_file)) + cc_utils....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dump_to_pages(dump): """Extract pages from an xml dump. Args: dump: a unicode string Returns: a list of unicode strings """
pos = 0 ret = [] start_tag = u"<page>\n" end_tag = u"</page>\n" while True: start_pos = dump.find(start_tag, pos) if start_pos == -1: break start_pos += len(start_tag) end_pos = dump.find(end_tag, start_pos) if end_pos == -1: break ret.append(dump[start_pos:end_pos]) p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _page_to_text(page): """Extract the text from a page. Args: page: a unicode string Returns: a unicode string """
# text start tag looks like "<text ..otherstuff>" start_pos = page.find(u"<text") assert start_pos != -1 end_tag_pos = page.find(u">", start_pos) assert end_tag_pos != -1 end_tag_pos += len(u">") end_pos = page.find(u"</text>") if end_pos == -1: return u"" return page[end_tag_pos:end_pos]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_and_replace(text, start_string, end_string, replace_fn): """Remove everything found between instances of start_string and end_string. Replace each such...
ret = u"" current_pos = 0 while True: start_pos = text.find(start_string, current_pos) if start_pos == -1: ret += text[current_pos:] break ret += text[current_pos:start_pos] end_pos = text.find(end_string, start_pos + len(start_string)) if end_pos == -1: break ret += rep...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_question_encoder(inputs, hparams): """Prepare question encoder. Args: inputs: a Tensor. hparams: run hyperparameters Returns: encoder_input: a Tensor...
encoder_input = inputs # Usual case - not a packed dataset. encoder_padding = common_attention.embedding_to_padding(encoder_input) ignore_padding = common_attention.attention_bias_ignore_padding( encoder_padding) encoder_self_attention_bias = ignore_padding if hparams.pos == "timing": encoder_inp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_image_question_encoder(image_feat, question, hparams): """Prepare encoder. Args: image_feat: a Tensor. question: a Tensor. hparams: run hyperparamete...
encoder_input = tf.concat([image_feat, question], axis=1) encoder_padding = common_attention.embedding_to_padding(encoder_input) ignore_padding = common_attention.attention_bias_ignore_padding( encoder_padding) encoder_self_attention_bias = ignore_padding encoder_decoder_attention_bias = ignore_paddin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterative_encoder_decoder(encoder_input, encoder_self_attention_bias, encoder_decoder_attention_bias, query, hparams): """Iterative encoder decoder."""
for _ in range(hparams.num_rec_steps): with tf.variable_scope("step", reuse=tf.AUTO_REUSE): encoder_output = image_question_encoder( encoder_input, encoder_self_attention_bias, hparams, query) decoder_output = decoder( query, encoder_output...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vqa_self_attention_feature_batch1024_big(): """Big model."""
hparams = vqa_self_attention_feature_batch1024() hparams.learning_rate_constant = 7e-4 hparams.batch_size = 256 hparams.hidden_size = 1024 hparams.filter_size = 4096 hparams.num_heads = 16 hparams.layer_prepostprocess_dropout = 0.3 hparams.attention_dropout = 0.3 hparams.relu_dropout = 0.3 return h...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bucket_boundaries(max_length, min_length=8, length_bucket_step=1.1): """A default set of length-bucket boundaries."""
assert length_bucket_step > 1.0 x = min_length boundaries = [] while x < max_length: boundaries.append(x) x = max(x + 1, int(x * length_bucket_step)) return boundaries
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def batching_scheme(batch_size, max_length, min_length_bucket, length_bucket_step, drop_long_sequences=False, shard_multiplier=1, length_multiplier=1, min_length=...
max_length = max_length or batch_size if max_length < min_length: raise ValueError("max_length must be greater or equal to min_length") boundaries = _bucket_boundaries(max_length, min_length_bucket, length_bucket_step) boundaries = [boundary * length_multiplier for bounda...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hparams_to_batching_scheme(hparams, drop_long_sequences=False, shard_multiplier=1, length_multiplier=1): """Wrapper around _batching_scheme with hparams."""
return batching_scheme( batch_size=hparams.batch_size, min_length=hparams.min_length, max_length=hparams.max_length, min_length_bucket=hparams.min_length_bucket, length_bucket_step=hparams.length_bucket_step, drop_long_sequences=drop_long_sequences, shard_multiplier=shard_mu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pad_for_tpu(shapes_dict, hparams, max_length): """Pads unknown features' dimensions for TPU."""
padded_shapes = {} def get_filler(specified_max_length): if not specified_max_length: return max_length return min(specified_max_length, max_length) inputs_none_filler = get_filler(hparams.max_input_seq_length) targets_none_filler = get_filler(hparams.max_target_seq_length) def pad_one_shape...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def standardize_shapes(features, batch_size=None): """Set the right shapes for the features."""
for fname in ["inputs", "targets"]: if fname not in features: continue f = features[fname] while len(f.get_shape()) < 4: f = tf.expand_dims(f, axis=-1) features[fname] = f if batch_size: # Ensure batch size is set on all features for _, t in six.iteritems(features): shape...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _file_num_records_cached(filename): """Return the number of TFRecords in a file."""
# Cache the result, as this is expensive to compute if filename in _file_num_records_cache: return _file_num_records_cache[filename] ret = 0 for _ in tf.python_io.tf_record_iterator(filename): ret += 1 _file_num_records_cache[filename] = ret return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pad_batch(features, batch_multiple): """Pad batch dim of features to nearest multiple of batch_multiple."""
feature = list(features.items())[0][1] batch_size = tf.shape(feature)[0] mod = batch_size % batch_multiple has_mod = tf.cast(tf.cast(mod, tf.bool), tf.int32) batch_padding = batch_multiple * has_mod - mod padded_features = {} for k, feature in features.items(): rank = len(feature.shape) paddings...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_shard_args(outfiles, num_examples): """Generate start and end indices per outfile."""
num_shards = len(outfiles) num_examples_per_shard = num_examples // num_shards start_idxs = [i * num_examples_per_shard for i in range(num_shards)] end_idxs = list(start_idxs) end_idxs.pop(0) end_idxs.append(num_examples) return zip(start_idxs, end_idxs, outfiles)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_example_dict(encoder, inputs, mask, outputs): """Convert single h5 record to an example dict."""
# Inputs bases = [] input_ids = [] last_idx = -1 for row in np.argwhere(inputs): idx, base_id = row idx, base_id = int(idx), int(base_id) assert idx > last_idx # if not, means 2 True values in 1 row # Some rows are all False. Those rows are mapped to UNK_ID. while idx != last_idx + 1: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def linear_interpolate(tensor1, tensor2, coeffs): """Linearly interpolate between two tensors at coeff. Args: tensor1: 4-D Tensor, shape=(NHWC) tensor2: 4-D Tens...
interp_tensors = [] for coeff in coeffs: interp_tensor = tensor1 + coeff * (tensor2 - tensor1) interp_tensors.append(interp_tensor) return tf.concat(interp_tensors, axis=0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def linear_interpolate_rank(tensor1, tensor2, coeffs, rank=1): """Linearly interpolate channel at "rank" between two tensors. The channels are ranked according t...
# sum across space, max across channels. _, _, _, num_channels = common_layers.shape_list(tensor1) diff_sq_sum = tf.reduce_sum((tensor1 - tensor2)**2, axis=(0, 1, 2)) _, feature_ranks = tf.math.top_k(diff_sq_sum, k=rank) feature_rank = feature_ranks[-1] channel_inds = tf.range(num_channels, dtype=tf.int32)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_cond_latents_at_level(cond_latents, level, hparams): """Returns a single or list of conditional latents at level 'level'."""
if cond_latents: if hparams.latent_dist_encoder in ["conv_net", "conv3d_net"]: return [cond_latent[level] for cond_latent in cond_latents] elif hparams.latent_dist_encoder in ["pointwise", "conv_lstm"]: return cond_latents[level]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_cond_latents(cond_latents, hparams): """Shape checking for cond_latents."""
if cond_latents is None: return if not isinstance(cond_latents[0], list): cond_latents = [cond_latents] exp_num_latents = hparams.num_cond_latents if hparams.latent_dist_encoder == "conv_net": exp_num_latents += int(hparams.cond_first_frame) if len(cond_latents) != exp_num_latents: raise Valu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_variable_ddi(name, shape, initial_value, dtype=tf.float32, init=False, trainable=True): """Wrapper for data-dependent initialization."""
# If init is a tf bool: w is assigned dynamically at runtime. # If init is a python bool: then w is determined during graph construction. w = tf.get_variable(name, shape, dtype, None, trainable=trainable) if isinstance(init, bool): if init: return assign(w, initial_value) return w else: ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dropout(x, rate=0.0, init=True): """Dropout x with dropout_rate = rate. Apply zero dropout during init or prediction time. Args: x: 4-D Tensor, shape=(NH...
if init or rate == 0: return x return tf.layers.dropout(x, rate=rate, training=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def actnorm_3d(name, x, logscale_factor=3.): """Applies actnorm to each time-step independently. There are a total of 2*n_channels*n_steps parameters learnt. Arg...
with tf.variable_scope(name, reuse=tf.AUTO_REUSE): x = tf.unstack(x, axis=1) x_normed = [] for ind, x_step in enumerate(x): x_step, _ = actnorm("actnorm_%d" % ind, x_step, logscale_factor=logscale_factor) x_normed.append(x_step) return tf.stack(x_normed, axis=1),...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def actnorm_center(name, x, reverse=False, init=False): """Add a bias to x. Initialize such that the output of the first minibatch is zero centered per channel. ...
shape = common_layers.shape_list(x) with tf.variable_scope(name, reuse=tf.AUTO_REUSE): assert len(shape) == 2 or len(shape) == 4 if len(shape) == 2: x_mean = tf.reduce_mean(x, [0], keepdims=True) b = get_variable_ddi("b", (1, shape[1]), initial_value=-x_mean, init=ini...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def actnorm_scale(name, x, logscale_factor=3., reverse=False, init=False): """Per-channel scaling of x."""
x_shape = common_layers.shape_list(x) with tf.variable_scope(name, reuse=tf.AUTO_REUSE): # Variance initialization logic. assert len(x_shape) == 2 or len(x_shape) == 4 if len(x_shape) == 2: x_var = tf.reduce_mean(x**2, [0], keepdims=True) logdet_factor = 1 var_shape = (1, x_shape[1])...