project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
sek788432/Waymo-2D-Object-Detection | decoding_module.py | shape_list | shape_list | Return a list of the tensor's shape, and ensure no None values in list. | [
"Return",
"a",
"list",
"of",
"the",
"tensor's",
"shape,",
"and",
"ensure",
"no",
"None",
"values",
"in",
"list."
] | def shape_list(tensor):
return tf_utils.get_shape_list(tensor) | ['def', 'shape_list(tensor):', 'return', 'tf_utils.get_shape_list(tensor)'] | 972,699 |
sek788432/Waymo-2D-Object-Detection | decoding_module.py | expand_to_same_rank | expand_to_same_rank | Expands a given tensor to target's rank to be broadcastable. | [
"Expands",
"a",
"given",
"tensor",
"to",
"target's",
"rank",
"to",
"be",
"broadcastable."
] | def expand_to_same_rank(tensor, target):
if tensor.shape.rank is None:
raise ValueError('Expect rank for tensor shape, but got None.')
if target.shape.rank is None:
raise ValueError('Expect rank for target shape, but got None.')
with tf.name_scope('expand_rank'):
diff_rank = target.s... | ['def', 'expand_to_same_rank(tensor,', 'target):', 'if', 'tensor.shape.rank', 'is', 'None:', 'raise', "ValueError('Expect", 'rank', 'for', 'tensor', 'shape,', 'but', 'got', "None.')", 'if', 'target.shape.rank', 'is', 'None:', 'raise', "ValueError('Expect", 'rank', 'for', 'target', 'shape,', 'but', 'got', "None.')", 'wi... | 972,700 |
sek788432/Waymo-2D-Object-Detection | sampling_module.py | greedy | greedy | Returns the top ids and scores based on greedy decoding. | [
"Returns",
"the",
"top",
"ids",
"and",
"scores",
"based",
"on",
"greedy",
"decoding."
] | def greedy(log_probs):
(log_probs, ids) = tf.math.top_k(log_probs, k=1)
return (log_probs, ids) | ['def', 'greedy(log_probs):', '(log_probs,', 'ids)', '=', 'tf.math.top_k(log_probs,', 'k=1)', 'return', '(log_probs,', 'ids)'] | 972,704 |
sek788432/Waymo-2D-Object-Detection | sampling_module.py | sample_top_k | sample_top_k | Chooses top_k logits and sets the others to negative infinity. | [
"Chooses",
"top_k",
"logits",
"and",
"sets",
"the",
"others",
"to",
"negative",
"infinity."
] | def sample_top_k(logits, top_k):
top_k_logits = tf.math.top_k(logits, k=top_k)
indices_to_remove = logits < tf.expand_dims(top_k_logits[0][..., -1], -1)
top_k_logits = set_tensor_by_indices_to_value(logits, indices_to_remove, np.NINF)
return top_k_logits | ['def', 'sample_top_k(logits,', 'top_k):', 'top_k_logits', '=', 'tf.math.top_k(logits,', 'k=top_k)', 'indices_to_remove', '=', 'logits', '<', 'tf.expand_dims(top_k_logits[0][...,', '-1],', '-1)', 'top_k_logits', '=', 'set_tensor_by_indices_to_value(logits,', 'indices_to_remove,', 'np.NINF)', 'return', 'top_k_logits'] | 972,706 |
sek788432/Waymo-2D-Object-Detection | sampling_module.py | scatter_values_on_batch_indices | scatter_values_on_batch_indices | Scatter `values` into a tensor using `batch_indices`. | [
"Scatter",
"`values`",
"into",
"a",
"tensor",
"using",
"`batch_indices`."
] | def scatter_values_on_batch_indices(values, batch_indices):
tensor_shape = decoding_module.shape_list(batch_indices)
broad_casted_batch_dims = tf.reshape(tf.broadcast_to(tf.expand_dims(tf.range(tensor_shape[0]), axis=-1), tensor_shape), [1, -1])
pair_indices = tf.transpose(tf.concat([broad_casted_batch_dims... | ['def', 'scatter_values_on_batch_indices(values,', 'batch_indices):', 'tensor_shape', '=', 'decoding_module.shape_list(batch_indices)', 'broad_casted_batch_dims', '=', 'tf.reshape(tf.broadcast_to(tf.expand_dims(tf.range(tensor_shape[0]),', 'axis=-1),', 'tensor_shape),', '[1,', '-1])', 'pair_indices', '=', 'tf.transpose... | 972,708 |
sek788432/Waymo-2D-Object-Detection | sampling_module.py | set_tensor_by_indices_to_value | set_tensor_by_indices_to_value | Where indices is True, set the value in input_tensor to value. | [
"Where",
"indices",
"is",
"True,",
"set",
"the",
"value",
"in",
"input_tensor",
"to",
"value."
] | def set_tensor_by_indices_to_value(input_tensor, indices, value):
value_tensor = tf.zeros_like(input_tensor) + value
output_tensor = tf.where(indices, value_tensor, input_tensor)
return output_tensor | ['def', 'set_tensor_by_indices_to_value(input_tensor,', 'indices,', 'value):', 'value_tensor', '=', 'tf.zeros_like(input_tensor)', '+', 'value', 'output_tensor', '=', 'tf.where(indices,', 'value_tensor,', 'input_tensor)', 'return', 'output_tensor'] | 972,709 |
sek788432/Waymo-2D-Object-Detection | trainer.py | define_flags | define_flags | Defines command line flags used by NHNet trainer. | [
"Defines",
"command",
"line",
"flags",
"used",
"by",
"NHNet",
"trainer."
] | def define_flags():
flags.DEFINE_enum('mode', 'train', ['train', 'eval', 'train_and_eval'], 'Execution mode.')
flags.DEFINE_string('train_file_pattern', '', 'Train file pattern.')
flags.DEFINE_string('eval_file_pattern', '', 'Eval file pattern.')
flags.DEFINE_string('model_dir', None, 'The output direct... | ['def', 'define_flags():', "flags.DEFINE_enum('mode',", "'train',", "['train',", "'eval',", "'train_and_eval'],", "'Execution", "mode.')", "flags.DEFINE_string('train_file_pattern',", "'',", "'Train", 'file', "pattern.')", "flags.DEFINE_string('eval_file_pattern',", "'',", "'Eval", 'file', "pattern.')", "flags.DEFINE_s... | 972,746 |
sek788432/Waymo-2D-Object-Detection | recompute_grad.py | get_recompute_context | get_recompute_context | Returns the current recomputing context if it exists. | [
"Returns",
"the",
"current",
"recomputing",
"context",
"if",
"it",
"exists."
] | def get_recompute_context() -> Optional[RecomputeContext]:
return _context_stack.top() | ['def', 'get_recompute_context()', '->', 'Optional[RecomputeContext]:', 'return', '_context_stack.top()'] | 972,754 |
sek788432/Waymo-2D-Object-Detection | distillation.py | BertDistillationTask.get_train_dataset | get_train_dataset | Return Dataset for this stage. | [
"Return",
"Dataset",
"for",
"this",
"stage."
] | def get_train_dataset(self, stage_id: int) -> tf.data.Dataset:
del stage_id
if self._the_only_train_dataset is None:
self._the_only_train_dataset = orbit.utils.make_distributed_dataset(self._strategy, self.build_inputs, self._train_data_config)
return self._the_only_train_dataset | ['def', 'get_train_dataset(self,', 'stage_id:', 'int)', '->', 'tf.data.Dataset:', 'del', 'stage_id', 'if', 'self._the_only_train_dataset', 'is', 'None:', 'self._the_only_train_dataset', '=', 'orbit.utils.make_distributed_dataset(self._strategy,', 'self.build_inputs,', 'self._train_data_config)', 'return', 'self._the_on... | 972,761 |
sek788432/Waymo-2D-Object-Detection | distillation.py | BertDistillationTask.build_model | build_model | Build teacher/student keras models with outputs for current stage. | [
"Build",
"teacher/student",
"keras",
"models",
"with",
"outputs",
"for",
"current",
"stage."
] | def build_model(self, stage_id) -> tf.keras.Model:
self._teacher_pretrainer.trainable = False
layer_wise_config = self._progressive_config.layer_wise_distill_config
freeze_previous_layers = layer_wise_config.if_freeze_previous_layers
student_encoder = self._student_pretrainer.encoder_network
if stag... | ['def', 'build_model(self,', 'stage_id)', '->', 'tf.keras.Model:', 'self._teacher_pretrainer.trainable', '=', 'False', 'layer_wise_config', '=', 'self._progressive_config.layer_wise_distill_config', 'freeze_previous_layers', '=', 'layer_wise_config.if_freeze_previous_layers', 'student_encoder', '=', 'self._student_pret... | 972,762 |
sek788432/Waymo-2D-Object-Detection | distillation.py | BertDistillationTask.build_losses | build_losses | Builds losses and update loss-related metrics for the current stage. | [
"Builds",
"losses",
"and",
"update",
"loss-related",
"metrics",
"for",
"the",
"current",
"stage."
] | def build_losses(self, labels, outputs, metrics) -> tf.Tensor:
last_stage = 'student_pretrainer_output' in outputs
if not last_stage:
distill_config = self._progressive_config.layer_wise_distill_config
teacher_feature = outputs['teacher_output_feature']
student_feature = outputs['student... | ['def', 'build_losses(self,', 'labels,', 'outputs,', 'metrics)', '->', 'tf.Tensor:', 'last_stage', '=', "'student_pretrainer_output'", 'in', 'outputs', 'if', 'not', 'last_stage:', 'distill_config', '=', 'self._progressive_config.layer_wise_distill_config', 'teacher_feature', '=', "outputs['teacher_output_feature']", 's... | 972,764 |
sek788432/Waymo-2D-Object-Detection | distillation.py | BertDistillationTask.cur_checkpoint_items | cur_checkpoint_items | Checkpoints for model, stage_id, optimizer for preemption handling. | [
"Checkpoints",
"for",
"model,",
"stage_id,",
"optimizer",
"for",
"preemption",
"handling."
] | def cur_checkpoint_items(self):
return dict(stage_id=self._stage_id, volatiles=self._volatiles, student_pretrainer=self._student_pretrainer, teacher_pretrainer=self._teacher_pretrainer, encoder=self._student_pretrainer.encoder_network) | ['def', 'cur_checkpoint_items(self):', 'return', 'dict(stage_id=self._stage_id,', 'volatiles=self._volatiles,', 'student_pretrainer=self._student_pretrainer,', 'teacher_pretrainer=self._teacher_pretrainer,', 'encoder=self._student_pretrainer.encoder_network)'] | 972,766 |
sek788432/Waymo-2D-Object-Detection | distillation.py | BertDistillationTask.initialize | initialize | Loads teacher's pretrained checkpoint and copy student's embedding. | [
"Loads",
"teacher's",
"pretrained",
"checkpoint",
"and",
"copy",
"student's",
"embedding."
] | def initialize(self, model):
del model
logging.info('Begin to load checkpoint for teacher pretrainer model.')
ckpt_dir_or_file = self._task_config.teacher_model_init_checkpoint
if not ckpt_dir_or_file:
raise ValueError('`teacher_model_init_checkpoint` is not specified.')
if tf.io.gfile.isdir... | ['def', 'initialize(self,', 'model):', 'del', 'model', "logging.info('Begin", 'to', 'load', 'checkpoint', 'for', 'teacher', 'pretrainer', "model.')", 'ckpt_dir_or_file', '=', 'self._task_config.teacher_model_init_checkpoint', 'if', 'not', 'ckpt_dir_or_file:', 'raise', "ValueError('`teacher_model_init_checkpoint`", 'is'... | 972,767 |
sek788432/Waymo-2D-Object-Detection | export_tfhub.py | create_mobilebert_model | create_mobilebert_model | Creates a model for exporting to tfhub. | [
"Creates",
"a",
"model",
"for",
"exporting",
"to",
"tfhub."
] | def create_mobilebert_model(bert_config):
pretrainer = model_utils.create_mobilebert_pretrainer(bert_config)
encoder = pretrainer.encoder_network
encoder_inputs_dict = {x.name: x for x in encoder.inputs}
encoder_output_dict = encoder(encoder_inputs_dict)
encoder_output_dict['default'] = encoder_outp... | ['def', 'create_mobilebert_model(bert_config):', 'pretrainer', '=', 'model_utils.create_mobilebert_pretrainer(bert_config)', 'encoder', '=', 'pretrainer.encoder_network', 'encoder_inputs_dict', '=', '{x.name:', 'x', 'for', 'x', 'in', 'encoder.inputs}', 'encoder_output_dict', '=', 'encoder(encoder_inputs_dict)', "encode... | 972,768 |
sek788432/Waymo-2D-Object-Detection | model_utils.py | create_mobilebert_pretrainer | create_mobilebert_pretrainer | Creates a BertPretrainerV2 that wraps MobileBERTEncoder model. | [
"Creates",
"a",
"BertPretrainerV2",
"that",
"wraps",
"MobileBERTEncoder",
"model."
] | def create_mobilebert_pretrainer(bert_config):
mobilebert_encoder = networks.MobileBERTEncoder(word_vocab_size=bert_config.vocab_size, word_embed_size=bert_config.embedding_size, type_vocab_size=bert_config.type_vocab_size, max_sequence_length=bert_config.max_position_embeddings, num_blocks=bert_config.num_hidden_l... | ['def', 'create_mobilebert_pretrainer(bert_config):', 'mobilebert_encoder', '=', 'networks.MobileBERTEncoder(word_vocab_size=bert_config.vocab_size,', 'word_embed_size=bert_config.embedding_size,', 'type_vocab_size=bert_config.type_vocab_size,', 'max_sequence_length=bert_config.max_position_embeddings,', 'num_blocks=be... | 972,770 |
sek788432/Waymo-2D-Object-Detection | run_distillation.py | config_override | config_override | Override ExperimentConfig according to flags. | [
"Override",
"ExperimentConfig",
"according",
"to",
"flags."
] | def config_override(params, flags_obj):
params.override({'runtime': {'tpu': flags_obj.tpu}})
for config_file in flags_obj.config_file or []:
params = hyperparams.override_params_dict(params, config_file, is_strict=True)
if flags_obj.params_override:
params = hyperparams.override_params_dict(... | ['def', 'config_override(params,', 'flags_obj):', "params.override({'runtime':", "{'tpu':", 'flags_obj.tpu}})', 'for', 'config_file', 'in', 'flags_obj.config_file', 'or', '[]:', 'params', '=', 'hyperparams.override_params_dict(params,', 'config_file,', 'is_strict=True)', 'if', 'flags_obj.params_override:', 'params', '=... | 972,775 |
sek788432/Waymo-2D-Object-Detection | dataset.py | BigBirdTriviaQAConfig.configure | configure | Configures additional user-specified arguments. | [
"Configures",
"additional",
"user-specified",
"arguments."
] | def configure(self, sentencepiece_model_path, sequence_length, stride, global_sequence_length=None):
self.sentencepiece_model_path = sentencepiece_model_path
self.sequence_length = sequence_length
self.stride = stride
if global_sequence_length is None and sequence_length is not None:
self.global... | ['def', 'configure(self,', 'sentencepiece_model_path,', 'sequence_length,', 'stride,', 'global_sequence_length=None):', 'self.sentencepiece_model_path', '=', 'sentencepiece_model_path', 'self.sequence_length', '=', 'sequence_length', 'self.stride', '=', 'stride', 'if', 'global_sequence_length', 'is', 'None', 'and', 'se... | 972,780 |
sek788432/Waymo-2D-Object-Detection | dataset.py | BigBirdTriviaQAConfig.validate | validate | Validates that user specifies valid arguments. | [
"Validates",
"that",
"user",
"specifies",
"valid",
"arguments."
] | def validate(self):
if self.sequence_length is None:
raise ValueError('sequence_length must be specified for BigBird.')
if self.stride is None:
raise ValueError('stride must be specified for BigBird.')
if self.sentencepiece_model_path is None:
raise ValueError('sentencepiece_model_pa... | ['def', 'validate(self):', 'if', 'self.sequence_length', 'is', 'None:', 'raise', "ValueError('sequence_length", 'must', 'be', 'specified', 'for', "BigBird.')", 'if', 'self.stride', 'is', 'None:', 'raise', "ValueError('stride", 'must', 'be', 'specified', 'for', "BigBird.')", 'if', 'self.sentencepiece_model_path', 'is', ... | 972,781 |
sek788432/Waymo-2D-Object-Detection | question_answering.py | QuestionAnsweringTask.set_preprocessed_eval_input_path | set_preprocessed_eval_input_path | Sets the path to the preprocessed eval data. | [
"Sets",
"the",
"path",
"to",
"the",
"preprocessed",
"eval",
"data."
] | def set_preprocessed_eval_input_path(self, eval_input_path):
self._tf_record_input_path = eval_input_path | ['def', 'set_preprocessed_eval_input_path(self,', 'eval_input_path):', 'self._tf_record_input_path', '=', 'eval_input_path'] | 972,799 |
sek788432/Waymo-2D-Object-Detection | translation.py | write_test_record | write_test_record | Writes the test input to a tfrecord. | [
"Writes",
"the",
"test",
"input",
"to",
"a",
"tfrecord."
] | def write_test_record(params, model_dir):
params = params.replace(transform_and_batch=False)
dataset = data_loader_factory.get_data_loader(params).load()
references = []
total_samples = 0
output_file = os.path.join(model_dir, 'eval.tf_record')
writer = tf.io.TFRecordWriter(output_file)
for d... | ['def', 'write_test_record(params,', 'model_dir):', 'params', '=', 'params.replace(transform_and_batch=False)', 'dataset', '=', 'data_loader_factory.get_data_loader(params).load()', 'references', '=', '[]', 'total_samples', '=', '0', 'output_file', '=', 'os.path.join(model_dir,', "'eval.tf_record')", 'writer', '=', 'tf... | 972,809 |
sek788432/Waymo-2D-Object-Detection | utils.py | get_encoder_from_hub | get_encoder_from_hub | Gets an encoder from hub. | [
"Gets",
"an",
"encoder",
"from",
"hub."
] | def get_encoder_from_hub(hub_model_path: str) -> tf.keras.Model:
input_word_ids = tf.keras.layers.Input(shape=(None,), dtype=tf.int32, name='input_word_ids')
input_mask = tf.keras.layers.Input(shape=(None,), dtype=tf.int32, name='input_mask')
input_type_ids = tf.keras.layers.Input(shape=(None,), dtype=tf.in... | ['def', 'get_encoder_from_hub(hub_model_path:', 'str)', '->', 'tf.keras.Model:', 'input_word_ids', '=', 'tf.keras.layers.Input(shape=(None,),', 'dtype=tf.int32,', "name='input_word_ids')", 'input_mask', '=', 'tf.keras.layers.Input(shape=(None,),', 'dtype=tf.int32,', "name='input_mask')", 'input_type_ids', '=', 'tf.kera... | 972,814 |
sek788432/Waymo-2D-Object-Detection | export_tfhub_lib_test.py | ExportPreprocessingTest.test_no_leaks | test_no_leaks | Tests not leaking the path to the original vocab file. | [
"Tests",
"not",
"leaking",
"the",
"path",
"to",
"the",
"original",
"vocab",
"file."
] | def test_no_leaks(self):
path = self._do_export(['d', 'ef', 'abc', 'xy'], do_lower_case=True, use_sp_model=False)
with tf.io.gfile.GFile(os.path.join(path, 'saved_model.pb'), 'rb') as f:
self.assertFalse(_STRING_NOT_TO_LEAK.encode('ascii') in f.read()) | ['def', 'test_no_leaks(self):', 'path', '=', "self._do_export(['d',", "'ef',", "'abc',", "'xy'],", 'do_lower_case=True,', 'use_sp_model=False)', 'with', 'tf.io.gfile.GFile(os.path.join(path,', "'saved_model.pb'),", "'rb')", 'as', 'f:', "self.assertFalse(_STRING_NOT_TO_LEAK.encode('ascii')", 'in', 'f.read())'] | 972,819 |
sek788432/Waymo-2D-Object-Detection | export_tfhub_lib_test.py | ExportPreprocessingTest.test_reexport | test_reexport | Test that preprocess keeps working after another save/load cycle. | [
"Test",
"that",
"preprocess",
"keeps",
"working",
"after",
"another",
"save/load",
"cycle."
] | def test_reexport(self, use_sp_model):
path1 = self._do_export(['d', 'ef', 'abc', 'xy'], do_lower_case=True, default_seq_length=10, tokenize_with_offsets=False, experimental_disable_assert=True, use_sp_model=use_sp_model)
path2 = path1.rstrip('/') + '.2'
model1 = tf.saved_model.load(path1)
tf.saved_mode... | ['def', 'test_reexport(self,', 'use_sp_model):', 'path1', '=', "self._do_export(['d',", "'ef',", "'abc',", "'xy'],", 'do_lower_case=True,', 'default_seq_length=10,', 'tokenize_with_offsets=False,', 'experimental_disable_assert=True,', 'use_sp_model=use_sp_model)', 'path2', '=', "path1.rstrip('/')", '+', "'.2'", 'model1... | 972,820 |
sek788432/Waymo-2D-Object-Detection | export_tfhub_lib_test.py | ExportPreprocessingTest.test_check_no_assert | test_check_no_assert | Tests the self-check during export without assertions. | [
"Tests",
"the",
"self-check",
"during",
"export",
"without",
"assertions."
] | def test_check_no_assert(self, use_sp_model):
preprocess_export_path = self._do_export(['d', 'ef', 'abc', 'xy'], do_lower_case=True, use_sp_model=use_sp_model, tokenize_with_offsets=False, experimental_disable_assert=False)
with self.assertRaisesRegex(AssertionError, 'failed to suppress \\d+ Assert ops'):
... | ['def', 'test_check_no_assert(self,', 'use_sp_model):', 'preprocess_export_path', '=', "self._do_export(['d',", "'ef',", "'abc',", "'xy'],", 'do_lower_case=True,', 'use_sp_model=use_sp_model,', 'tokenize_with_offsets=False,', 'experimental_disable_assert=False)', 'with', 'self.assertRaisesRegex(AssertionError,', "'fail... | 972,823 |
sek788432/Waymo-2D-Object-Detection | data_pipeline.py | DatasetManager.serialize | serialize | Convert NumPy arrays into a TFRecords entry. | [
"Convert",
"NumPy",
"arrays",
"into",
"a",
"TFRecords",
"entry."
] | def serialize(data):
def create_int_feature(values):
return tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
feature_dict = {k: create_int_feature(v.astype(np.int64)) for (k, v) in data.items()}
return tf.train.Example(features=tf.train.Features(feature=feature_dict)).SerializeTo... | ['def', 'serialize(data):', 'def', 'create_int_feature(values):', 'return', 'tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))', 'feature_dict', '=', '{k:', 'create_int_feature(v.astype(np.int64))', 'for', '(k,', 'v)', 'in', 'data.items()}', 'return', 'tf.train.Example(features=tf.train.Features(featu... | 972,947 |
sek788432/Waymo-2D-Object-Detection | common.py | define_flags | define_flags | Defines flags for training the Ranking model. | [
"Defines",
"flags",
"for",
"training",
"the",
"Ranking",
"model."
] | def define_flags() -> None:
tfm_flags.define_flags()
FLAGS.set_default(name='experiment', value='dlrm_criteo')
FLAGS.set_default(name='mode', value='train_and_eval')
flags.DEFINE_integer(name='seed', default=None, help='This value will be used to seed both NumPy and TensorFlow.')
flags.DEFINE_string... | ['def', 'define_flags()', '->', 'None:', 'tfm_flags.define_flags()', "FLAGS.set_default(name='experiment',", "value='dlrm_criteo')", "FLAGS.set_default(name='mode',", "value='train_and_eval')", "flags.DEFINE_integer(name='seed',", 'default=None,', "help='This", 'value', 'will', 'be', 'used', 'to', 'seed', 'both', 'NumP... | 972,977 |
sek788432/Waymo-2D-Object-Detection | data_pipeline.py | train_input_fn | train_input_fn | Returns callable object of batched training examples. | [
"Returns",
"callable",
"object",
"of",
"batched",
"training",
"examples."
] | def train_input_fn(params: config.Task) -> CriteoTsvReader:
return CriteoTsvReader(file_pattern=params.train_data.input_path, params=params.train_data, vocab_sizes=params.model.vocab_sizes, num_dense_features=params.model.num_dense_features, use_synthetic_data=params.use_synthetic_data) | ['def', 'train_input_fn(params:', 'config.Task)', '->', 'CriteoTsvReader:', 'return', 'CriteoTsvReader(file_pattern=params.train_data.input_path,', 'params=params.train_data,', 'vocab_sizes=params.model.vocab_sizes,', 'num_dense_features=params.model.num_dense_features,', 'use_synthetic_data=params.use_synthetic_data)'... | 972,978 |
sek788432/Waymo-2D-Object-Detection | data_pipeline.py | eval_input_fn | eval_input_fn | Returns callable object of batched eval examples. | [
"Returns",
"callable",
"object",
"of",
"batched",
"eval",
"examples."
] | def eval_input_fn(params: config.Task) -> CriteoTsvReader:
return CriteoTsvReader(file_pattern=params.validation_data.input_path, params=params.validation_data, vocab_sizes=params.model.vocab_sizes, num_dense_features=params.model.num_dense_features, use_synthetic_data=params.use_synthetic_data) | ['def', 'eval_input_fn(params:', 'config.Task)', '->', 'CriteoTsvReader:', 'return', 'CriteoTsvReader(file_pattern=params.validation_data.input_path,', 'params=params.validation_data,', 'vocab_sizes=params.model.vocab_sizes,', 'num_dense_features=params.model.num_dense_features,', 'use_synthetic_data=params.use_synthet... | 972,979 |
sek788432/Waymo-2D-Object-Detection | keras_utils.py | TimeHistory.global_steps | global_steps | The current 1-indexed global step. | [
"The",
"current",
"1-indexed",
"global",
"step."
] | def global_steps(self):
return self.steps_before_epoch + self.steps_in_epoch | ['def', 'global_steps(self):', 'return', 'self.steps_before_epoch', '+', 'self.steps_in_epoch'] | 973,004 |
sek788432/Waymo-2D-Object-Detection | keras_utils.py | TimeHistory.get_examples_per_sec | get_examples_per_sec | Calculates examples/sec through timestamp_log and skip warmup period. | [
"Calculates",
"examples/sec",
"through",
"timestamp_log",
"and",
"skip",
"warmup",
"period."
] | def get_examples_per_sec(self, warmup=1):
time_log = self.timestamp_log
seconds = time_log[-1].timestamp - time_log[warmup].timestamp
steps = time_log[-1].batch_index - time_log[warmup].batch_index
return self.batch_size * steps / seconds | ['def', 'get_examples_per_sec(self,', 'warmup=1):', 'time_log', '=', 'self.timestamp_log', 'seconds', '=', 'time_log[-1].timestamp', '-', 'time_log[warmup].timestamp', 'steps', '=', 'time_log[-1].batch_index', '-', 'time_log[warmup].batch_index', 'return', 'self.batch_size', '*', 'steps', '/', 'seconds'] | 973,007 |
sek788432/Waymo-2D-Object-Detection | train_spatial_partitioning.py | get_computation_shape_for_model_parallelism | get_computation_shape_for_model_parallelism | Return computation shape to be used for TPUStrategy spatial partition. | [
"Return",
"computation",
"shape",
"to",
"be",
"used",
"for",
"TPUStrategy",
"spatial",
"partition."
] | def get_computation_shape_for_model_parallelism(input_partition_dims):
num_logical_devices = np.prod(input_partition_dims)
if num_logical_devices == 1:
return [1, 1, 1, 1]
if num_logical_devices == 2:
return [1, 1, 1, 2]
if num_logical_devices == 4:
return [1, 2, 1, 2]
if num... | ['def', 'get_computation_shape_for_model_parallelism(input_partition_dims):', 'num_logical_devices', '=', 'np.prod(input_partition_dims)', 'if', 'num_logical_devices', '==', '1:', 'return', '[1,', '1,', '1,', '1]', 'if', 'num_logical_devices', '==', '2:', 'return', '[1,', '1,', '1,', '2]', 'if', 'num_logical_devices', ... | 973,015 |
sek788432/Waymo-2D-Object-Detection | train_spatial_partitioning.py | create_distribution_strategy | create_distribution_strategy | Creates distribution strategy to use for computation. | [
"Creates",
"distribution",
"strategy",
"to",
"use",
"for",
"computation."
] | def create_distribution_strategy(distribution_strategy, tpu_address, input_partition_dims=None, num_gpus=None):
if input_partition_dims is not None:
if distribution_strategy != 'tpu':
raise ValueError('Spatial partitioning is only supported for TPUStrategy.')
resolver = tf.distribute.clu... | ['def', 'create_distribution_strategy(distribution_strategy,', 'tpu_address,', 'input_partition_dims=None,', 'num_gpus=None):', 'if', 'input_partition_dims', 'is', 'not', 'None:', 'if', 'distribution_strategy', '!=', "'tpu':", 'raise', "ValueError('Spatial", 'partitioning', 'is', 'only', 'supported', 'for', "TPUStrateg... | 973,016 |
sek788432/Waymo-2D-Object-Detection | maskrcnn.py | cascadercnn_spinenet_coco | cascadercnn_spinenet_coco | COCO object detection with Cascade R-CNN with SpineNet backbone. | [
"COCO",
"object",
"detection",
"with",
"Cascade",
"R-CNN",
"with",
"SpineNet",
"backbone."
] | def cascadercnn_spinenet_coco() -> cfg.ExperimentConfig:
steps_per_epoch = 463
coco_val_samples = 5000
train_batch_size = 256
eval_batch_size = 8
config = cfg.ExperimentConfig(runtime=cfg.RuntimeConfig(mixed_precision_dtype='bfloat16'), task=MaskRCNNTask(annotation_file=os.path.join(COCO_INPUT_PATH_... | ['def', 'cascadercnn_spinenet_coco()', '->', 'cfg.ExperimentConfig:', 'steps_per_epoch', '=', '463', 'coco_val_samples', '=', '5000', 'train_batch_size', '=', '256', 'eval_batch_size', '=', '8', 'config', '=', "cfg.ExperimentConfig(runtime=cfg.RuntimeConfig(mixed_precision_dtype='bfloat16'),", 'task=MaskRCNNTask(annota... | 973,024 |
sek788432/Waymo-2D-Object-Detection | semantic_segmentation.py | seg_deeplabv3_pascal | seg_deeplabv3_pascal | Image segmentation on imagenet with resnet deeplabv3. | [
"Image",
"segmentation",
"on",
"imagenet",
"with",
"resnet",
"deeplabv3."
] | def seg_deeplabv3_pascal() -> cfg.ExperimentConfig:
train_batch_size = 16
eval_batch_size = 8
steps_per_epoch = PASCAL_TRAIN_EXAMPLES // train_batch_size
output_stride = 16
aspp_dilation_rates = [12, 24, 36]
multigrid = [1, 2, 4]
stem_type = 'v1'
level = int(np.math.log2(output_stride))
... | ['def', 'seg_deeplabv3_pascal()', '->', 'cfg.ExperimentConfig:', 'train_batch_size', '=', '16', 'eval_batch_size', '=', '8', 'steps_per_epoch', '=', 'PASCAL_TRAIN_EXAMPLES', '//', 'train_batch_size', 'output_stride', '=', '16', 'aspp_dilation_rates', '=', '[12,', '24,', '36]', 'multigrid', '=', '[1,', '2,', '4]', 'stem... | 973,028 |
sek788432/Waymo-2D-Object-Detection | video_classification.py | video_classification_ucf101 | video_classification_ucf101 | Video classification on UCF-101 with resnet. | [
"Video",
"classification",
"on",
"UCF-101",
"with",
"resnet."
] | def video_classification_ucf101() -> cfg.ExperimentConfig:
train_dataset = DataConfig(name='ucf101', num_classes=101, is_training=True, split='train', drop_remainder=True, num_examples=9537, temporal_stride=2, feature_shape=(32, 224, 224, 3))
train_dataset.tfds_name = 'ucf101'
train_dataset.tfds_split = 'tr... | ['def', 'video_classification_ucf101()', '->', 'cfg.ExperimentConfig:', 'train_dataset', '=', "DataConfig(name='ucf101',", 'num_classes=101,', 'is_training=True,', "split='train',", 'drop_remainder=True,', 'num_examples=9537,', 'temporal_stride=2,', 'feature_shape=(32,', '224,', '224,', '3))', 'train_dataset.tfds_name'... | 973,037 |
sek788432/Waymo-2D-Object-Detection | video_classification.py | video_classification_kinetics700_2020 | video_classification_kinetics700_2020 | Video classification on Kinectics 700 2020 with resnet. | [
"Video",
"classification",
"on",
"Kinectics",
"700",
"2020",
"with",
"resnet."
] | def video_classification_kinetics700_2020() -> cfg.ExperimentConfig:
train_dataset = kinetics700_2020(is_training=True)
validation_dataset = kinetics700_2020(is_training=False)
task = VideoClassificationTask(model=VideoClassificationModel(backbone=backbones_3d.Backbone3D(type='resnet_3d', resnet_3d=backbone... | ['def', 'video_classification_kinetics700_2020()', '->', 'cfg.ExperimentConfig:', 'train_dataset', '=', 'kinetics700_2020(is_training=True)', 'validation_dataset', '=', 'kinetics700_2020(is_training=False)', 'task', '=', "VideoClassificationTask(model=VideoClassificationModel(backbone=backbones_3d.Backbone3D(type='resn... | 973,041 |
sek788432/Waymo-2D-Object-Detection | tfrecord_lib.py | image_info_to_feature_dict | image_info_to_feature_dict | Convert image information to a dict of features. | [
"Convert",
"image",
"information",
"to",
"a",
"dict",
"of",
"features."
] | def image_info_to_feature_dict(height, width, filename, image_id, encoded_str, encoded_format):
key = hashlib.sha256(encoded_str).hexdigest()
return {'image/height': convert_to_feature(height), 'image/width': convert_to_feature(width), 'image/filename': convert_to_feature(filename.encode('utf8')), 'image/source... | ['def', 'image_info_to_feature_dict(height,', 'width,', 'filename,', 'image_id,', 'encoded_str,', 'encoded_format):', 'key', '=', 'hashlib.sha256(encoded_str).hexdigest()', 'return', "{'image/height':", 'convert_to_feature(height),', "'image/width':", 'convert_to_feature(width),', "'image/filename':", "convert_to_featu... | 973,048 |
sek788432/Waymo-2D-Object-Detection | tfrecord_lib.py | check_and_make_dir | check_and_make_dir | Creates the directory if it doesn't exist. | [
"Creates",
"the",
"directory",
"if",
"it",
"doesn't",
"exist."
] | def check_and_make_dir(directory):
if not tf.io.gfile.isdir(directory):
tf.io.gfile.makedirs(directory) | ['def', 'check_and_make_dir(directory):', 'if', 'not', 'tf.io.gfile.isdir(directory):', 'tf.io.gfile.makedirs(directory)'] | 973,050 |
sek788432/Waymo-2D-Object-Detection | input_reader_factory.py | input_reader_generator | input_reader_generator | Instantiates an input reader class according to the params. | [
"Instantiates",
"an",
"input",
"reader",
"class",
"according",
"to",
"the",
"params."
] | def input_reader_generator(params: cfg.DataConfig, **kwargs) -> core_input_reader.InputReader:
if params.is_training and params.get('pseudo_label_data', False):
return vision_input_reader.CombinationDatasetInputReader(params, pseudo_label_dataset_fn=dataset_fn_util.pick_dataset_fn(params.pseudo_label_data.f... | ['def', 'input_reader_generator(params:', 'cfg.DataConfig,', '**kwargs)', '->', 'core_input_reader.InputReader:', 'if', 'params.is_training', 'and', "params.get('pseudo_label_data',", 'False):', 'return', 'vision_input_reader.CombinationDatasetInputReader(params,', 'pseudo_label_dataset_fn=dataset_fn_util.pick_dataset_... | 973,054 |
sek788432/Waymo-2D-Object-Detection | tfexample_utils.py | make_image_bytes | make_image_bytes | Generates image and return bytes in JPEG format. | [
"Generates",
"image",
"and",
"return",
"bytes",
"in",
"JPEG",
"format."
] | def make_image_bytes(shape: Sequence[int]):
random_image = np.random.randint(0, 256, size=shape, dtype=np.uint8)
random_image = Image.fromarray(random_image)
with io.BytesIO() as buffer:
random_image.save(buffer, format='JPEG')
raw_image_bytes = buffer.getvalue()
return raw_image_bytes | ['def', 'make_image_bytes(shape:', 'Sequence[int]):', 'random_image', '=', 'np.random.randint(0,', '256,', 'size=shape,', 'dtype=np.uint8)', 'random_image', '=', 'Image.fromarray(random_image)', 'with', 'io.BytesIO()', 'as', 'buffer:', 'random_image.save(buffer,', "format='JPEG')", 'raw_image_bytes', '=', 'buffer.getva... | 973,057 |
sek788432/Waymo-2D-Object-Detection | tfexample_utils.py | put_int64_to_context | put_int64_to_context | Puts int64 to SequenceExample context with key. | [
"Puts",
"int64",
"to",
"SequenceExample",
"context",
"with",
"key."
] | def put_int64_to_context(seq_example: tf.train.SequenceExample, label: int=0, key: str=LABEL_KEY):
seq_example.context.feature[key].int64_list.value[:] = [label] | ['def', 'put_int64_to_context(seq_example:', 'tf.train.SequenceExample,', 'label:', 'int=0,', 'key:', 'str=LABEL_KEY):', 'seq_example.context.feature[key].int64_list.value[:]', '=', '[label]'] | 973,058 |
sek788432/Waymo-2D-Object-Detection | tfexample_utils.py | put_float_list_to_feature | put_float_list_to_feature | Puts float list to SequenceExample context with key. | [
"Puts",
"float",
"list",
"to",
"SequenceExample",
"context",
"with",
"key."
] | def put_float_list_to_feature(seq_example: tf.train.SequenceExample, value: Sequence[Sequence[float]], key: str):
for s in value:
seq_example.feature_lists.feature_list.get_or_create(key).feature.add().float_list.value[:] = s | ['def', 'put_float_list_to_feature(seq_example:', 'tf.train.SequenceExample,', 'value:', 'Sequence[Sequence[float]],', 'key:', 'str):', 'for', 's', 'in', 'value:', 'seq_example.feature_lists.feature_list.get_or_create(key).feature.add().float_list.value[:]', '=', 's'] | 973,060 |
sek788432/Waymo-2D-Object-Detection | video_input.py | process_image | process_image | Processes a serialized image tensor. | [
"Processes",
"a",
"serialized",
"image",
"tensor."
] | def process_image(image: tf.Tensor, is_training: bool=True, num_frames: int=32, stride: int=1, random_stride_range: int=0, num_test_clips: int=1, min_resize: int=256, crop_size: int=224, num_crops: int=1, zero_centering_image: bool=False, min_aspect_ratio: float=0.5, max_aspect_ratio: float=2, min_area_ratio: float=0.4... | ['def', 'process_image(image:', 'tf.Tensor,', 'is_training:', 'bool=True,', 'num_frames:', 'int=32,', 'stride:', 'int=1,', 'random_stride_range:', 'int=0,', 'num_test_clips:', 'int=1,', 'min_resize:', 'int=256,', 'crop_size:', 'int=224,', 'num_crops:', 'int=1,', 'zero_centering_image:', 'bool=False,', 'min_aspect_ratio... | 973,067 |
sek788432/Waymo-2D-Object-Detection | segmentation_model_test.py | SegmentationNetworkTest.test_segmentation_network_creation | test_segmentation_network_creation | Test for creation of a segmentation network. | [
"Test",
"for",
"creation",
"of",
"a",
"segmentation",
"network."
] | def test_segmentation_network_creation(self, input_size, level):
num_classes = 10
inputs = np.random.rand(2, input_size, input_size, 3)
tf.keras.backend.set_image_data_format('channels_last')
backbone = backbones.ResNet(model_id=50)
decoder = fpn.FPN(input_specs=backbone.output_specs, min_level=2, m... | ['def', 'test_segmentation_network_creation(self,', 'input_size,', 'level):', 'num_classes', '=', '10', 'inputs', '=', 'np.random.rand(2,', 'input_size,', 'input_size,', '3)', "tf.keras.backend.set_image_data_format('channels_last')", 'backbone', '=', 'backbones.ResNet(model_id=50)', 'decoder', '=', 'fpn.FPN(input_spec... | 973,100 |
sek788432/Waymo-2D-Object-Detection | efficientnet.py | block_spec_decoder | block_spec_decoder | Decodes and returns specs for a block. | [
"Decodes",
"and",
"returns",
"specs",
"for",
"a",
"block."
] | def block_spec_decoder(specs: List[Tuple[Any, ...]], width_scale: float, depth_scale: float) -> List[BlockSpec]:
decoded_specs = []
for s in specs:
s = s + (width_scale, depth_scale)
decoded_specs.append(BlockSpec(*s))
return decoded_specs | ['def', 'block_spec_decoder(specs:', 'List[Tuple[Any,', '...]],', 'width_scale:', 'float,', 'depth_scale:', 'float)', '->', 'List[BlockSpec]:', 'decoded_specs', '=', '[]', 'for', 's', 'in', 'specs:', 's', '=', 's', '+', '(width_scale,', 'depth_scale)', 'decoded_specs.append(BlockSpec(*s))', 'return', 'decoded_specs'] | 973,106 |
sek788432/Waymo-2D-Object-Detection | efficientnet.py | build_efficientnet | build_efficientnet | Builds EfficientNet backbone from a config. | [
"Builds",
"EfficientNet",
"backbone",
"from",
"a",
"config."
] | def build_efficientnet(input_specs: tf.keras.layers.InputSpec, backbone_config: hyperparams.Config, norm_activation_config: hyperparams.Config, l2_regularizer: tf.keras.regularizers.Regularizer=None) -> tf.keras.Model:
backbone_type = backbone_config.type
backbone_cfg = backbone_config.get()
assert backbone... | ['def', 'build_efficientnet(input_specs:', 'tf.keras.layers.InputSpec,', 'backbone_config:', 'hyperparams.Config,', 'norm_activation_config:', 'hyperparams.Config,', 'l2_regularizer:', 'tf.keras.regularizers.Regularizer=None)', '->', 'tf.keras.Model:', 'backbone_type', '=', 'backbone_config.type', 'backbone_cfg', '=', ... | 973,107 |
sek788432/Waymo-2D-Object-Detection | factory_test.py | FactoryTest.test_revnet_creation | test_revnet_creation | Test creation of RevNet models. | [
"Test",
"creation",
"of",
"RevNet",
"models."
] | def test_revnet_creation(self, model_id):
network = backbones.RevNet(model_id=model_id, norm_momentum=0.99, norm_epsilon=1e-05)
backbone_config = backbones_cfg.Backbone(type='revnet', revnet=backbones_cfg.RevNet(model_id=model_id))
norm_activation_config = common_cfg.NormActivation(norm_momentum=0.99, norm_... | ['def', 'test_revnet_creation(self,', 'model_id):', 'network', '=', 'backbones.RevNet(model_id=model_id,', 'norm_momentum=0.99,', 'norm_epsilon=1e-05)', 'backbone_config', '=', "backbones_cfg.Backbone(type='revnet',", 'revnet=backbones_cfg.RevNet(model_id=model_id))', 'norm_activation_config', '=', 'common_cfg.NormActi... | 973,117 |
sek788432/Waymo-2D-Object-Detection | mobilenet.py | block_spec_decoder | block_spec_decoder | Decodes specs for a block. | [
"Decodes",
"specs",
"for",
"a",
"block."
] | def block_spec_decoder(specs: Dict[Any, Any], filter_size_scale: float, divisible_by: int=8, finegrain_classification_mode: bool=True):
spec_name = specs['spec_name']
block_spec_schema = specs['block_spec_schema']
block_specs = specs['block_specs']
if not block_specs:
raise ValueError('The block... | ['def', 'block_spec_decoder(specs:', 'Dict[Any,', 'Any],', 'filter_size_scale:', 'float,', 'divisible_by:', 'int=8,', 'finegrain_classification_mode:', 'bool=True):', 'spec_name', '=', "specs['spec_name']", 'block_spec_schema', '=', "specs['block_spec_schema']", 'block_specs', '=', "specs['block_specs']", 'if', 'not', ... | 973,119 |
sek788432/Waymo-2D-Object-Detection | mobilenet.py | build_mobilenet | build_mobilenet | Builds MobileNet backbone from a config. | [
"Builds",
"MobileNet",
"backbone",
"from",
"a",
"config."
] | def build_mobilenet(input_specs: tf.keras.layers.InputSpec, backbone_config: hyperparams.Config, norm_activation_config: hyperparams.Config, l2_regularizer: Optional[tf.keras.regularizers.Regularizer]=None) -> tf.keras.Model:
backbone_type = backbone_config.type
backbone_cfg = backbone_config.get()
assert b... | ['def', 'build_mobilenet(input_specs:', 'tf.keras.layers.InputSpec,', 'backbone_config:', 'hyperparams.Config,', 'norm_activation_config:', 'hyperparams.Config,', 'l2_regularizer:', 'Optional[tf.keras.regularizers.Regularizer]=None)', '->', 'tf.keras.Model:', 'backbone_type', '=', 'backbone_config.type', 'backbone_cfg'... | 973,120 |
sek788432/Waymo-2D-Object-Detection | resnet_3d.py | build_resnet3d_rs | build_resnet3d_rs | Builds ResNet-3D-RS backbone from a config. | [
"Builds",
"ResNet-3D-RS",
"backbone",
"from",
"a",
"config."
] | def build_resnet3d_rs(input_specs: tf.keras.layers.InputSpec, backbone_config: hyperparams.Config, norm_activation_config: hyperparams.Config, l2_regularizer: Optional[tf.keras.regularizers.Regularizer]=None) -> tf.keras.Model:
backbone_cfg = backbone_config.get()
temporal_strides = []
temporal_kernel_sizes... | ['def', 'build_resnet3d_rs(input_specs:', 'tf.keras.layers.InputSpec,', 'backbone_config:', 'hyperparams.Config,', 'norm_activation_config:', 'hyperparams.Config,', 'l2_regularizer:', 'Optional[tf.keras.regularizers.Regularizer]=None)', '->', 'tf.keras.Model:', 'backbone_cfg', '=', 'backbone_config.get()', 'temporal_st... | 973,128 |
sek788432/Waymo-2D-Object-Detection | resnet_deeplab_test.py | ResNetTest.test_network_features | test_network_features | Test additional features of ResNet models. | [
"Test",
"additional",
"features",
"of",
"ResNet",
"models."
] | def test_network_features(self, stem_type, se_ratio, init_stochastic_depth_rate):
input_size = 128
model_id = 50
endpoint_filter_scale = 4
output_stride = 8
tf.keras.backend.set_image_data_format('channels_last')
network = resnet_deeplab.DilatedResNet(model_id=model_id, output_stride=output_stri... | ['def', 'test_network_features(self,', 'stem_type,', 'se_ratio,', 'init_stochastic_depth_rate):', 'input_size', '=', '128', 'model_id', '=', '50', 'endpoint_filter_scale', '=', '4', 'output_stride', '=', '8', "tf.keras.backend.set_image_data_format('channels_last')", 'network', '=', 'resnet_deeplab.DilatedResNet(model_... | 973,134 |
sek788432/Waymo-2D-Object-Detection | revnet.py | build_revnet | build_revnet | Builds RevNet backbone from a config. | [
"Builds",
"RevNet",
"backbone",
"from",
"a",
"config."
] | def build_revnet(input_specs: tf.keras.layers.InputSpec, backbone_config: hyperparams.Config, norm_activation_config: hyperparams.Config, l2_regularizer: tf.keras.regularizers.Regularizer=None) -> tf.keras.Model:
backbone_type = backbone_config.type
backbone_cfg = backbone_config.get()
assert backbone_type ... | ['def', 'build_revnet(input_specs:', 'tf.keras.layers.InputSpec,', 'backbone_config:', 'hyperparams.Config,', 'norm_activation_config:', 'hyperparams.Config,', 'l2_regularizer:', 'tf.keras.regularizers.Regularizer=None)', '->', 'tf.keras.Model:', 'backbone_type', '=', 'backbone_config.type', 'backbone_cfg', '=', 'backb... | 973,141 |
sek788432/Waymo-2D-Object-Detection | spinenet.py | build_spinenet | build_spinenet | Builds SpineNet backbone from a config. | [
"Builds",
"SpineNet",
"backbone",
"from",
"a",
"config."
] | def build_spinenet(input_specs: tf.keras.layers.InputSpec, backbone_config: hyperparams.Config, norm_activation_config: hyperparams.Config, l2_regularizer: tf.keras.regularizers.Regularizer=None) -> tf.keras.Model:
backbone_type = backbone_config.type
backbone_cfg = backbone_config.get()
assert backbone_typ... | ['def', 'build_spinenet(input_specs:', 'tf.keras.layers.InputSpec,', 'backbone_config:', 'hyperparams.Config,', 'norm_activation_config:', 'hyperparams.Config,', 'l2_regularizer:', 'tf.keras.regularizers.Regularizer=None)', '->', 'tf.keras.Model:', 'backbone_type', '=', 'backbone_config.type', 'backbone_cfg', '=', 'bac... | 973,146 |
sek788432/Waymo-2D-Object-Detection | nasfpn.py | build_block_specs | build_block_specs | Builds the list of BlockSpec objects for NAS-FPN. | [
"Builds",
"the",
"list",
"of",
"BlockSpec",
"objects",
"for",
"NAS-FPN."
] | def build_block_specs(block_specs: Optional[List[Tuple[Any, ...]]]=None) -> List[BlockSpec]:
if not block_specs:
block_specs = NASFPN_BLOCK_SPECS
logging.info('Building NAS-FPN block specs: %s', block_specs)
return [BlockSpec(*b) for b in block_specs] | ['def', 'build_block_specs(block_specs:', 'Optional[List[Tuple[Any,', '...]]]=None)', '->', 'List[BlockSpec]:', 'if', 'not', 'block_specs:', 'block_specs', '=', 'NASFPN_BLOCK_SPECS', "logging.info('Building", 'NAS-FPN', 'block', 'specs:', "%s',", 'block_specs)', 'return', '[BlockSpec(*b)', 'for', 'b', 'in', 'block_spec... | 973,159 |
sek788432/Waymo-2D-Object-Detection | nasfpn_test.py | NASFPNTest.test_network_creation | test_network_creation | Test creation of NAS-FPN. | [
"Test",
"creation",
"of",
"NAS-FPN."
] | def test_network_creation(self, input_size, min_level, max_level, use_separable_conv):
tf.keras.backend.set_image_data_format('channels_last')
inputs = tf.keras.Input(shape=(input_size, input_size, 3), batch_size=1)
num_filters = 256
backbone = resnet.ResNet(model_id=50)
network = nasfpn.NASFPN(inpu... | ['def', 'test_network_creation(self,', 'input_size,', 'min_level,', 'max_level,', 'use_separable_conv):', "tf.keras.backend.set_image_data_format('channels_last')", 'inputs', '=', 'tf.keras.Input(shape=(input_size,', 'input_size,', '3),', 'batch_size=1)', 'num_filters', '=', '256', 'backbone', '=', 'resnet.ResNet(model... | 973,161 |
sek788432/Waymo-2D-Object-Detection | dense_prediction_heads.py | RPNHead.call | call | Forward pass of the RPN head. | [
"Forward",
"pass",
"of",
"the",
"RPN",
"head."
] | def call(self, features: Mapping[str, tf.Tensor]):
scores = {}
boxes = {}
for (i, level) in enumerate(range(self._config_dict['min_level'], self._config_dict['max_level'] + 1)):
x = features[str(level)]
for (conv, norm) in zip(self._convs, self._norms[i]):
x = conv(x)
... | ['def', 'call(self,', 'features:', 'Mapping[str,', 'tf.Tensor]):', 'scores', '=', '{}', 'boxes', '=', '{}', 'for', '(i,', 'level)', 'in', "enumerate(range(self._config_dict['min_level'],", "self._config_dict['max_level']", '+', '1)):', 'x', '=', 'features[str(level)]', 'for', '(conv,', 'norm)', 'in', 'zip(self._convs,'... | 973,165 |
sek788432/Waymo-2D-Object-Detection | nn_layers.py | round_filters | round_filters | Rounds number of filters based on width multiplier. | [
"Rounds",
"number",
"of",
"filters",
"based",
"on",
"width",
"multiplier."
] | def round_filters(filters: int, multiplier: float, divisor: int=8, min_depth: Optional[int]=None, skip: bool=False):
orig_f = filters
if skip or not multiplier:
return filters
new_filters = make_divisible(value=filters * multiplier, divisor=divisor, min_value=min_depth)
logging.info('round_filte... | ['def', 'round_filters(filters:', 'int,', 'multiplier:', 'float,', 'divisor:', 'int=8,', 'min_depth:', 'Optional[int]=None,', 'skip:', 'bool=False):', 'orig_f', '=', 'filters', 'if', 'skip', 'or', 'not', 'multiplier:', 'return', 'filters', 'new_filters', '=', 'make_divisible(value=filters', '*', 'multiplier,', 'divisor... | 973,176 |
sek788432/Waymo-2D-Object-Detection | nn_layers.py | pyramid_feature_fusion | pyramid_feature_fusion | Fuses all feature maps in the feature pyramid at the target level. | [
"Fuses",
"all",
"feature",
"maps",
"in",
"the",
"feature",
"pyramid",
"at",
"the",
"target",
"level."
] | def pyramid_feature_fusion(inputs, target_level):
pyramid_feats = {int(k): v for (k, v) in inputs.items()}
min_level = min(pyramid_feats.keys())
max_level = max(pyramid_feats.keys())
resampled_feats = []
for l in range(min_level, max_level + 1):
if l == target_level:
resampled_fe... | ['def', 'pyramid_feature_fusion(inputs,', 'target_level):', 'pyramid_feats', '=', '{int(k):', 'v', 'for', '(k,', 'v)', 'in', 'inputs.items()}', 'min_level', '=', 'min(pyramid_feats.keys())', 'max_level', '=', 'max(pyramid_feats.keys())', 'resampled_feats', '=', '[]', 'for', 'l', 'in', 'range(min_level,', 'max_level', '... | 973,178 |
sek788432/Waymo-2D-Object-Detection | anchor.py | build_anchor_generator | build_anchor_generator | Build anchor generator from levels. | [
"Build",
"anchor",
"generator",
"from",
"levels."
] | def build_anchor_generator(min_level, max_level, num_scales, aspect_ratios, anchor_size):
anchor_sizes = collections.OrderedDict()
strides = collections.OrderedDict()
scales = []
for scale in range(num_scales):
scales.append(2 ** (scale / float(num_scales)))
for level in range(min_level, max... | ['def', 'build_anchor_generator(min_level,', 'max_level,', 'num_scales,', 'aspect_ratios,', 'anchor_size):', 'anchor_sizes', '=', 'collections.OrderedDict()', 'strides', '=', 'collections.OrderedDict()', 'scales', '=', '[]', 'for', 'scale', 'in', 'range(num_scales):', 'scales.append(2', '**', '(scale', '/', 'float(num_... | 973,197 |
sek788432/Waymo-2D-Object-Detection | augment.py | from_4d | from_4d | Converts a 4D image back to `ndims` rank. | [
"Converts",
"a",
"4D",
"image",
"back",
"to",
"`ndims`",
"rank."
] | def from_4d(image: tf.Tensor, ndims: tf.Tensor) -> tf.Tensor:
shape = tf.shape(image)
begin = tf.cast(tf.less_equal(ndims, 3), dtype=tf.int32)
end = 4 - tf.cast(tf.equal(ndims, 2), dtype=tf.int32)
new_shape = shape[begin:end]
return tf.reshape(image, new_shape) | ['def', 'from_4d(image:', 'tf.Tensor,', 'ndims:', 'tf.Tensor)', '->', 'tf.Tensor:', 'shape', '=', 'tf.shape(image)', 'begin', '=', 'tf.cast(tf.less_equal(ndims,', '3),', 'dtype=tf.int32)', 'end', '=', '4', '-', 'tf.cast(tf.equal(ndims,', '2),', 'dtype=tf.int32)', 'new_shape', '=', 'shape[begin:end]', 'return', 'tf.resh... | 973,203 |
sek788432/Waymo-2D-Object-Detection | augment.py | AutoAugment.policy_simple | policy_simple | Same as `policy_v0`, except with custom ops removed. | [
"Same",
"as",
"`policy_v0`,",
"except",
"with",
"custom",
"ops",
"removed."
] | def policy_simple():
policy = [[('Color', 0.4, 9), ('Equalize', 0.6, 3)], [('Solarize', 0.8, 3), ('Equalize', 0.4, 7)], [('Solarize', 0.4, 2), ('Solarize', 0.6, 2)], [('Color', 0.2, 0), ('Equalize', 0.8, 8)], [('Equalize', 0.4, 8), ('SolarizeAdd', 0.8, 3)], [('Color', 0.6, 1), ('Equalize', 1.0, 2)], [('Color', 0.4,... | ['def', 'policy_simple():', 'policy', '=', "[[('Color',", '0.4,', '9),', "('Equalize',", '0.6,', '3)],', "[('Solarize',", '0.8,', '3),', "('Equalize',", '0.4,', '7)],', "[('Solarize',", '0.4,', '2),', "('Solarize',", '0.6,', '2)],', "[('Color',", '0.2,', '0),', "('Equalize',", '0.8,', '8)],', "[('Equalize',", '0.4,', '... | 973,235 |
sek788432/Waymo-2D-Object-Detection | augment_test.py | AutoaugmentTest.test_autoaugment_video | test_autoaugment_video | Smoke test with video to be sure there are no syntax errors. | [
"Smoke",
"test",
"with",
"video",
"to",
"be",
"sure",
"there",
"are",
"no",
"syntax",
"errors."
] | def test_autoaugment_video(self):
image = tf.zeros((2, 224, 224, 3), dtype=tf.uint8)
for policy in self.AVAILABLE_POLICIES:
augmenter = augment.AutoAugment(augmentation_name=policy)
aug_image = augmenter.distort(image)
self.assertEqual((2, 224, 224, 3), aug_image.shape) | ['def', 'test_autoaugment_video(self):', 'image', '=', 'tf.zeros((2,', '224,', '224,', '3),', 'dtype=tf.uint8)', 'for', 'policy', 'in', 'self.AVAILABLE_POLICIES:', 'augmenter', '=', 'augment.AutoAugment(augmentation_name=policy)', 'aug_image', '=', 'augmenter.distort(image)', 'self.assertEqual((2,', '224,', '224,', '3)... | 973,241 |
sek788432/Waymo-2D-Object-Detection | augment_test.py | AutoaugmentTest.test_all_policy_ops_video | test_all_policy_ops_video | Smoke test to be sure all video augmentation functions can execute. | [
"Smoke",
"test",
"to",
"be",
"sure",
"all",
"video",
"augmentation",
"functions",
"can",
"execute."
] | def test_all_policy_ops_video(self):
prob = 1
magnitude = 10
replace_value = [128] * 3
cutout_const = 100
translate_const = 250
image = tf.ones((2, 224, 224, 3), dtype=tf.uint8)
for op_name in augment.NAME_TO_FUNC:
(func, _, args) = augment._parse_policy_info(op_name, prob, magnitude... | ['def', 'test_all_policy_ops_video(self):', 'prob', '=', '1', 'magnitude', '=', '10', 'replace_value', '=', '[128]', '*', '3', 'cutout_const', '=', '100', 'translate_const', '=', '250', 'image', '=', 'tf.ones((2,', '224,', '224,', '3),', 'dtype=tf.uint8)', 'for', 'op_name', 'in', 'augment.NAME_TO_FUNC:', '(func,', '_,'... | 973,243 |
sek788432/Waymo-2D-Object-Detection | augment_test.py | AutoaugmentTest.test_custom_policy | test_custom_policy | Test autoaugment with a custom policy. | [
"Test",
"autoaugment",
"with",
"a",
"custom",
"policy."
] | def test_custom_policy(self):
image = tf.zeros((224, 224, 3), dtype=tf.uint8)
augmenter = augment.AutoAugment(policies=self._generate_test_policy())
aug_image = augmenter.distort(image)
self.assertEqual((224, 224, 3), aug_image.shape) | ['def', 'test_custom_policy(self):', 'image', '=', 'tf.zeros((224,', '224,', '3),', 'dtype=tf.uint8)', 'augmenter', '=', 'augment.AutoAugment(policies=self._generate_test_policy())', 'aug_image', '=', 'augmenter.distort(image)', 'self.assertEqual((224,', '224,', '3),', 'aug_image.shape)'] | 973,244 |
sek788432/Waymo-2D-Object-Detection | augment_test.py | AutoaugmentTest.test_invalid_custom_sub_policy | test_invalid_custom_sub_policy | Test autoaugment with out-of-range values in the custom policy. | [
"Test",
"autoaugment",
"with",
"out-of-range",
"values",
"in",
"the",
"custom",
"policy."
] | def test_invalid_custom_sub_policy(self, sub_policy, value):
image = tf.zeros((224, 224, 3), dtype=tf.uint8)
policy = self._generate_test_policy()
policy[0][0] = sub_policy
augmenter = augment.AutoAugment(policies=policy)
with self.assertRaisesRegex(tf.errors.InvalidArgumentError, "Expected \\'tf.Te... | ['def', 'test_invalid_custom_sub_policy(self,', 'sub_policy,', 'value):', 'image', '=', 'tf.zeros((224,', '224,', '3),', 'dtype=tf.uint8)', 'policy', '=', 'self._generate_test_policy()', 'policy[0][0]', '=', 'sub_policy', 'augmenter', '=', 'augment.AutoAugment(policies=policy)', 'with', 'self.assertRaisesRegex(tf.error... | 973,245 |
sek788432/Waymo-2D-Object-Detection | augment_test.py | AutoaugmentTest.test_invalid_custom_policy_ndim | test_invalid_custom_policy_ndim | Test autoaugment with wrong dimension in the custom policy. | [
"Test",
"autoaugment",
"with",
"wrong",
"dimension",
"in",
"the",
"custom",
"policy."
] | def test_invalid_custom_policy_ndim(self):
policy = [[('Equalize', 0.8, 1), ('Shear', 0.8, 4)], [('TranslateY', 0.6, 3), ('Rotate', 0.9, 3)]]
policy = [[policy]]
with self.assertRaisesRegex(ValueError, 'Expected \\(:, :, 3\\) but got \\(1, 1, 2, 2, 3\\).'):
augment.AutoAugment(policies=policy) | ['def', 'test_invalid_custom_policy_ndim(self):', 'policy', '=', "[[('Equalize',", '0.8,', '1),', "('Shear',", '0.8,', '4)],', "[('TranslateY',", '0.6,', '3),', "('Rotate',", '0.9,', '3)]]', 'policy', '=', '[[policy]]', 'with', 'self.assertRaisesRegex(ValueError,', "'Expected", '\\\\(:,', ':,', '3\\\\)', 'but', 'got', ... | 973,246 |
sek788432/Waymo-2D-Object-Detection | augment_test.py | AutoaugmentTest.test_invalid_custom_policy_shape | test_invalid_custom_policy_shape | Test autoaugment with wrong shape in the custom policy. | [
"Test",
"autoaugment",
"with",
"wrong",
"shape",
"in",
"the",
"custom",
"policy."
] | def test_invalid_custom_policy_shape(self):
policy = [[('Equalize', 0.8, 1, 1), ('Shear', 0.8, 4, 1)], [('TranslateY', 0.6, 3, 1), ('Rotate', 0.9, 3, 1)]]
with self.assertRaisesRegex(ValueError, 'Expected \\(:, :, 3\\) but got \\(2, 2, 4\\)'):
augment.AutoAugment(policies=policy) | ['def', 'test_invalid_custom_policy_shape(self):', 'policy', '=', "[[('Equalize',", '0.8,', '1,', '1),', "('Shear',", '0.8,', '4,', '1)],', "[('TranslateY',", '0.6,', '3,', '1),', "('Rotate',", '0.9,', '3,', '1)]]', 'with', 'self.assertRaisesRegex(ValueError,', "'Expected", '\\\\(:,', ':,', '3\\\\)', 'but', 'got', '\\\... | 973,247 |
sek788432/Waymo-2D-Object-Detection | mask_ops.py | paste_instance_masks | paste_instance_masks | Paste instance masks to generate the image segmentation results. | [
"Paste",
"instance",
"masks",
"to",
"generate",
"the",
"image",
"segmentation",
"results."
] | def paste_instance_masks(masks, detected_boxes, image_height, image_width):
def expand_boxes(boxes, scale):
w_half = boxes[:, 2] * 0.5
h_half = boxes[:, 3] * 0.5
x_c = boxes[:, 0] + w_half
y_c = boxes[:, 1] + h_half
w_half *= scale
h_half *= scale
boxes_exp =... | ['def', 'paste_instance_masks(masks,', 'detected_boxes,', 'image_height,', 'image_width):', 'def', 'expand_boxes(boxes,', 'scale):', 'w_half', '=', 'boxes[:,', '2]', '*', '0.5', 'h_half', '=', 'boxes[:,', '3]', '*', '0.5', 'x_c', '=', 'boxes[:,', '0]', '+', 'w_half', 'y_c', '=', 'boxes[:,', '1]', '+', 'h_half', 'w_half... | 973,263 |
sek788432/Waymo-2D-Object-Detection | preprocess_ops_3d.py | random_crop_resize | random_crop_resize | First crops clip with jittering and then resizes to (output_h, output_w). | [
"First",
"crops",
"clip",
"with",
"jittering",
"and",
"then",
"resizes",
"to",
"(output_h,",
"output_w)."
] | def random_crop_resize(frames: tf.Tensor, output_h: int, output_w: int, num_frames: int, num_channels: int, aspect_ratio: Tuple[float, float], area_range: Tuple[float, float]) -> tf.Tensor:
shape = tf.shape(frames)
(seq_len, _, _, channels) = (shape[0], shape[1], shape[2], shape[3])
bbox = tf.constant([0.0,... | ['def', 'random_crop_resize(frames:', 'tf.Tensor,', 'output_h:', 'int,', 'output_w:', 'int,', 'num_frames:', 'int,', 'num_channels:', 'int,', 'aspect_ratio:', 'Tuple[float,', 'float],', 'area_range:', 'Tuple[float,', 'float])', '->', 'tf.Tensor:', 'shape', '=', 'tf.shape(frames)', '(seq_len,', '_,', '_,', 'channels)', ... | 973,283 |
sek788432/Waymo-2D-Object-Detection | assemblenet.py | flat_lists_to_blocks | flat_lists_to_blocks | Transforms the raw list structure configs to BlockSpec tuple. | [
"Transforms",
"the",
"raw",
"list",
"structure",
"configs",
"to",
"BlockSpec",
"tuple."
] | def flat_lists_to_blocks(model_structures, model_edge_weights):
blocks = []
for (node, edge_weights) in zip(model_structures, model_edge_weights):
if node[0] < 0:
block = BlockSpec(level=node[0], temporal_dilation=node[1])
else:
block = BlockSpec(level=node[0], input_bloc... | ['def', 'flat_lists_to_blocks(model_structures,', 'model_edge_weights):', 'blocks', '=', '[]', 'for', '(node,', 'edge_weights)', 'in', 'zip(model_structures,', 'model_edge_weights):', 'if', 'node[0]', '<', '0:', 'block', '=', 'BlockSpec(level=node[0],', 'temporal_dilation=node[1])', 'else:', 'block', '=', 'BlockSpec(le... | 973,292 |
sek788432/Waymo-2D-Object-Detection | assemblenet.py | blocks_to_flat_lists | blocks_to_flat_lists | Transforms BlockSpec tuple to the raw list structure configs. | [
"Transforms",
"BlockSpec",
"tuple",
"to",
"the",
"raw",
"list",
"structure",
"configs."
] | def blocks_to_flat_lists(blocks: List[BlockSpec]):
model_structure = [[b.level, list(b.input_blocks), b.num_filters, b.temporal_dilation, b.spatial_stride, 0] if b.level >= 0 else [b.level, b.temporal_dilation] for b in blocks]
model_edge_weights = [[list(b.input_block_weight)] if b.input_block_weight else [] f... | ['def', 'blocks_to_flat_lists(blocks:', 'List[BlockSpec]):', 'model_structure', '=', '[[b.level,', 'list(b.input_blocks),', 'b.num_filters,', 'b.temporal_dilation,', 'b.spatial_stride,', '0]', 'if', 'b.level', '>=', '0', 'else', '[b.level,', 'b.temporal_dilation]', 'for', 'b', 'in', 'blocks]', 'model_edge_weights', '='... | 973,293 |
sek788432/Waymo-2D-Object-Detection | assemblenet.py | assemblenet_kinetics600 | assemblenet_kinetics600 | Video classification on Videonet with assemblenet. | [
"Video",
"classification",
"on",
"Videonet",
"with",
"assemblenet."
] | def assemblenet_kinetics600() -> cfg.ExperimentConfig:
exp = video_classification.video_classification_kinetics600()
feature_shape = (32, 224, 224, 3)
exp.task.train_data.global_batch_size = 1024
exp.task.validation_data.global_batch_size = 32
exp.task.train_data.feature_shape = feature_shape
ex... | ['def', 'assemblenet_kinetics600()', '->', 'cfg.ExperimentConfig:', 'exp', '=', 'video_classification.video_classification_kinetics600()', 'feature_shape', '=', '(32,', '224,', '224,', '3)', 'exp.task.train_data.global_batch_size', '=', '1024', 'exp.task.validation_data.global_batch_size', '=', '32', 'exp.task.train_da... | 973,294 |
sek788432/Waymo-2D-Object-Detection | assemblenet.py | block_group | block_group | Creates one group of blocks for the AssembleNett model. | [
"Creates",
"one",
"group",
"of",
"blocks",
"for",
"the",
"AssembleNett",
"model."
] | def block_group(inputs: tf.Tensor, filters: int, block_fn: Callable[..., tf.Tensor], blocks: int, strides: int, name, block_level, num_frames=32, temporal_dilation=1):
inputs = block_fn(inputs, filters, intermediate_channel_size[block_level], strides, use_projection=True, num_frames=num_frames, temporal_dilation=te... | ['def', 'block_group(inputs:', 'tf.Tensor,', 'filters:', 'int,', 'block_fn:', 'Callable[...,', 'tf.Tensor],', 'blocks:', 'int,', 'strides:', 'int,', 'name,', 'block_level,', 'num_frames=32,', 'temporal_dilation=1):', 'inputs', '=', 'block_fn(inputs,', 'filters,', 'intermediate_channel_size[block_level],', 'strides,', '... | 973,300 |
sek788432/Waymo-2D-Object-Detection | assemblenet.py | spatial_resize_and_concat | spatial_resize_and_concat | Concatenates multiple different sized tensors channel-wise. | [
"Concatenates",
"multiple",
"different",
"sized",
"tensors",
"channel-wise."
] | def spatial_resize_and_concat(inputs):
data_format = tf.keras.backend.image_data_format()
assert data_format == 'channels_last'
if len(inputs) == 1:
return inputs[0]
if data_format != 'channels_last':
return inputs
sm_size = [1000, 1000]
for inp in inputs:
sm_size[0] = mi... | ['def', 'spatial_resize_and_concat(inputs):', 'data_format', '=', 'tf.keras.backend.image_data_format()', 'assert', 'data_format', '==', "'channels_last'", 'if', 'len(inputs)', '==', '1:', 'return', 'inputs[0]', 'if', 'data_format', '!=', "'channels_last':", 'return', 'inputs', 'sm_size', '=', '[1000,', '1000]', 'for',... | 973,301 |
sek788432/Waymo-2D-Object-Detection | assemblenet.py | rgb_conv_stem | rgb_conv_stem | Layers for a RGB stem. | [
"Layers",
"for",
"a",
"RGB",
"stem."
] | def rgb_conv_stem(inputs, num_frames, filters, temporal_dilation, bn_decay: float=rf.BATCH_NORM_DECAY, bn_epsilon: float=rf.BATCH_NORM_EPSILON, use_sync_bn: bool=False):
data_format = tf.keras.backend.image_data_format()
assert data_format == 'channels_last'
if temporal_dilation < 1:
temporal_dilati... | ['def', 'rgb_conv_stem(inputs,', 'num_frames,', 'filters,', 'temporal_dilation,', 'bn_decay:', 'float=rf.BATCH_NORM_DECAY,', 'bn_epsilon:', 'float=rf.BATCH_NORM_EPSILON,', 'use_sync_bn:', 'bool=False):', 'data_format', '=', 'tf.keras.backend.image_data_format()', 'assert', 'data_format', '==', "'channels_last'", 'if', ... | 973,303 |
sek788432/Waymo-2D-Object-Detection | assemblenet.py | multi_stream_heads | multi_stream_heads | Layers for the classification heads. | [
"Layers",
"for",
"the",
"classification",
"heads."
] | def multi_stream_heads(streams, final_nodes, num_frames, num_classes, max_pool_preditions: bool=False):
inputs = streams[final_nodes[0]]
num_channels = inputs.shape[-1]
def _pool_and_reshape(net):
net = tf.keras.layers.GlobalAveragePooling2D()(inputs=net)
net = tf.identity(net, 'final_avg_p... | ['def', 'multi_stream_heads(streams,', 'final_nodes,', 'num_frames,', 'num_classes,', 'max_pool_preditions:', 'bool=False):', 'inputs', '=', 'streams[final_nodes[0]]', 'num_channels', '=', 'inputs.shape[-1]', 'def', '_pool_and_reshape(net):', 'net', '=', 'tf.keras.layers.GlobalAveragePooling2D()(inputs=net)', 'net', '=... | 973,305 |
sek788432/Waymo-2D-Object-Detection | rep_flow_2d_layer.py | divergence | divergence | Computes the divergence value used with TV-L1 optical flow algorithm. | [
"Computes",
"the",
"divergence",
"value",
"used",
"with",
"TV-L1",
"optical",
"flow",
"algorithm."
] | def divergence(p1, p2, f_grad_x, f_grad_y, name):
data_format = tf.keras.backend.image_data_format()
df = 'NHWC' if data_format == 'channels_last' else 'NCHW'
with tf.name_scope('divergence_' + name):
if data_format == 'channels_last':
p1 = tf.pad(p1[:, :, :-1, :], [[0, 0], [0, 0], [1, 0... | ['def', 'divergence(p1,', 'p2,', 'f_grad_x,', 'f_grad_y,', 'name):', 'data_format', '=', 'tf.keras.backend.image_data_format()', 'df', '=', "'NHWC'", 'if', 'data_format', '==', "'channels_last'", 'else', "'NCHW'", 'with', "tf.name_scope('divergence_'", '+', 'name):', 'if', 'data_format', '==', "'channels_last':", 'p1',... | 973,309 |
sek788432/Waymo-2D-Object-Detection | deep_mask_head_rcnn.py | deep_mask_head_rcnn_resnetfpn_coco | deep_mask_head_rcnn_resnetfpn_coco | COCO object detection with Mask R-CNN with deep mask heads. | [
"COCO",
"object",
"detection",
"with",
"Mask",
"R-CNN",
"with",
"deep",
"mask",
"heads."
] | def deep_mask_head_rcnn_resnetfpn_coco() -> cfg.ExperimentConfig:
global_batch_size = 64
steps_per_epoch = int(retinanet_config.COCO_TRAIN_EXAMPLES / global_batch_size)
coco_val_samples = 5000
config = cfg.ExperimentConfig(runtime=cfg.RuntimeConfig(mixed_precision_dtype='bfloat16'), task=DeepMaskHeadRCN... | ['def', 'deep_mask_head_rcnn_resnetfpn_coco()', '->', 'cfg.ExperimentConfig:', 'global_batch_size', '=', '64', 'steps_per_epoch', '=', 'int(retinanet_config.COCO_TRAIN_EXAMPLES', '/', 'global_batch_size)', 'coco_val_samples', '=', '5000', 'config', '=', "cfg.ExperimentConfig(runtime=cfg.RuntimeConfig(mixed_precision_dt... | 973,310 |
sek788432/Waymo-2D-Object-Detection | instance_heads.py | DeepMaskHead.call | call | Forward pass of mask branch for the Mask-RCNN model. | [
"Forward",
"pass",
"of",
"mask",
"branch",
"for",
"the",
"Mask-RCNN",
"model."
] | def call(self, inputs, training=None):
(roi_features, roi_classes) = inputs
(batch_size, num_rois, height, width, filters) = roi_features.get_shape().as_list()
if batch_size is None:
batch_size = tf.shape(roi_features)[0]
x = tf.reshape(roi_features, [-1, height, width, filters])
x = self._c... | ['def', 'call(self,', 'inputs,', 'training=None):', '(roi_features,', 'roi_classes)', '=', 'inputs', '(batch_size,', 'num_rois,', 'height,', 'width,', 'filters)', '=', 'roi_features.get_shape().as_list()', 'if', 'batch_size', 'is', 'None:', 'batch_size', '=', 'tf.shape(roi_features)[0]', 'x', '=', 'tf.reshape(roi_featu... | 973,317 |
sek788432/Waymo-2D-Object-Detection | movinet.py | Movinet.initial_state_specs | initial_state_specs | Creates a mapping of state name to InputSpec from the input shape. | [
"Creates",
"a",
"mapping",
"of",
"state",
"name",
"to",
"InputSpec",
"from",
"the",
"input",
"shape."
] | def initial_state_specs(self, input_shape: Sequence[int]) -> Dict[str, tf.keras.layers.InputSpec]:
state_shapes = self._get_initial_state_shapes(self._block_specs, input_shape, use_positional_encoding=self._use_positional_encoding)
return {name: tf.keras.layers.InputSpec(shape=shape, dtype=self._get_state_dtype... | ['def', 'initial_state_specs(self,', 'input_shape:', 'Sequence[int])', '->', 'Dict[str,', 'tf.keras.layers.InputSpec]:', 'state_shapes', '=', 'self._get_initial_state_shapes(self._block_specs,', 'input_shape,', 'use_positional_encoding=self._use_positional_encoding)', 'return', '{name:', 'tf.keras.layers.InputSpec(shap... | 973,322 |
sek788432/Waymo-2D-Object-Detection | movinet.py | Movinet.init_states | init_states | Returns initial states for the first call in steaming mode. | [
"Returns",
"initial",
"states",
"for",
"the",
"first",
"call",
"in",
"steaming",
"mode."
] | def init_states(self, input_shape: Sequence[int]) -> Dict[str, tf.Tensor]:
state_shapes = self._get_initial_state_shapes(self._block_specs, input_shape, use_positional_encoding=self._use_positional_encoding)
states = {name: tf.zeros(shape, dtype=self._get_state_dtype(name)) for (name, shape) in state_shapes.ite... | ['def', 'init_states(self,', 'input_shape:', 'Sequence[int])', '->', 'Dict[str,', 'tf.Tensor]:', 'state_shapes', '=', 'self._get_initial_state_shapes(self._block_specs,', 'input_shape,', 'use_positional_encoding=self._use_positional_encoding)', 'states', '=', '{name:', 'tf.zeros(shape,', 'dtype=self._get_state_dtype(na... | 973,323 |
sek788432/Waymo-2D-Object-Detection | movinet_model.py | MovinetClassifier.backbone | backbone | Returns the backbone of the model. | [
"Returns",
"the",
"backbone",
"of",
"the",
"model."
] | def backbone(self) -> tf.keras.Model:
return self._backbone | ['def', 'backbone(self)', '->', 'tf.keras.Model:', 'return', 'self._backbone'] | 973,356 |
sek788432/Waymo-2D-Object-Detection | movinet_model_test.py | MovinetModelTest.test_movinet_classifier_creation | test_movinet_classifier_creation | Test for creation of a Movinet classifier. | [
"Test",
"for",
"creation",
"of",
"a",
"Movinet",
"classifier."
] | def test_movinet_classifier_creation(self, is_training):
temporal_size = 16
spatial_size = 224
tf.keras.backend.set_image_data_format('channels_last')
input_specs = tf.keras.layers.InputSpec(shape=[None, temporal_size, spatial_size, spatial_size, 3])
backbone = movinet.Movinet(model_id='a0', input_s... | ['def', 'test_movinet_classifier_creation(self,', 'is_training):', 'temporal_size', '=', '16', 'spatial_size', '=', '224', "tf.keras.backend.set_image_data_format('channels_last')", 'input_specs', '=', 'tf.keras.layers.InputSpec(shape=[None,', 'temporal_size,', 'spatial_size,', 'spatial_size,', '3])', 'backbone', '=', ... | 973,357 |
sek788432/Waymo-2D-Object-Detection | movinet_model_test.py | MovinetModelTest.test_movinet_classifier_stream | test_movinet_classifier_stream | Test if the classifier can be run in streaming mode. | [
"Test",
"if",
"the",
"classifier",
"can",
"be",
"run",
"in",
"streaming",
"mode."
] | def test_movinet_classifier_stream(self):
tf.keras.backend.set_image_data_format('channels_last')
backbone = movinet.Movinet(model_id='a0', causal=True, use_external_states=True)
model = movinet_model.MovinetClassifier(backbone, num_classes=600, output_states=True)
inputs = tf.ones([1, 8, 172, 172, 3])
... | ['def', 'test_movinet_classifier_stream(self):', "tf.keras.backend.set_image_data_format('channels_last')", 'backbone', '=', "movinet.Movinet(model_id='a0',", 'causal=True,', 'use_external_states=True)', 'model', '=', 'movinet_model.MovinetClassifier(backbone,', 'num_classes=600,', 'output_states=True)', 'inputs', '=',... | 973,358 |
sek788432/Waymo-2D-Object-Detection | movinet_model_test.py | MovinetModelTest.test_movinet_classifier_stream_pos_enc_2plus1d | test_movinet_classifier_stream_pos_enc_2plus1d | Test if the model can run in streaming mode with pos encoding, (2+1)D. | [
"Test",
"if",
"the",
"model",
"can",
"run",
"in",
"streaming",
"mode",
"with",
"pos",
"encoding,",
"(2+1)D."
] | def test_movinet_classifier_stream_pos_enc_2plus1d(self):
tf.keras.backend.set_image_data_format('channels_last')
backbone = movinet.Movinet(model_id='a0', causal=True, use_external_states=True, use_positional_encoding=True, conv_type='2plus1d')
model = movinet_model.MovinetClassifier(backbone, num_classes=... | ['def', 'test_movinet_classifier_stream_pos_enc_2plus1d(self):', "tf.keras.backend.set_image_data_format('channels_last')", 'backbone', '=', "movinet.Movinet(model_id='a0',", 'causal=True,', 'use_external_states=True,', 'use_positional_encoding=True,', "conv_type='2plus1d')", 'model', '=', 'movinet_model.MovinetClassif... | 973,360 |
sek788432/Waymo-2D-Object-Detection | movinet_test.py | MoViNetTest.test_network_with_states | test_network_with_states | Test creation of MoViNet family models with states. | [
"Test",
"creation",
"of",
"MoViNet",
"family",
"models",
"with",
"states."
] | def test_network_with_states(self):
tf.keras.backend.set_image_data_format('channels_last')
backbone = movinet.Movinet(model_id='a0', causal=True, use_external_states=True)
inputs = tf.ones([1, 8, 128, 128, 3])
init_states = backbone.init_states(tf.shape(inputs))
(endpoints, new_states) = backbone({... | ['def', 'test_network_with_states(self):', "tf.keras.backend.set_image_data_format('channels_last')", 'backbone', '=', "movinet.Movinet(model_id='a0',", 'causal=True,', 'use_external_states=True)', 'inputs', '=', 'tf.ones([1,', '8,', '128,', '128,', '3])', 'init_states', '=', 'backbone.init_states(tf.shape(inputs))', '... | 973,365 |
sek788432/Waymo-2D-Object-Detection | movinet_test.py | MoViNetTest.test_movinet_stream | test_movinet_stream | Test if the backbone can be run in streaming mode. | [
"Test",
"if",
"the",
"backbone",
"can",
"be",
"run",
"in",
"streaming",
"mode."
] | def test_movinet_stream(self):
tf.keras.backend.set_image_data_format('channels_last')
backbone = movinet.Movinet(model_id='a0', causal=True, use_external_states=True)
inputs = tf.ones([1, 5, 128, 128, 3])
init_states = backbone.init_states(tf.shape(inputs))
(expected_endpoints, _) = backbone({**ini... | ['def', 'test_movinet_stream(self):', "tf.keras.backend.set_image_data_format('channels_last')", 'backbone', '=', "movinet.Movinet(model_id='a0',", 'causal=True,', 'use_external_states=True)', 'inputs', '=', 'tf.ones([1,', '5,', '128,', '128,', '3])', 'init_states', '=', 'backbone.init_states(tf.shape(inputs))', '(expe... | 973,366 |
sek788432/Waymo-2D-Object-Detection | contrastive_losses.py | cross_replica_concat | cross_replica_concat | Reduce a concatenation of the `tensor` across multiple replicas. | [
"Reduce",
"a",
"concatenation",
"of",
"the",
"`tensor`",
"across",
"multiple",
"replicas."
] | def cross_replica_concat(tensor: tf.Tensor, num_replicas: int) -> tf.Tensor:
if num_replicas <= 1:
return tensor
replica_context = tf.distribute.get_replica_context()
with tf.name_scope('cross_replica_concat'):
ext_tensor = tf.scatter_nd(indices=[[replica_context.replica_id_in_sync_group]], ... | ['def', 'cross_replica_concat(tensor:', 'tf.Tensor,', 'num_replicas:', 'int)', '->', 'tf.Tensor:', 'if', 'num_replicas', '<=', '1:', 'return', 'tensor', 'replica_context', '=', 'tf.distribute.get_replica_context()', 'with', "tf.name_scope('cross_replica_concat'):", 'ext_tensor', '=', 'tf.scatter_nd(indices=[[replica_co... | 973,378 |
sek788432/Waymo-2D-Object-Detection | box_ops.py | compute_ciou | compute_ciou | Calculates the complete intersection of union between box1 and box2. | [
"Calculates",
"the",
"complete",
"intersection",
"of",
"union",
"between",
"box1",
"and",
"box2."
] | def compute_ciou(box1, box2):
with tf.name_scope('ciou'):
(iou, diou) = compute_diou(box1, box2)
arcterm = (tf.math.atan(tf.math.divide_no_nan(box1[..., 2], box1[..., 3])) - tf.math.atan(tf.math.divide_no_nan(box2[..., 2], box2[..., 3]))) ** 2
v = 4 * arcterm / math.pi ** 2
a = tf.ma... | ['def', 'compute_ciou(box1,', 'box2):', 'with', "tf.name_scope('ciou'):", '(iou,', 'diou)', '=', 'compute_diou(box1,', 'box2)', 'arcterm', '=', '(tf.math.atan(tf.math.divide_no_nan(box1[...,', '2],', 'box1[...,', '3]))', '-', 'tf.math.atan(tf.math.divide_no_nan(box2[...,', '2],', 'box2[...,', '3])))', '**', '2', 'v', '... | 973,395 |
sek788432/Waymo-2D-Object-Detection | preprocess_ops.py | fit_preserve_aspect_ratio | fit_preserve_aspect_ratio | Resizes the image while peserving the image aspect ratio. | [
"Resizes",
"the",
"image",
"while",
"peserving",
"the",
"image",
"aspect",
"ratio."
] | def fit_preserve_aspect_ratio(image, boxes, width=None, height=None, target_dim=None):
if width is None or height is None:
shape = tf.shape(image)
if tf.shape(shape)[0] == 4:
width = shape[1]
height = shape[2]
else:
width = shape[0]
height = sh... | ['def', 'fit_preserve_aspect_ratio(image,', 'boxes,', 'width=None,', 'height=None,', 'target_dim=None):', 'if', 'width', 'is', 'None', 'or', 'height', 'is', 'None:', 'shape', '=', 'tf.shape(image)', 'if', 'tf.shape(shape)[0]', '==', '4:', 'width', '=', 'shape[1]', 'height', '=', 'shape[2]', 'else:', 'width', '=', 'shap... | 973,401 |
sek788432/Waymo-2D-Object-Detection | preprocess_ops.py | get_best_anchor | get_best_anchor | Gets the correct anchor that is assoiciated with each box using IOU. | [
"Gets",
"the",
"correct",
"anchor",
"that",
"is",
"assoiciated",
"with",
"each",
"box",
"using",
"IOU."
] | def get_best_anchor(y_true, anchors, width=1, height=1):
with tf.name_scope('get_anchor'):
width = tf.cast(width, dtype=tf.float32)
height = tf.cast(height, dtype=tf.float32)
anchor_xy = y_true[..., 0:2]
anchors = tf.convert_to_tensor(anchors, dtype=tf.float32)
anchors_x = an... | ['def', 'get_best_anchor(y_true,', 'anchors,', 'width=1,', 'height=1):', 'with', "tf.name_scope('get_anchor'):", 'width', '=', 'tf.cast(width,', 'dtype=tf.float32)', 'height', '=', 'tf.cast(height,', 'dtype=tf.float32)', 'anchor_xy', '=', 'y_true[...,', '0:2]', 'anchors', '=', 'tf.convert_to_tensor(anchors,', 'dtype=tf... | 973,402 |
sek788432/Waymo-2D-Object-Detection | preprocess_ops.py | build_grided_gt | build_grided_gt | Converts ground truth for use in loss functions. | [
"Converts",
"ground",
"truth",
"for",
"use",
"in",
"loss",
"functions."
] | def build_grided_gt(y_true, mask, size, dtype, use_tie_breaker):
boxes = tf.cast(y_true['bbox'], dtype)
classes = tf.expand_dims(tf.cast(y_true['classes'], dtype=dtype), axis=-1)
anchors = tf.cast(y_true['best_anchors'], dtype)
num_boxes = tf.shape(boxes)[0]
len_masks = tf.shape(mask)[0]
full = ... | ['def', 'build_grided_gt(y_true,', 'mask,', 'size,', 'dtype,', 'use_tie_breaker):', 'boxes', '=', "tf.cast(y_true['bbox'],", 'dtype)', 'classes', '=', "tf.expand_dims(tf.cast(y_true['classes'],", 'dtype=dtype),', 'axis=-1)', 'anchors', '=', "tf.cast(y_true['best_anchors'],", 'dtype)', 'num_boxes', '=', 'tf.shape(boxes)... | 973,403 |
sek788432/Waymo-2D-Object-Detection | utils.py | Dequantize | Dequantize | Dequantize the feature from the byte format to the float format. | [
"Dequantize",
"the",
"feature",
"from",
"the",
"byte",
"format",
"to",
"the",
"float",
"format."
] | def Dequantize(feat_vector, max_quantized_value=2, min_quantized_value=-2):
assert max_quantized_value > min_quantized_value
quantized_range = max_quantized_value - min_quantized_value
scalar = quantized_range / 255.0
bias = quantized_range / 512.0 + min_quantized_value
return feat_vector * scalar +... | ['def', 'Dequantize(feat_vector,', 'max_quantized_value=2,', 'min_quantized_value=-2):', 'assert', 'max_quantized_value', '>', 'min_quantized_value', 'quantized_range', '=', 'max_quantized_value', '-', 'min_quantized_value', 'scalar', '=', 'quantized_range', '/', '255.0', 'bias', '=', 'quantized_range', '/', '512.0', '... | 973,407 |
sek788432/Waymo-2D-Object-Detection | utils.py | AddGlobalStepSummary | AddGlobalStepSummary | Add the global_step summary to the Tensorboard. | [
"Add",
"the",
"global_step",
"summary",
"to",
"the",
"Tensorboard."
] | def AddGlobalStepSummary(summary_writer, global_step_val, global_step_info_dict, summary_scope='Eval'):
this_hit_at_one = global_step_info_dict['hit_at_one']
this_perr = global_step_info_dict['perr']
this_loss = global_step_info_dict['loss']
examples_per_second = global_step_info_dict.get('examples_per_... | ['def', 'AddGlobalStepSummary(summary_writer,', 'global_step_val,', 'global_step_info_dict,', "summary_scope='Eval'):", 'this_hit_at_one', '=', "global_step_info_dict['hit_at_one']", 'this_perr', '=', "global_step_info_dict['perr']", 'this_loss', '=', "global_step_info_dict['loss']", 'examples_per_second', '=', "global... | 973,409 |
sek788432/Waymo-2D-Object-Detection | utils.py | AddEpochSummary | AddEpochSummary | Add the epoch summary to the Tensorboard. | [
"Add",
"the",
"epoch",
"summary",
"to",
"the",
"Tensorboard."
] | def AddEpochSummary(summary_writer, global_step_val, epoch_info_dict, summary_scope='Eval'):
epoch_id = epoch_info_dict['epoch_id']
avg_hit_at_one = epoch_info_dict['avg_hit_at_one']
avg_perr = epoch_info_dict['avg_perr']
avg_loss = epoch_info_dict['avg_loss']
aps = epoch_info_dict['aps']
gap = ... | ['def', 'AddEpochSummary(summary_writer,', 'global_step_val,', 'epoch_info_dict,', "summary_scope='Eval'):", 'epoch_id', '=', "epoch_info_dict['epoch_id']", 'avg_hit_at_one', '=', "epoch_info_dict['avg_hit_at_one']", 'avg_perr', '=', "epoch_info_dict['avg_perr']", 'avg_loss', '=', "epoch_info_dict['avg_loss']", 'aps', ... | 973,410 |
sek788432/Waymo-2D-Object-Detection | average_precision_calculator.py | AveragePrecisionCalculator.heap_size | heap_size | Gets the heap size maintained in the class. | [
"Gets",
"the",
"heap",
"size",
"maintained",
"in",
"the",
"class."
] | def heap_size(self):
return len(self._heap) | ['def', 'heap_size(self):', 'return', 'len(self._heap)'] | 973,418 |
sek788432/Waymo-2D-Object-Detection | average_precision_calculator.py | AveragePrecisionCalculator.clear | clear | Clear the accumulated predictions. | [
"Clear",
"the",
"accumulated",
"predictions."
] | def clear(self):
self._heap = []
self._total_positives = 0 | ['def', 'clear(self):', 'self._heap', '=', '[]', 'self._total_positives', '=', '0'] | 973,421 |
sek788432/Waymo-2D-Object-Detection | average_precision_calculator.py | AveragePrecisionCalculator.ap | ap | Calculate the non-interpolated average precision. | [
"Calculate",
"the",
"non-interpolated",
"average",
"precision."
] | def ap(predictions, actuals):
return AveragePrecisionCalculator.ap_at_n(predictions, actuals, n=None) | ['def', 'ap(predictions,', 'actuals):', 'return', 'AveragePrecisionCalculator.ap_at_n(predictions,', 'actuals,', 'n=None)'] | 973,423 |
sek788432/Waymo-2D-Object-Detection | eval_util.py | flatten | flatten | Merges a list of lists into a single list. | [
"Merges",
"a",
"list",
"of",
"lists",
"into",
"a",
"single",
"list."
] | def flatten(l):
return [item for sublist in l for item in sublist] | ['def', 'flatten(l):', 'return', '[item', 'for', 'sublist', 'in', 'l', 'for', 'item', 'in', 'sublist]'] | 973,425 |
sek788432/Waymo-2D-Object-Detection | eval_util.py | calculate_hit_at_one | calculate_hit_at_one | Performs a local (numpy) calculation of the hit at one. | [
"Performs",
"a",
"local",
"(numpy)",
"calculation",
"of",
"the",
"hit",
"at",
"one."
] | def calculate_hit_at_one(predictions, actuals):
top_prediction = np.argmax(predictions, 1)
hits = actuals[np.arange(actuals.shape[0]), top_prediction]
return np.average(hits) | ['def', 'calculate_hit_at_one(predictions,', 'actuals):', 'top_prediction', '=', 'np.argmax(predictions,', '1)', 'hits', '=', 'actuals[np.arange(actuals.shape[0]),', 'top_prediction]', 'return', 'np.average(hits)'] | 973,426 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.