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_weights(model_hparams, vocab_size, hidden_dim=None): """Create or get concatenated embedding or softmax variable. Args: model_hparams: HParams, model hyp...
if hidden_dim is None: hidden_dim = model_hparams.hidden_size num_shards = model_hparams.symbol_modality_num_shards shards = [] for i in range(num_shards): shard_size = (vocab_size // num_shards) + ( 1 if i < vocab_size % num_shards else 0) var_name = "weights_%d" % i shards.append( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _symbol_bottom_simple(x, model_hparams, vocab_size, name, reuse): """Bottom transformation for symbols."""
with tf.variable_scope(name, reuse=reuse): # Ensure the inputs are 3-D if len(x.get_shape()) == 4: x = tf.squeeze(x, axis=3) while len(x.get_shape()) < 3: x = tf.expand_dims(x, axis=-1) var = get_weights(model_hparams, vocab_size) x = common_layers.dropout_no_scaling( x, 1.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 symbol_targets_bottom(x, model_hparams, vocab_size): """Bottom transformation for target symbols."""
if (model_hparams.shared_embedding_and_softmax_weights or model_hparams.get("shared_embedding")): try: return _symbol_bottom_simple( x, model_hparams, vocab_size, "shared", reuse=True) except ValueError: # perhaps there were no inputs, and this is a new variable. return _sym...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def video_bitwise_bottom(x, model_hparams, vocab_size): """Bottom transformation for embedding video bitwise."""
pixel_embedding_size = 64 inputs = x with tf.variable_scope("video_modality_bitwise", reuse=tf.AUTO_REUSE): common_layers.summarize_video(inputs, "bottom") # Embed bitwise. assert vocab_size == 256 embedded = discretization.int_to_bit_embed(inputs, 8, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def video_pixel_noise_bottom(x, model_hparams, vocab_size): """Bottom transformation for video."""
input_noise = getattr(model_hparams, "video_modality_input_noise", 0.25) inputs = x if model_hparams.mode == tf.estimator.ModeKeys.TRAIN: background = tfp.stats.percentile(inputs, 50., axis=[0, 1, 2, 3]) input_shape = common_layers.shape_list(inputs) input_size = tf.reduce_prod(input_shape[:-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 convert_rgb_to_real(prediction, targets): """Convert prediction and target from rgb to real."""
prediction = tf.squeeze(prediction, axis=-1) prediction = common_layers.convert_rgb_to_real(prediction) targets = common_layers.convert_rgb_to_real(targets) return prediction, targets
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ctc_symbol_loss(top_out, targets, model_hparams, vocab_size, weight_fn): """Compute the CTC loss."""
del model_hparams, vocab_size # unused arg logits = top_out with tf.name_scope("ctc_loss", values=[logits, targets]): # For CTC we assume targets are 1d, [batch, length, 1, 1] here. targets_shape = targets.get_shape().as_list() assert len(targets_shape) == 4 assert targets_shape[2] == 1 asse...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multi_label_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Average loss over the labels."""
del vocab_size # unused arg logits = top_out num_labels = tf.shape(targets)[1] logits = tf.tile(logits, [1, num_labels, 1, 1, 1]) xent, weights = common_layers.padded_cross_entropy( logits, targets, model_hparams.label_smoothing, weights_fn=weights_fn, reduce_sum=False, ) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def one_hot_class_label_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Apply softmax cross-entropy between outputs and targets. Args: top_out:...
del model_hparams, vocab_size # unused arg loss_scale = tf.losses.softmax_cross_entropy( onehot_labels=targets, logits=top_out) weights = weights_fn(targets) loss_denom = tf.reduce_sum(weights) return loss_scale, loss_denom
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def real_log_poisson_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Poisson loss for real."""
del model_hparams, vocab_size # unused arg predictions = top_out if (len(common_layers.shape_list(top_out)) != len( common_layers.shape_list(targets))): predictions = tf.squeeze(top_out, axis=[-1]) with tf.name_scope("log_possion"): weights = weights_fn(targets) lp_loss = tf.nn.log_poisson_l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def class_label_top(body_output, targets, model_hparams, vocab_size): """Transform inputs from model space to target space. Average over inner dims and a linear ...
del targets # unused arg with tf.variable_scope("class_label_modality_%d_%d" % ( vocab_size, model_hparams.hidden_size)): x = body_output x = tf.reduce_mean(x, axis=[1, 2], keepdims=True) res = tf.layers.dense(x, vocab_size) return tf.expand_dims(res, 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 image_channel_compress_top(body_output, targets, model_hparams, vocab_size): """Transforms body output to return logits. Args: body_output: Tensor of shape [...
del targets # unused arg with tf.variable_scope("image_channel_compress_modality"): hidden_size = model_hparams.hidden_size img_len = model_hparams.img_len channels = 3 # RGB batch = common_layers.shape_list(body_output)[0] x = tf.layers.conv2d( body_output, hidden_size * chan...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def symbol_top(body_output, targets, model_hparams, vocab_size): """Generate logits. Args: body_output: A Tensor with shape [batch, p0, p1, model_hparams.hidden_...
del targets # unused arg if model_hparams.shared_embedding_and_softmax_weights: scope_name = "shared" reuse = tf.AUTO_REUSE else: scope_name = "softmax" reuse = False with tf.variable_scope(scope_name, reuse=reuse): body_output_shape = common_layers.shape_list(body_output) var = get_we...
<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_bottom(modality_type, value=None): """Gets default bottom transformation; if none available, return value."""
if modality_type == ModalityType.AUDIO: return audio_bottom elif modality_type == ModalityType.AUDIO_SPECTRAL: return audio_spectral_bottom elif modality_type in (ModalityType.CLASS_LABEL, ModalityType.MULTI_LABEL, ModalityType.ONE_HOT_CLASS_LABEL, ...
<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_loss(modality_type, value=None): """Gets default loss transformation; if none available, return value."""
if modality_type in (ModalityType.AUDIO, ModalityType.AUDIO_SPECTRAL, ModalityType.CLASS_LABEL, ModalityType.IDENTITY, ModalityType.IDENTITY_SYMBOL, ModalityType.IMAGE, ModalityTy...
<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_name(modality_type, value=None): """Gets default name for transformations; if none available, return value."""
# For legacy reasons, modalities vary in their naming scheme. Future plans are # to remove any need for get_name. We do not recommend using it. if modality_type == ModalityType.AUDIO: return lambda model_hparams, vocab_size: "audio_modality" elif modality_type == ModalityType.AUDIO_SPECTRAL: return lam...
<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_targets_bottom(modality_type, value=None): """Gets default bottom transformation for targets; if none, return value."""
if modality_type == ModalityType.AUDIO: return make_targets_bottom(audio_bottom) elif modality_type == ModalityType.AUDIO_SPECTRAL: return make_targets_bottom(audio_spectral_bottom) elif modality_type in (ModalityType.CLASS_LABEL, ModalityType.MULTI_LABEL, ...
<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_top(modality_type, value=None): """Gets default top transformation; if none available, return value."""
if modality_type in (ModalityType.AUDIO, ModalityType.AUDIO_SPECTRAL, ModalityType.GENERIC_L2_LOSS, ModalityType.IDENTITY, ModalityType.IDENTITY_SYMBOL, ModalityType.IMAGE_CHANNEL_BOTTOM_IDENTITY, ...
<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_weights_fn(modality_type, value=None): """Gets default weights function; if none available, return value."""
if modality_type in (ModalityType.CTC_SYMBOL, ModalityType.IDENTITY_SYMBOL, ModalityType.MULTI_LABEL, ModalityType.SYMBOL, ModalityType.SYMBOL_ONE_HOT): return common_layers.weights_nonzero elif modality_type in Modalit...
<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_combination(list_of_sentences): """Generates all possible pair combinations for the input list of sentences. For example: input = ["paraphrase1", "par...
num_sentences = len(list_of_sentences) - 1 combinations = [] for i, _ in enumerate(list_of_sentences): if i == num_sentences: break num_pairs = num_sentences - i populated = num_pairs * [list_of_sentences[i]] zipped = list(zip(populated, list_of_sentences[i + 1:])) combinations += zippe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def imagetransformer2d_base_8l_8_32_big(): """hparams fo 8 layer big 2d model for cifar 10."""
hparams = image_transformer2d_base() hparams.num_heads = 16 hparams.hidden_size = 1024 hparams.filter_size = 2048 hparams.num_decoder_layers = 8 hparams.batch_size = 1 hparams.layer_prepostprocess_dropout = 0.3 hparams.query_shape = (8, 16) hparams.memory_flange = (0, 32) hparams.unconditional = in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def img2img_transformer2d_base(): """Base params for img2img 2d attention."""
hparams = image_transformer2d_base() # learning related flags hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" # This version seems to benefit from a higher learning rate. hparams.learning_rate = 0.2 hparams.layer_prepostprocess_dropout = 0.1 hparams.learning_rate_warmu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def img2img_transformer2d_q3(): """Current best hparams for local 2d."""
hparams = img2img_transformer2d_q1() hparams.batch_size = 2 hparams.query_shape = (8, 16) hparams.memory_flange = (8, 32) 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 img2img_transformer_base(): """Base params for local1d attention."""
hparams = image_transformer2d_base() # learning related flags hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" # This version seems to benefit from a higher learning rate. hparams.learning_rate = 0.2 hparams.layer_prepostprocess_dropout = 0.1 hparams.learning_rate_warmu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def img2img_transformer_b3(): """Current best hparams for local 1d."""
hparams = img2img_transformer_base() hparams.batch_size = 2 hparams.layer_preprocess_sequence = "none" hparams.layer_postprocess_sequence = "dan" hparams.block_length = 128 hparams.sampling_temp = 0.9 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 img2img_transformer_dilated(): """Try dilated."""
hparams = img2img_transformer_base() hparams.add_hparam("num_memory_blocks", 1) hparams.num_heads = 8 hparams.attention_key_channels = hparams.attention_value_channels = 0 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.num_decoder_layers = 8 hparams.sampling_method = "random" hparams.ga...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def img2img_transformer_base_tpu(): """Hparams for training img2img_transformer on tpu."""
hparams = img2img_transformer_base() update_hparams_for_tpu(hparams) hparams.batch_size = 2 hparams.num_heads = 4 # heads are expensive on tpu hparams.num_decoder_layers = 8 hparams.num_encoder_layers = 4 hparams.shared_embedding_and_softmax_weights = 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 ResidualFeedForward(feature_depth, feedforward_depth, dropout, mode): """Residual feed-forward layer with normalization at start."""
return layers.Residual( layers.LayerNorm(), layers.Dense(feedforward_depth), layers.Relu(), layers.Dropout(rate=dropout, mode=mode), layers.Dense(feature_depth), layers.Dropout(rate=dropout, mode=mode) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def EncoderLayer(feature_depth, feedforward_depth, num_heads, dropout, mode): """Transformer encoder layer. The input to the encoder is a pair (embedded source, ...
# The encoder block expects (activation, mask) as input and returns # the new activations only, we add the mask back to output next. encoder_block = layers.Serial( layers.Residual( # Attention block here. layers.Parallel(layers.LayerNorm(), layers.Identity()), layers.MultiHeadedAttenti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def TransformerEncoder(vocab_size, num_classes=10, feature_depth=512, feedforward_depth=2048, num_layers=6, num_heads=8, dropout=0.1, max_len=2048, mode='train'):...
input_embedding = layers.Serial( layers.Embedding(feature_depth, vocab_size), layers.Dropout(rate=dropout, mode=mode), layers.PositionalEncoding(max_len=max_len) ) return layers.Serial( layers.Branch(), # Branch input to create embedding and mask. layers.Parallel(input_embedding, l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def DecoderLayer(feature_depth, feedforward_depth, num_heads, dropout, mode): """Transformer decoder layer. Args: feature_depth: int: depth of embedding feedforw...
return layers.Serial( layers.Residual( # Self-attention block. layers.LayerNorm(), layers.Branch(), layers.Parallel(layers.Identity(), # activation for (q, k, v) layers.CausalMask(axis=-2)), # attention mask layers.MultiHeadedAttention(featur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ChunkedDecoderLayer(feature_depth, feedforward_depth, num_heads, dropout, chunk_selector, mode): """Transformer decoder layer operating on chunks. Args: feat...
return layers.Serial( layers.Residual( # Self-attention block. layers.Map(layers.LayerNorm()), layers.ChunkedCausalMultiHeadedAttention( feature_depth, num_heads=num_heads, dropout=dropout, chunk_selector=chunk_selector, mode=mode), layers.Map(layers.D...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ChunkedTransformerLM(vocab_size, feature_depth=512, feedforward_depth=2048, num_layers=6, num_heads=8, dropout=0.1, chunk_selector=None, max_len=2048, mode='t...
stack = [ChunkedDecoderLayer(feature_depth, feedforward_depth, num_heads, dropout, chunk_selector, mode) for _ in range(num_layers)] # Below each Map(L) applies the layer L to each chunk independently. return layers.Serial( layers.ShiftRight(), layers.Map(lay...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mtf_transformer_paper_lm(size): """Config for language-model experiments. Train these on languagemodel_lm1b32k_packed for 136000 steps (10 epochs) The size p...
n = 2 ** size hparams = mtf_transformer_base_lm() hparams.batch_size = 256 hparams.d_model = 1024 hparams.d_ff = int(8192 * n) hparams.d_kv = 256 hparams.num_heads = int(8 * n) hparams.shared_embedding_and_softmax_weights = False # one epoch for languagemodel_lm1b32k_packed = 13600 steps hparams.le...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mtf_transformer_paper_tr(size): """Config for translation experiments. Train these on translate_enfr_wmt32k_packed for 154000 steps (3 epochs) The size param...
n = 2 ** size hparams = mtf_transformer_base() hparams.label_smoothing = 0.1 hparams.batch_size = 128 hparams.d_model = 1024 hparams.d_ff = int(4096 * n) hparams.num_heads = int(8 * n) hparams.shared_embedding_and_softmax_weights = False # one epoch for translate_enfr_wmt32k_packed = 51400 steps hp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mtf_transformer_lm_baseline(): """Small language model to run on 1 TPU. Run this on 2x2 on languagemodel_lm1b32k_packed for 272000 steps (10 epochs) Results:...
hparams = mtf_transformer_paper_lm(-1) hparams.batch_size = 128 hparams.learning_rate_decay_steps = 27200 # one epoch on lm1b 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 graph_attention(q, k, v, bias, dropout_rate=0.0, image_shapes=None, name=None, make_image_summary=True, save_weights_to=None, dropout_broadcast_dims=None, adj...
with tf.variable_scope( name, default_name="dot_product_attention", values=[q, k, v]) as scope: # [batch, num_heads, query_length, memory_length] logits = tf.matmul(q, k, transpose_b=True) if adjacency_matrix is not None: key_head_depth = common_layers.shape_list(q)[-1] adjacency_vector...
<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_edge_transforms(node_states, depth, num_transforms, name="transform"): """Helper function that computes transformation for keys and values. Let B be...
node_shapes = common_layers.shape_list(node_states) x = common_layers.dense( node_states, depth * num_transforms, use_bias=False, name=name) batch = node_shapes[0] # B. length = node_shapes[1] # N. # Making the fourth dimension explicit by separating the vectors of size # K*T (i...
<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_mpnn_qkv(node_states, total_key_depth, total_value_depth, num_transforms): """Computes query, key and value for edge matrices. Let B be the number of...
# node_states is initially a tensor with shape [B, N, D]. The call to dense # creates a D x K kernel that serves as a fully-connected layer. # # For each possible batch b and node n in the first two dimensions of # node_states, the corresponding size-D vector (the third dimension of # node_states) is the ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sparse_message_pass_batched(node_states, adjacency_matrices, num_edge_types, hidden_size, use_bias=True, average_aggregation=False, name="sparse_ggnn_batched"...
b, n = tf.shape(node_states)[0], tf.shape(node_states)[1] # Flatten the batch dimension of the node states. node_states = tf.reshape(node_states, [b*n, hidden_size]) # Flatten the batch dimension of the adjacency matrices. indices = adjacency_matrices.indices new_index2 = indices[:, 3] # The edge type ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sparse_message_pass(node_states, adjacency_matrices, num_edge_types, hidden_size, use_bias=True, average_aggregation=False, name="sparse_ggnn"): """One messa...
n = tf.shape(node_states)[0] t = num_edge_types incoming_edges_per_type = tf.sparse_reduce_sum(adjacency_matrices, axis=1) # Convert the adjacency matrix into shape [T, N, N] - one [N, N] adjacency # matrix for each edge type. Since sparse tensor multiplication only supports # two-dimensional tensors, we ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dot_product_mpnn_attention(q, k, v, adjacency_matrix, num_edge_types, num_transforms=None, use_weighted_sum=False, name=None): """Dot product attention with ...
with tf.variable_scope( name, default_name="dot_product_mpnn_attention", values=[q, k, v, adjacency_matrix, num_edge_types]): # If not explicitly set, use num_transforms set to num_edge_types. num_transforms = ( num_edge_types if num_transforms is None else num_transforms) if n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ggnn_fast_dense(node_states, adjacency_matrix, num_edge_types, total_value_depth, name=None): """ggnn version of the MPNN from Gilmer et al. Let B be the num...
# between the same nodes (with only one edge of each type. adjacency_matrix # will need to be converted to shape [B, T, N, N]. with tf.variable_scope( name, default_name="ggnn_fast_dense", values=[node_states, adjacency_matrix, num_edge_types]): nodes_shape = common_layers.shape_list(node_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 compute_values(edge_compatibility, v): """Compute values. If edge compatibilities is just adjacency, we get ggnn. Args: edge_compatibility: A tensor of shape...
# Computes the incoming value vectors for each node by weighting them # according to the attention weights. These values are still segregated by # edge type. # Shape = [B, T, N, V]. all_edge_values = tf.matmul(tf.to_float(edge_compatibility), v) # Combines the weighted value vectors together across edge ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def precompute_edge_matrices(adjacency, hparams): """Precompute the a_in and a_out tensors. (we don't want to add to the graph everytime _fprop is called) Args: ...
batch_size, num_nodes, _, edge_dim = common_layers.shape_list(adjacency) # build the edge_network for incoming edges with tf.variable_scope("edge_network"): x = tf.reshape( adjacency, [batch_size * num_nodes * num_nodes, edge_dim], name="adj_reshape_in") for ip_layer in range(hparams.ed...
<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_files_distributed(generator, output_name, output_dir, num_shards=1, max_cases=None, task_id=0): """generate_files but with a single writer writing t...
assert task_id < num_shards output_filename = sharded_name(output_name, task_id, num_shards) output_file = os.path.join(output_dir, output_filename) tf.logging.info("Writing to file %s", output_file) writer = tf.python_io.TFRecordWriter(output_file) counter = 0 for case in generator: if counter % 10...
<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_files(generator, output_filenames, max_cases=None, cycle_every_n=1): """Generate cases from a generator and save as TFRecord files. Generated cases ...
if outputs_exist(output_filenames): tf.logging.info("Skipping generator because outputs files exists at {}" .format(output_filenames)) return tmp_filenames = [fname + ".incomplete" for fname in output_filenames] num_shards = len(output_filenames) # Check if is training or eval, ref:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_report_hook(count, block_size, total_size): """Report hook for download progress. Args: count: current block number block_size: block size total_siz...
percent = int(count * block_size * 100 / total_size) print("\r%d%%" % percent + " completed", end="\r")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maybe_download(directory, filename, uri): """Download filename from uri unless it's already in directory. Copies a remote file to local if that local file do...
tf.gfile.MakeDirs(directory) filepath = os.path.join(directory, filename) if tf.gfile.Exists(filepath): tf.logging.info("Not downloading, file already found: %s" % filepath) return filepath tf.logging.info("Downloading %s to %s" % (uri, filepath)) try: tf.gfile.Copy(uri, filepath) except tf.er...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maybe_download_from_drive(directory, filename, url): """Download filename from Google drive unless it's already in directory. Args: directory: path to the di...
if not tf.gfile.Exists(directory): tf.logging.info("Creating directory %s" % directory) tf.gfile.MakeDirs(directory) filepath = os.path.join(directory, filename) confirm_token = None if tf.gfile.Exists(filepath): tf.logging.info("Not downloading, file already found: %s" % filepath) return filep...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gunzip_file(gz_path, new_path): """Unzips from gz_path into new_path. Args: gz_path: path to the zipped file. new_path: path to where the file will be unzipp...
if tf.gfile.Exists(new_path): tf.logging.info("File %s already exists, skipping unpacking" % new_path) return tf.logging.info("Unpacking %s to %s" % (gz_path, new_path)) # We may be unpacking into a newly created directory, add write mode. mode = stat.S_IRWXU or stat.S_IXGRP or stat.S_IRGRP or stat.S_I...
<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_or_generate_vocab_inner(data_dir, vocab_filename, vocab_size, generator, max_subtoken_length=None, reserved_tokens=None): """Inner implementation for voc...
if data_dir and vocab_filename: vocab_filepath = os.path.join(data_dir, vocab_filename) if tf.gfile.Exists(vocab_filepath): tf.logging.info("Found vocab file: %s", vocab_filepath) return text_encoder.SubwordTextEncoder(vocab_filepath) else: vocab_filepath = None tf.logging.info("Generati...
<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_or_generate_vocab(data_dir, tmp_dir, vocab_filename, vocab_size, sources, file_byte_budget=1e6, max_subtoken_length=None): """Generate a vocabulary from ...
vocab_generator = generate_lines_for_vocab(tmp_dir, sources, file_byte_budget) return get_or_generate_vocab_inner(data_dir, vocab_filename, vocab_size, vocab_generator, max_subtoken_length)
<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_lines_for_vocab(tmp_dir, sources, file_byte_budget=1e6): """Generate lines for vocabulary generation."""
tf.logging.info("Generating vocab from: %s", str(sources)) for source in sources: url = source[0] filename = os.path.basename(url) compressed_file = maybe_download(tmp_dir, filename, url) for lang_file in source[1]: tf.logging.info("Reading file: %s" % lang_file) filepath = os.path.joi...
<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_or_generate_tabbed_vocab(data_dir, tmp_dir, source_filename, index, vocab_filename, vocab_size): r"""Generate a vocabulary from a tabbed source file. The...
def generate(): filepath = os.path.join(tmp_dir, source_filename) tf.logging.info("Generating vocab from %s", filepath) with tf.gfile.GFile(filepath, mode="r") as source_file: for line in source_file: line = line.strip() if line and "\t" in line: parts = line.split("\t", 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 get_or_generate_txt_vocab(data_dir, vocab_filename, vocab_size, filepatterns): """Generate a vocabulary from txt files with example-per-line."""
if isinstance(filepatterns, str): filepatterns = [filepatterns] def generate(): tf.logging.info("Generating vocab from %s", filepatterns) for filepattern in filepatterns: for filename in tf.gfile.Glob(filepattern): with tf.gfile.GFile(filename, mode="r") as source_file: for lin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _shuffle_single(fname, extra_fn=None): """Shuffle a single file of records. Args: fname: a string extra_fn: an optional function from list of TFRecords to li...
records = read_records(fname) random.shuffle(records) if extra_fn is not None: records = extra_fn(records) out_fname = fname.replace(UNSHUFFLED_SUFFIX, "") write_records(records, out_fname) tf.gfile.Remove(fname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shuffle_dataset(filenames, extra_fn=None): """Shuffles the dataset. Args: filenames: a list of strings extra_fn: an optional function from list of records to...
if outputs_exist(filenames): tf.logging.info("Skipping shuffle because output files exist") return tf.logging.info("Shuffling data...") for filename in filenames: _shuffle_single(filename, extra_fn=extra_fn) tf.logging.info("Data shuffled.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pack_examples(examples, has_inputs, packed_length=256, spacing=2, queue_size=10, chop_long_sequences=False): """Pack examples into longer examples. If has_in...
packer = SequencePairPacker if has_inputs else SequencePacker combined = [] for example in examples: x = ((example["inputs"], example["targets"]) if has_inputs else example["targets"]) if chop_long_sequences and len(x) > packed_length: assert not has_inputs num_fragments = len(x) // ...
<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_tmp_dir(suffix="", prefix="tmp", dir=None): # pylint: disable=redefined-builtin """Make a temporary directory."""
if dir is None: return tempfile.mkdtemp(suffix, prefix, dir) else: while True: rand_term = random.randint(1, 9999) tmp_dir = os.path.join(dir, "%s%d%s" % (prefix, rand_term, suffix)) if tf.gfile.Exists(tmp_dir): continue tf.gfile.MakeDirs(tmp_dir) break return tmp_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tfrecord_iterator_for_problem(problem, data_dir, dataset_split=tf.estimator.ModeKeys.TRAIN): """Iterate over the records on disk for the Problem."""
filenames = tf.gfile.Glob(problem.filepattern(data_dir, mode=dataset_split)) example_spec = problem.example_reading_spec()[0] return tfrecord_iterator(filenames, example_spec=example_spec)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tfrecord_iterator(filenames, gzipped=False, example_spec=None): """Yields records from TFRecord files. Args: filenames: list<str>, list of TFRecord filenames...
with tf.Graph().as_default(): dataset = tf.data.Dataset.from_tensor_slices(filenames) def _load_records(filename): return tf.data.TFRecordDataset( filename, compression_type=tf.constant("GZIP") if gzipped else None, buffer_size=16 * 1000 * 1000) dataset = dataset.fla...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random_deinterleave(text, separator_symbol="X"): """Create a fill-in-the-blanks training example from text. Split on spaces, then cut into segments at random...
words = text.strip().split(" ") n = len(words) if n <= 1: return text, "" cut = [False] * n cut[0] = True num_cuts = int(math.exp(random.uniform(0, math.log(n)))) for _ in range(num_cuts): cut[random.randint(1, n -1)] = True out = [[], []] part = random.randint(0, 1) for i in range(n): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def neural_gpu_body(inputs, hparams, name=None): """The core Neural GPU."""
with tf.variable_scope(name, "neural_gpu"): def step(state, inp): # pylint: disable=missing-docstring x = tf.nn.dropout(state, 1.0 - hparams.dropout) for layer in range(hparams.num_hidden_layers): x = common_layers.conv_gru( x, (hparams.kernel_height, hparams.kernel_width), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reorder_shape(input_shape, output=None): # pylint: disable=invalid-name """Helper to determine the shape of reorder output."""
if output is None: return input_shape return base.nested_map(output, lambda i: input_shape[i])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Reorder(x, params, output=None, **kwargs): """Reorder a tuple into another tuple. For example, we can re-order (x, y) into (y, x) or even (y, (x, y), y). The...
del params, kwargs if output is None: return x return base.nested_map(output, lambda i: x[i])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _concatenate_shape(input_shape, axis=-1): # pylint: disable=invalid-name """Helper to determine the shape of Concatenate output."""
ax = axis % len(input_shape[0]) concat_size = sum(shape[ax] for shape in input_shape) out_shape = input_shape[0][:ax] + (concat_size,) + input_shape[0][ax+1:] return out_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 Residual(*layers, **kwargs): """Constructs a residual version of layers, summing input to layers output."""
shortcut = kwargs.get('shortcut', Identity()) # pylint: disable=no-value-for-parameter if len(layers) > 1: return Serial( Branch(), # pylint: disable=no-value-for-parameter Parallel(Serial(*layers), shortcut), SumBranches() # pylint: disable=no-value-for-parameter ) elif len(la...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_hparams_for_universal_transformer(hparams): """Adds default hparams for all of the variants of the Universal Transformer. Args: hparams: default hpara...
hparams.daisy_chain_variables = False # Breaks multi-gpu in while loops. # If not None, mixes vanilla transformer with Universal Transformer. # Options: None, "before_ut", and "after_ut". hparams.add_hparam("mix_with_transformer", None) # Number of vanilla transformer layers used to be mixed with u-transo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def universal_transformer_base(): """Base parameters for Universal Transformer."""
hparams = transformer.transformer_base() # To have a similar capacity to the transformer_base with 6 layers, # we need to increase the size of the UT's layer # since, in fact, UT has a single layer repeating multiple times. hparams.hidden_size = 1024 hparams.filter_size = 4096 hparams.num_heads = 16 hp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adaptive_universal_transformer_multilayer_tpu(): """Multi-layer config for adaptive Transformer on TPU."""
hparams = adaptive_universal_transformer_base_tpu() hparams.num_inrecurrence_layers = 2 hparams.mix_with_transformer = "before_ut,after_ut" hparams.num_mixedin_layers = 1 hparams.transformer_ffn_type = "sepconv" # TODO(lukaszkaiser): the options below don't work on TPU yet, make them work. # hparams.add_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adaptive_universal_transformer_multilayer_hard(): """Multi-layer config for adaptive Transformer with hard attention."""
hparams = adaptive_universal_transformer_multilayer_tpu() hparams.batch_size = 256 hparams.hard_attention_k = 8 hparams.add_step_timing_signal = True # hparams.add_sru = True # This is very slow on GPUs, does it help? hparams.self_attention_type = "dot_product_relative_v2" hparams.max_relative_position ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ConvDiagonalGRU(units, kernel_size=(3, 3)): """Build convolutional GRU with diagonal gating as in ImprovedNGPU."""
def BuildConv(): return layers.Conv(filters=units, kernel_size=kernel_size, padding='SAME') return layers.GeneralGRUCell( candidate_transform=BuildConv, memory_transform=DiagonalGate, gate_nonlinearity=layers.HardSigmoid, candidate_nonlinearity=layers.HardTanh)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strip_ids(ids, ids_to_strip): """Strip ids_to_strip from the end ids."""
ids = list(ids) while ids and ids[-1] in ids_to_strip: ids.pop() return ids
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _escape_token(token, alphabet): """Escape away underscores and OOV characters and append '_'. This allows the token to be expressed as the concatenation of a...
if not isinstance(token, six.text_type): raise ValueError("Expected string type for token, got %s" % type(token)) token = token.replace(u"\\", u"\\\\").replace(u"_", u"\\u") ret = [c if c in alphabet and c != u"\n" else r"\%d;" % ord(c) for c in token] return u"".join(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 encode(self, s): """Transform a human-readable string into a sequence of int ids. The ids should be in the range [num_reserved_ids, vocab_size). Ids [0, num_...
return [int(w) + self._num_reserved_ids for w in s.split()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(self, ids, strip_extraneous=False): """Transform a sequence of int ids into a human-readable string. EOS is not expected in ids. Args: ids: list of in...
if strip_extraneous: ids = strip_ids(ids, list(range(self._num_reserved_ids or 0))) return " ".join(self.decode_list(ids))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode_list(self, ids): """Transform a sequence of int ids into a their string versions. This method supports transforming individual input/output ids to the...
decoded_ids = [] for id_ in ids: if 0 <= id_ < self._num_reserved_ids: decoded_ids.append(RESERVED_TOKENS[int(id_)]) else: decoded_ids.append(id_ - self._num_reserved_ids) return [str(d) for d in decoded_ids]
<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(self, s): """Converts a space-separated string of tokens to a list of ids."""
sentence = s tokens = sentence.strip().split() if self._replace_oov is not None: tokens = [t if t in self._token_to_id else self._replace_oov for t in tokens] ret = [self._token_to_id[tok] for tok in tokens] return ret[::-1] if self._reverse 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 _init_vocab_from_list(self, vocab_list): """Initialize tokens from a list of tokens. It is ok if reserved tokens appear in the vocab list. They will be remov...
def token_gen(): for token in vocab_list: if token not in RESERVED_TOKENS: yield token self._init_vocab(token_gen())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_vocab(self, token_generator, add_reserved_tokens=True): """Initialize vocabulary with tokens from token_generator."""
self._id_to_token = {} non_reserved_start_index = 0 if add_reserved_tokens: self._id_to_token.update(enumerate(RESERVED_TOKENS)) non_reserved_start_index = len(RESERVED_TOKENS) self._id_to_token.update( enumerate(token_generator, start=non_reserved_start_index)) # _token_to_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def store_to_file(self, filename): """Write vocab file to disk. Vocab files have one token per line. The file ends in a newline. Reserved tokens are written to t...
with tf.gfile.Open(filename, "w") as f: for i in range(len(self._id_to_token)): f.write(self._id_to_token[i] + "\n")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(self, ids, strip_extraneous=False): """Converts a sequence of subtoken ids to a native string. Args: ids: a list of integers in the range [0, vocab_si...
if strip_extraneous: ids = strip_ids(ids, list(range(self._num_reserved_ids or 0))) return unicode_to_native( tokenizer.decode(self._subtoken_ids_to_tokens(ids)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _tokens_to_subtoken_ids(self, tokens): """Converts a list of tokens to a list of subtoken ids. Args: tokens: a list of strings. Returns: a list of integers i...
ret = [] for token in tokens: ret.extend(self._token_to_subtoken_ids(token)) 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 _token_to_subtoken_ids(self, token): """Converts token to a list of subtoken ids. Args: token: a string. Returns: a list of integers in the range [0, vocab_s...
cache_location = hash(token) % self._cache_size cache_key, cache_value = self._cache[cache_location] if cache_key == token: return cache_value ret = self._escaped_token_to_subtoken_ids( _escape_token(token, self._alphabet)) self._cache[cache_location] = (token, 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 _subtoken_ids_to_tokens(self, subtokens): """Converts a list of subtoken ids to a list of tokens. Args: subtokens: a list of integers in the range [0, vocab_...
concatenated = "".join( [self._subtoken_id_to_subtoken_string(s) for s in subtokens]) split = concatenated.split("_") ret = [] for t in split: if t: unescaped = _unescape_token(t + "_") if unescaped: ret.append(unescaped) 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 _subtoken_id_to_subtoken_string(self, subtoken): """Converts a subtoken integer ID to a subtoken string."""
if 0 <= subtoken < self.vocab_size: return self._all_subtoken_strings[subtoken] return u""
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _escaped_token_to_subtoken_ids(self, escaped_token): """Converts an escaped token string to a list of subtoken IDs. Args: escaped_token: An escaped token as ...
return [ self._subtoken_string_to_id[subtoken] for subtoken in self._escaped_token_to_subtoken_strings(escaped_token) ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_from_generator(cls, generator, target_size, max_subtoken_length=None, reserved_tokens=None): """Builds a SubwordTextEncoder from the generated text. Ar...
token_counts = collections.defaultdict(int) for item in generator: for tok in tokenizer.encode(native_to_unicode(item)): token_counts[tok] += 1 encoder = cls.build_to_target_size( target_size, token_counts, 1, 1e3, max_subtoken_length=max_subtoken_length, reserved_toke...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_to_target_size(cls, target_size, token_counts, min_val, max_val, max_subtoken_length=None, reserved_tokens=None, num_iterations=4): """Builds a Subword...
if min_val > max_val: raise ValueError("Lower bound for the minimum token count " "is greater than the upper bound.") if target_size < 1: raise ValueError("Target size must be positive.") if reserved_tokens is None: reserved_tokens = RESERVED_TOKENS def bisect...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_from_token_counts(self, token_counts, min_count, num_iterations=4, reserved_tokens=None, max_subtoken_length=None): """Train a SubwordTextEncoder based...
if reserved_tokens is None: reserved_tokens = RESERVED_TOKENS else: # There is not complete freedom in replacing RESERVED_TOKENS. for default, proposed in zip(RESERVED_TOKENS, reserved_tokens): if default != proposed: raise ValueError("RESERVED_TOKENS must be a prefix of " ...
<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(self): """Debugging dump of the current subtoken vocabulary."""
subtoken_strings = [(i, s) for s, i in six.iteritems(self._subtoken_string_to_id)] print(u", ".join(u"{0} : '{1}'".format(i, s) for i, s in sorted(subtoken_strings)))
<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_from_file_object(self, f): """Load from a file object. Args: f: File object to load vocabulary from """
subtoken_strings = [] for line in f: s = line.strip() # Some vocab files wrap words in single quotes, but others don't if ((s.startswith("'") and s.endswith("'")) or (s.startswith("\"") and s.endswith("\""))): s = s[1:-1] subtoken_strings.append(native_to_unicode(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 _load_from_file(self, filename): """Load from a vocab file."""
if not tf.gfile.Exists(filename): raise ValueError("File %s not found" % filename) with tf.gfile.Open(filename) as f: self._load_from_file_object(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 encode(self, s): """Transform a string with a filename into a list of RGB integers. Args: s: path to the file with an image. Returns: ids: list of integers "...
try: import matplotlib.image as im # pylint: disable=g-import-not-at-top except ImportError as e: tf.logging.warning( "Reading an image requires matplotlib to be installed: %s", e) raise NotImplementedError("Image reading not implemented.") return im.imread(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 decode(self, ids, strip_extraneous=False): """Transform a sequence of int ids into an image file. Args: ids: list of integers to be converted. strip_extraneo...
del strip_extraneous _, tmp_file_path = tempfile.mkstemp("_decode.png") if self._height is None or self._width is None: size = int(math.sqrt(len(ids) / self._channels)) length = size * size * self._channels else: size = None length = self._height * self._width * self._channels ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pack_images(images, rows, cols): """Helper utility to make a tiled field of images from numpy arrays. Args: images: Image tensor in shape [N, W, H, C]. rows...
shape = onp.shape(images) width, height, depth = shape[-3:] images = onp.reshape(images, (-1, width, height, depth)) batch = onp.shape(images)[0] rows = onp.minimum(rows, batch) cols = onp.minimum(batch // rows, cols) images = images[:rows * cols] images = onp.reshape(images, (rows, cols, width, height...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def markdownify_operative_config_str(string): """Convert an operative config string to markdown format."""
# TODO(b/37527917): Total hack below. Implement more principled formatting. def process(line): """Convert a single line to markdown format.""" if not line.startswith('#'): return ' ' + line line = line[2:] if line.startswith('===='): return '' if line.startswith('None'): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Close SummaryWriter. Final!"""
if not self._closed: self._event_writer.close() self._closed = True del self._event_writer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scalar(self, tag, value, step=None): """Saves scalar value. Args: tag: str: label for this data value: int/float: number to log step: int: training step """
value = float(onp.array(value)) if step is None: step = self._step else: self._step = step summary = Summary(value=[Summary.Value(tag=tag, simple_value=value)]) self.add_summary(summary, step)