text
stringlengths
5
22M
id
stringlengths
12
177
metadata
dict
__index_level_0__
int64
0
1.37k
#include <vector> #include <iostream> #include <ATen/ATen.h> #include <cuda.h> #include <cuda_runtime.h> #include <cuda_fp16.h> #include <cuda_bf16.h> #include <cuda_profiler_api.h> #include "THC/THC.h" #include <ATen/cuda/CUDAContext.h> #include <torch/extension.h> #include <math.h> #include "softmax.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; std::vector<torch::Tensor> fwd_cuda( bool is_training, int heads, torch::Tensor const& input, float dropout_prob ) { const int attn_batches = input.size(0); const int sequences = attn_batches / heads; const int q_seq_len = input.size(1); const int k_seq_len = q_seq_len; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = input.options().requires_grad(false); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor softmax_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* input_ptr = static_cast<void*>(input.data_ptr()); void* softmax_results_ptr = static_cast<void*>(softmax_results.data_ptr()); // Padded Softmax bool softmax_success = false; if (input.type().scalarType() == at::ScalarType::BFloat16){ softmax_success = dispatch_softmax<nv_bfloat16, nv_bfloat16, float>( reinterpret_cast<nv_bfloat16*>(softmax_results_ptr), reinterpret_cast<const nv_bfloat16*>(input_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else if (input.type().scalarType() == at::ScalarType::Half){ softmax_success = dispatch_softmax<half, half, float>( reinterpret_cast<half*>(softmax_results_ptr), reinterpret_cast<const half*>(input_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else if (input.type().scalarType() == at::ScalarType::Float){ softmax_success = dispatch_softmax<float, float, float>( reinterpret_cast<float*>(softmax_results_ptr), reinterpret_cast<const float*>(input_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else { softmax_success = false; } if (is_training) { //use at:: function so that C++ version generates the same random mask as python version auto dropout_tuple = at::_fused_dropout(softmax_results, 1.0f-dropout_prob); dropout_results = std::get<0>(dropout_tuple); dropout_mask = std::get<1>(dropout_tuple); } // Matmul2 return { dropout_results, dropout_mask, softmax_results }; } torch::Tensor bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& softmax_results, torch::Tensor const& dropout_mask, float dropout_prob ) { const int attn_batches = output_grads.size(0); const int q_seq_len = output_grads.size(1); const int k_seq_len = q_seq_len; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations // torch::Tensor input_grads = torch::empty_like(output_grads); // Apply Dropout Mask and Scale by Dropout Probability // Softmax Grad if (softmax_results.type().scalarType() == at::ScalarType::BFloat16){ dispatch_masked_scale_softmax_backward<nv_bfloat16, nv_bfloat16, float, false>( static_cast<nv_bfloat16*>(output_grads.data_ptr()), static_cast<nv_bfloat16*>(output_grads.data_ptr()), reinterpret_cast<nv_bfloat16 const*>(softmax_results.data_ptr()), static_cast<uint8_t const*>(dropout_mask.data_ptr()), 1.0/(1.0-dropout_prob), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else if (softmax_results.type().scalarType() == at::ScalarType::Half){ dispatch_masked_scale_softmax_backward<half, half, float, false>( static_cast<half*>(output_grads.data_ptr()), static_cast<half*>(output_grads.data_ptr()), reinterpret_cast<half const*>(softmax_results.data_ptr()), static_cast<uint8_t const*>(dropout_mask.data_ptr()), 1.0/(1.0-dropout_prob), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else if (softmax_results.type().scalarType() == at::ScalarType::Float){ dispatch_masked_scale_softmax_backward<float, float, float, false>( static_cast<float*>(output_grads.data_ptr()), static_cast<float*>(output_grads.data_ptr()), reinterpret_cast<float const*>(softmax_results.data_ptr()), static_cast<uint8_t const*>(dropout_mask.data_ptr()), 1.0/(1.0-dropout_prob), k_seq_len, k_seq_len, attn_batches*q_seq_len); } //backward pass is completely in-place return output_grads; }
COCO-LM/fairseq/fused_ops/csrc/softmax_dropout/softmax_dropout_kernel.cu/0
{ "file_path": "COCO-LM/fairseq/fused_ops/csrc/softmax_dropout/softmax_dropout_kernel.cu", "repo_id": "COCO-LM", "token_count": 3577 }
194
[build-system] requires = ["setuptools", "wheel", "cython"] build-backend = "setuptools.build_meta"
COCO-LM/fairseq/pyproject.toml/0
{ "file_path": "COCO-LM/fairseq/pyproject.toml", "repo_id": "COCO-LM", "token_count": 37 }
195
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Split a large file into shards while respecting document boundaries. Documents should be separated by a single empty line. """ import argparse import contextlib def main(): parser = argparse.ArgumentParser() parser.add_argument("input") parser.add_argument("--num-shards", type=int) args = parser.parse_args() assert args.num_shards is not None and args.num_shards > 1 with open(args.input, "r", encoding="utf-8") as h: with contextlib.ExitStack() as stack: outputs = [ stack.enter_context( open(args.input + ".shard" + str(i), "w", encoding="utf-8") ) for i in range(args.num_shards) ] doc = [] first_doc = [True] * args.num_shards def output_doc(i): if not first_doc[i]: outputs[i].write("\n") first_doc[i] = False for line in doc: outputs[i].write(line) doc.clear() num_docs = 0 for line in h: if line.strip() == "": # empty line indicates new document output_doc(num_docs % args.num_shards) num_docs += 1 else: doc.append(line) output_doc(num_docs % args.num_shards) if __name__ == "__main__": main()
COCO-LM/fairseq/scripts/shard_docs.py/0
{ "file_path": "COCO-LM/fairseq/scripts/shard_docs.py", "repo_id": "COCO-LM", "token_count": 775 }
196
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # This file defines example configuration arguments for quantizing # a transformer model with product quantization n_centroids: Linear: key: in_features value: {"*": 8} Embedding: key: embedding_dim value: {"*": 8} block_sizes: Linear: key: fuzzy_name value: {fc: 8, attn: 4, emb: 4} Embedding: key: fuzzy_name value: {emb: 8} layers_to_quantize: - decoder\\.layers\\.\d+\\.fc[12] - decoder\\.embed_tokens\\.embeddings\\.[012]\\.[01] - decoder\\.layers\\.\d+\\.self_attn\\.(k_proj|v_proj|q_proj|out_proj)
COCO-LM/fairseq/tests/gpu/transformer_quantization_config.yaml/0
{ "file_path": "COCO-LM/fairseq/tests/gpu/transformer_quantization_config.yaml", "repo_id": "COCO-LM", "token_count": 321 }
197
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest import numpy as np from fairseq.data.data_utils_fast import batch_by_size_fn from fairseq.data.data_utils_fast import batch_by_size_vec class TestBatchBySize(unittest.TestCase): @classmethod def batch_by_size_baseline( cls, indices, num_tokens_vec, max_tokens, max_sentences, bsz_mult, ): """Simple, reliable and slow implementation of batch by size """ batches = [] start = 0 while start < len(indices): for end in range(start + 1, len(indices) + 1): max_val = max(num_tokens_vec[pos] for pos in range(start, end)) sent_count = end - start num_tokens = max_val * sent_count overflow = num_tokens > max_tokens > 0 or sent_count > max_sentences > 0 terminate = overflow or end == len(indices) if overflow: sent_count -= 1 if terminate: if sent_count > bsz_mult: sent_count = sent_count - sent_count % bsz_mult batches.append(indices[start : start + sent_count]) start = start + sent_count break return batches @classmethod def _get_error_message( cls, max_sentences, max_tokens, bsz_mult, num_tokens_vec, validation, results ): return f"""Reference batch_by_size implementation should produce same output as the baseline method. Params: max_sentences={max_sentences}, max_tokens={max_tokens}, bsz_mult={bsz_mult}, num_tokens_vec={num_tokens_vec}, expected_batches={validation}, returned_batches={results}""" def _compare_results( self, indices_len, batch_by_size_impl, max_sentences, max_tokens, bsz_mult, num_tokens_vec, ): indices = np.array(list(range(indices_len))) validation = self.batch_by_size_baseline( indices, num_tokens_vec, max_tokens=max_tokens, max_sentences=max_sentences, bsz_mult=bsz_mult, ) results = batch_by_size_impl( indices, num_tokens_vec, max_tokens=max_tokens, max_sentences=max_sentences, bsz_mult=bsz_mult, ) error_msg = self._get_error_message( max_sentences, max_tokens, bsz_mult, num_tokens_vec, validation, results ) self.assertEqual(len(validation), len(results), error_msg) for first, second in zip(validation, results): self.assertTrue(np.array_equal(first, second), error_msg) def _run_compare_with_baseline_sweep(self, batch_by_size_impl): """Compare reference batch_by_size implementation with batch_by_size_baseline across a dense grid of hyperparam values""" MAX_MAX_TOKENS = 10 NUM_TOKENS_VECS_COUNT = 5 for indices_len in [10, 11]: # try odd and even len of indices for max_sentences in range(0, indices_len + 2): for max_tokens in range(0, MAX_MAX_TOKENS): for bsz_mult in range(1, max(MAX_MAX_TOKENS, indices_len) + 2): for _ in range(NUM_TOKENS_VECS_COUNT): num_tokens_vec = np.random.randint( 0, max_tokens + 1, size=indices_len ) self._compare_results( indices_len, batch_by_size_impl, max_sentences, max_tokens, bsz_mult, num_tokens_vec, ) class TestBatchBySizeVec(TestBatchBySize): def test_compare_with_baseline(self): self._run_compare_with_baseline_sweep(batch_by_size_vec) class TestBatchBySizeFn(TestBatchBySize): def test_compare_with_baseline(self): def batch_by_size_fn_wrapper( indices, num_tokens_vec, max_tokens, max_sentences, bsz_mult, ): def num_tokens_fn(idx): return num_tokens_vec[idx] return batch_by_size_fn( indices, num_tokens_fn, max_tokens, max_sentences, bsz_mult ) self._run_compare_with_baseline_sweep(batch_by_size_fn_wrapper) if __name__ == "__main__": unittest.main()
COCO-LM/fairseq/tests/test_data_utils.py/0
{ "file_path": "COCO-LM/fairseq/tests/test_data_utils.py", "repo_id": "COCO-LM", "token_count": 2629 }
198
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest import torch from fairseq.modules.multihead_attention import MultiheadAttention class TestMultiheadAttention(unittest.TestCase): def test_append_prev_key_padding_mask(self): bsz = 1 src_len = 4 cases = [ # no padding mask (None, None, None), # current padding mask only ( torch.tensor([[1]]).bool(), None, torch.tensor([[0, 0, 0, 1]]).bool(), ), # previous padding mask only ( None, torch.tensor([[0, 1, 0]]).bool(), torch.tensor([[0, 1, 0, 0]]).bool(), ), # both padding masks ( torch.tensor([[1]]).bool(), torch.tensor([[0, 1, 0]]).bool(), torch.tensor([[0, 1, 0, 1]]).bool(), ), ] for c in cases: key_padding_mask = MultiheadAttention._append_prev_key_padding_mask( c[0], c[1], batch_size=bsz, src_len=src_len, static_kv=False, ) if key_padding_mask is not None: self.assertTrue( torch.all(torch.eq(key_padding_mask, c[2])), f"Unexpected resultant key padding mask: {key_padding_mask}" f" given current: {c[0]} and previous: {c[1]}", ) self.assertEqual(key_padding_mask.size(0), bsz) self.assertEqual(key_padding_mask.size(1), src_len) else: self.assertIsNone(c[2]) if __name__ == "__main__": unittest.main()
COCO-LM/fairseq/tests/test_multihead_attention.py/0
{ "file_path": "COCO-LM/fairseq/tests/test_multihead_attention.py", "repo_id": "COCO-LM", "token_count": 1044 }
199
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # The script is largely adapted from the huggingface transformers library from __future__ import absolute_import, division, print_function, unicode_literals import logging import math import os import torch from torch import nn from torch.nn.modules.loss import _Loss import torch.nn.functional as F from torch.nn import Parameter from transformers.modeling_utils import PreTrainedModel, PoolerAnswerClass, PoolerEndLogits, PoolerStartLogits from transformers.models.bert.modeling_bert import ACT2FN from transformers.file_utils import WEIGHTS_NAME from transformers.activations import get_activation from cocolm.configuration_cocolm import COCOLMConfig from cocolm.convert_state_dict import get_checkpoint_from_transformer_cache logger = logging.getLogger(__name__) try: from apex.normalization.fused_layer_norm import FusedLayerNorm as COCOLMLayerNorm except ImportError: print("Better speed can be achieved with apex installed from https://www.github.com/nvidia/apex.") from torch.nn import LayerNorm as COCOLMLayerNorm COCOLM_PRETRAINED_MODEL_ARCHIVE_MAP = { 'microsoft/cocolm-base': "https://huggingface.co/microsoft/cocolm-base/resolve/main/pytorch_model.bin", 'microsoft/cocolm-large': "https://huggingface.co/microsoft/cocolm-large/resolve/main/pytorch_model.bin", } class COCOLMPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for dowloading and loading pretrained models. """ config_class = COCOLMConfig supported_convert_pretrained_model_archive_map = { "cocolm": COCOLM_PRETRAINED_MODEL_ARCHIVE_MAP, } base_model_prefix = "cocolm" pretrained_model_archive_map = { **COCOLM_PRETRAINED_MODEL_ARCHIVE_MAP, } def _init_weights(self, module): """ Initialize the weights """ if isinstance(module, (nn.Linear, nn.Embedding)): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_( mean=0.0, std=self.config.initializer_range) elif isinstance(module, COCOLMLayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) if isinstance(module, nn.Linear) and module.bias is not None: module.bias.data.zero_() @classmethod def from_pretrained( cls, pretrained_model_name_or_path, reuse_position_embedding=True, drop_parameters=None, *model_args, **kwargs, ): model_type = kwargs.pop('model_type', 'cocolm') if model_type is not None and "state_dict" not in kwargs: if model_type in cls.supported_convert_pretrained_model_archive_map: pretrained_model_archive_map = cls.supported_convert_pretrained_model_archive_map[ model_type] if pretrained_model_name_or_path in pretrained_model_archive_map: state_dict = get_checkpoint_from_transformer_cache( archive_file=pretrained_model_archive_map[pretrained_model_name_or_path], pretrained_model_name_or_path=pretrained_model_name_or_path, pretrained_model_archive_map=pretrained_model_archive_map, cache_dir=kwargs.get("cache_dir", None), force_download=kwargs.get("force_download", None), proxies=kwargs.get("proxies", None), resume_download=kwargs.get("resume_download", None), ) kwargs["state_dict"] = state_dict logger.info("Load HF ckpts") elif os.path.isfile(pretrained_model_name_or_path): state_dict = torch.load( pretrained_model_name_or_path, map_location='cpu') kwargs["state_dict"] = state_dict logger.info("Load local ckpts") elif os.path.isdir(pretrained_model_name_or_path): state_dict = torch.load(os.path.join( pretrained_model_name_or_path, WEIGHTS_NAME), map_location='cpu') kwargs["state_dict"] = state_dict logger.info("Load local ckpts") else: raise RuntimeError( "No pre-trained checkpoint !") if kwargs["state_dict"] is None: logger.info("s2s-ft does't support the model !") raise NotImplementedError() state_dict = kwargs["state_dict"] _k = 'cocolm.embeddings.position_embeddings.weight' if _k in state_dict and "config" in kwargs: config = kwargs["config"] if config.max_position_embeddings > state_dict[_k].shape[0]: logger.info("Resize > position embeddings !") old_vocab_size = state_dict[_k].shape[0] new_postion_embedding = state_dict[_k].data.new_tensor(torch.ones( size=(config.max_position_embeddings, state_dict[_k].shape[1])), dtype=torch.float) new_postion_embedding = nn.Parameter( data=new_postion_embedding, requires_grad=True) new_postion_embedding.data.normal_( mean=0.0, std=config.initializer_range) max_range = config.max_position_embeddings if reuse_position_embedding else old_vocab_size shift = 0 while shift < max_range: delta = min(old_vocab_size, max_range - shift) new_postion_embedding.data[shift: shift + delta, :] = state_dict[_k][:delta, :] logger.info(" CP [%d ~ %d] into [%d ~ %d] " % (0, delta, shift, shift + delta)) shift += delta state_dict[_k] = new_postion_embedding.data del new_postion_embedding elif config.max_position_embeddings < state_dict[_k].shape[0]: logger.info("Resize < position embeddings !") old_vocab_size = state_dict[_k].shape[0] new_postion_embedding = state_dict[_k].data.new_tensor(torch.ones( size=(config.max_position_embeddings, state_dict[_k].shape[1])), dtype=torch.float) new_postion_embedding = nn.Parameter( data=new_postion_embedding, requires_grad=True) new_postion_embedding.data.normal_( mean=0.0, std=config.initializer_range) new_postion_embedding.data.copy_( state_dict[_k][:config.max_position_embeddings, :]) state_dict[_k] = new_postion_embedding.data del new_postion_embedding if drop_parameters is not None: if not isinstance(drop_parameters, list): raise RuntimeError() not_drop_state_dict = {} for key in state_dict: drop_flag = False for prefix in drop_parameters: if key.startswith(prefix): drop_flag = True break if drop_flag: logger.info("Drop %s" % key) else: not_drop_state_dict[key] = state_dict[key] kwargs["state_dict"] = not_drop_state_dict del state_dict if pretrained_model_name_or_path in pretrained_model_archive_map: pretrained_model_name_or_path = pretrained_model_archive_map[pretrained_model_name_or_path] elif not os.path.isfile(pretrained_model_name_or_path): pretrained_model_name_or_path = 'microsoft/cocolm-large' return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) class COCOLMEmbeddings(nn.Module): """Construct the embeddings from word, position and token_type embeddings. """ def __init__(self, config): super(COCOLMEmbeddings, self).__init__() self.word_embeddings = nn.Embedding( config.vocab_size, config.hidden_size, padding_idx=0) fix_word_embedding = getattr(config, "fix_word_embedding", None) if fix_word_embedding: self.word_embeddings.weight.requires_grad = False self.position_embeddings = nn.Embedding( config.max_position_embeddings, config.hidden_size) if config.type_vocab_size > 0: self.token_type_embeddings = nn.Embedding( config.type_vocab_size, config.hidden_size) else: self.token_type_embeddings = None # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load # any TensorFlow checkpoint file self.layer_norm_type = config.layer_norm_type if self.layer_norm_type in ('post',): self.LayerNorm = COCOLMLayerNorm( config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None): if input_ids is not None: input_shape = input_ids.size() else: input_shape = inputs_embeds.size()[:-1] seq_length = input_shape[1] device = input_ids.device if input_ids is not None else inputs_embeds.device if position_ids is None: position_ids = torch.arange( seq_length, dtype=torch.long, device=device) position_ids = position_ids.unsqueeze(0).expand(input_shape) if token_type_ids is None: token_type_ids = torch.zeros( input_shape, dtype=torch.long, device=device) if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids) position_embeddings = self.position_embeddings(position_ids) embeddings = inputs_embeds + position_embeddings if self.token_type_embeddings: embeddings = embeddings + \ self.token_type_embeddings(token_type_ids) if self.layer_norm_type in ('post',): embeddings = self.LayerNorm(embeddings) embeddings = self.dropout(embeddings) return embeddings, position_ids class SelfMultiheadAttention(nn.Module): """Multi-headed attention. See "Attention Is All You Need" for more details. """ def __init__( self, embed_dim, num_heads, dropout=0.0, bias=True, scaling_factor=1, ): super().__init__() self.embed_dim = embed_dim self.num_heads = num_heads self.dropout = nn.Dropout(dropout) self.head_dim = embed_dim // num_heads assert ( self.head_dim * num_heads == self.embed_dim ), "embed_dim must be divisible by num_heads" self.scaling = (self.head_dim * scaling_factor) ** -0.5 self.qk_head_dim = self.head_dim self.in_proj = nn.Linear(embed_dim, embed_dim * 3, bias=bias) self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) def forward( self, query, key_padding_mask, need_weights, attn_mask, attn_bias, before_softmax=False, need_head_weights=False, ): """Input shape: Time x Batch x Channel Args: key_padding_mask (ByteTensor, optional): mask to exclude keys that are pads, of shape `(batch, src_len)`, where padding elements are indicated by 1s. need_weights (bool, optional): return the attention weights, averaged over heads (default: False). attn_mask (ByteTensor, optional): typically used to implement causal attention, where the mask prevents the attention from looking forward in time (default: None). before_softmax (bool, optional): return the raw attention weights and values before the attention softmax. need_head_weights (bool, optional): return the attention weights for each head. Implies *need_weights*. Default: return the average attention weights over all heads. """ if need_head_weights: need_weights = True tgt_len, bsz, embed_dim = query.size() assert embed_dim == self.embed_dim assert list(query.size()) == [tgt_len, bsz, embed_dim] if self.qk_head_dim == self.head_dim: # , self.k_proj(query), self.v_proj(query) q, k, v = self.in_proj(query).chunk(3, dim=-1) else: q, k = self.qk_proj(query).chunk(2, dim=-1) v = self.v_proj(query) q = ( q.contiguous().view(tgt_len, bsz * self.num_heads, self.qk_head_dim) .transpose(0, 1) * self.scaling ) if k is not None: k = ( k.contiguous().view(-1, bsz * self.num_heads, self.qk_head_dim) .transpose(0, 1) ) if v is not None: v = ( v.contiguous().view(-1, bsz * self.num_heads, self.head_dim) .transpose(0, 1) ) assert k is not None src_len = k.size(1) # This is part of a workaround to get around fork/join parallelism # not supporting Optional types. if key_padding_mask is not None and key_padding_mask.dim() == 0: key_padding_mask = None if key_padding_mask is not None: assert key_padding_mask.size(0) == bsz assert key_padding_mask.size(1) == src_len attn_weights = torch.bmm(q, k.transpose(1, 2)) assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len] if attn_mask is not None: attn_mask = attn_mask.unsqueeze(0) attn_weights += attn_mask if key_padding_mask is not None: # don't attend to padding symbols attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) attn_weights.masked_fill_( key_padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool), float("-inf") ) attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) if attn_bias is not None: attn_weights += attn_bias if before_softmax: return attn_weights, v attn_probs = nn.Softmax(dim=-1)(attn_weights) attn_probs = self.dropout(attn_probs) assert v is not None attn = torch.bmm(attn_probs, v) assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.head_dim] attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim) attn = self.out_proj(attn) ret_attn_weights = None if need_weights: ret_attn_weights = attn_weights.view( bsz, self.num_heads, tgt_len, src_len ).transpose(1, 0) if not need_head_weights: # average attention weights over heads ret_attn_weights = attn_weights.mean(dim=0) return attn, ret_attn_weights class COCOLMAttention(nn.Module): def __init__(self, config): super().__init__() self.config = config self.self_attn = SelfMultiheadAttention(config.hidden_size, config.num_attention_heads, dropout=config.attention_probs_dropout_prob) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward(self, x, attention_mask, attn_bias): x = x.transpose(0, 1) residual = x x, attn = self.self_attn(query=x, key_padding_mask=attention_mask, need_weights=True if self.config.output_attentions else False, attn_mask=None, attn_bias=attn_bias) x[x != x] = 0 x = self.dropout(x) x = residual + x x = self.LayerNorm(x) if attn is not None: return (x.transpose(0, 1), ) + attn return (x.transpose(0, 1), ) class COCOLMIntermediate(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states class COCOLMOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.layer_norm_type = config.layer_norm_type if self.layer_norm_type in ('post', 'hybrid'): self.LayerNorm = COCOLMLayerNorm( config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) if self.layer_norm_type == 'pre': return hidden_states + input_tensor elif self.layer_norm_type == 'hybrid': return hidden_states + self.LayerNorm(input_tensor) + input_tensor else: return self.LayerNorm(hidden_states + input_tensor) class COCOLMLayer(nn.Module): def __init__(self, config): super(COCOLMLayer, self).__init__() self.attention = COCOLMAttention(config) if hasattr(config, 'num_ffn_layers') and config.num_ffn_layers > 1: self.num_ffn_layers = config.num_ffn_layers self.intermediate = nn.ModuleList( [COCOLMIntermediate(config) for _ in range(config.num_ffn_layers)]) self.output = nn.ModuleList( [COCOLMOutput(config) for _ in range(config.num_ffn_layers)]) else: self.num_ffn_layers = 0 self.intermediate = COCOLMIntermediate(config) self.output = COCOLMOutput(config) self.layer_norm_type = config.layer_norm_type if self.layer_norm_type in ('pre', 'hybrid'): if self.num_ffn_layers > 0: self.LayerNorm = nn.ModuleList([COCOLMLayerNorm( config.hidden_size, eps=1e-5) for i in range(self.num_ffn_layers)]) else: self.LayerNorm = COCOLMLayerNorm(config.hidden_size, eps=1e-5) def forward(self, hidden_states, attention_mask=None, split_lengths=None, rel_pos=None): self_attention_outputs = self.attention(hidden_states, attention_mask, rel_pos) attention_output = self_attention_outputs[0] if isinstance(self.intermediate, nn.ModuleList): layer_output = attention_output for i, (intermediate_layer, output_layer) in enumerate(zip(self.intermediate, self.output)): if self.layer_norm_type in ('pre', 'hybrid'): _attention_output = self.LayerNorm[i](layer_output) else: _attention_output = layer_output intermediate_output = intermediate_layer(_attention_output) layer_output = output_layer(intermediate_output, layer_output) else: if self.layer_norm_type in ('pre', 'hybrid'): _attention_output = self.LayerNorm(attention_output) else: _attention_output = attention_output intermediate_output = self.intermediate(_attention_output) layer_output = self.output(intermediate_output, attention_output) outputs = (layer_output,) + self_attention_outputs[1:] return outputs class COCOLMEncoder(nn.Module): def __init__(self, config): super(COCOLMEncoder, self).__init__() self.output_attentions = config.output_attentions self.output_hidden_states = config.output_hidden_states self.layer = nn.ModuleList([COCOLMLayer(config) for _ in range(config.num_hidden_layers)]) self.layer_norm_type = config.layer_norm_type if self.layer_norm_type in ('pre', 'hybrid'): self.LayerNorm = COCOLMLayerNorm(config.hidden_size, eps=1e-5) def forward(self, hidden_states, attention_mask=None, split_lengths=None, rel_pos=None): all_hidden_states = () all_attentions = () for i, layer_module in enumerate(self.layer): if self.output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) layer_outputs = layer_module( hidden_states, attention_mask, split_lengths=split_lengths, rel_pos=rel_pos) hidden_states = layer_outputs[0] if (self.layer_norm_type in ('pre', 'hybrid')) and (i == len(self.layer) - 1): # pre-layernorm: apply layernorm for the topmost hidden states hidden_states = self.LayerNorm(hidden_states) if self.output_attentions: all_attentions = all_attentions + (layer_outputs[1],) # Add last layer if self.output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) outputs = (hidden_states,) if self.output_hidden_states: outputs = outputs + (all_hidden_states,) if self.output_attentions: outputs = outputs + (all_attentions,) # last-layer hidden state, (all hidden states), (all attentions) return outputs class COCOLMBinaryPredictions(nn.Module): """Binary prediction module for the main model.""" def __init__(self, config): super().__init__() self.out_proj = nn.Linear(config.hidden_size, 1) self.config = config def forward(self, hidden_states): logits = self.out_proj(hidden_states).squeeze(-1) return logits class COCOLMCLMHead(nn.Module): def __init__(self, config): super(COCOLMCLMHead, self).__init__() # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) self.decoder.bias = self.bias def forward(self, hidden_states): x = self.decoder(hidden_states) return x class COCOLMSCLHead(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = get_activation("gelu") self.LayerNorm = COCOLMLayerNorm( config.hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states): # We "pool" the model by simply taking the hidden state corresponding # to the first token. first_token_tensor = hidden_states[:, 0] pooled_output = self.dense(first_token_tensor) pooled_output = self.activation(pooled_output) pooled_output = self.LayerNorm(pooled_output) return pooled_output def relative_position_bucket(relative_position, num_buckets=32, max_distance=128): sign = torch.sign(relative_position) num_buckets //= 2 n = torch.abs(relative_position) # half of the buckets are for exact increments in positions max_exact = num_buckets // 2 is_small = n < max_exact max_bucket_val = num_buckets - 1 - max_exact # The other half of the buckets are for logarithmically bigger bins in positions up to max_distance val_if_large = max_exact + torch.ceil( torch.log(n.float() / max_exact) / math.log((max_distance - 1) / max_exact) * (max_bucket_val) ).long() val_if_large = torch.min(val_if_large, torch.full_like(val_if_large, num_buckets - 1)) ret = torch.where(is_small, n, val_if_large) * sign return ret class COCOLMModel(COCOLMPreTrainedModel): def __init__(self, config): super(COCOLMModel, self).__init__(config) self.config = config self.embeddings = COCOLMEmbeddings(config) self.encoder = COCOLMEncoder(config) if hasattr(config, 'need_pooler') and getattr(config, 'need_pooler'): self.scl_head = COCOLMSCLHead(config) else: self.scl_head = None if self.config.rel_pos_bins > 0: assert self.config.rel_pos_bins % 2 == 0 self.relative_attention_bias = nn.Embedding(self.config.rel_pos_bins, self.config.num_attention_heads) context_position = torch.arange(self.config.max_position_embeddings, dtype=torch.long)[:, None] memory_position = torch.arange(self.config.max_position_embeddings, dtype=torch.long)[None, :] relative_position = memory_position - context_position self.rp_bucket = relative_position_bucket( relative_position, num_buckets=self.config.rel_pos_bins, max_distance=self.config.max_rel_pos ) self.rp_bucket -= self.rp_bucket.min() def get_rel_pos_bias(self, x): # Assume the input is ordered. If your input token is permuted, you may need to update this accordingly if self.rp_bucket.device != x.device: self.rp_bucket = self.rp_bucket.to(x.device) seq_len = x.size(1) rp_bucket = self.rp_bucket[:seq_len, :seq_len] values = F.embedding(rp_bucket, self.relative_attention_bias.weight) values = values.permute([2, 0, 1]) return values.contiguous() def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, split_lengths=None): if input_ids is not None and inputs_embeds is not None: raise ValueError( "You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_shape = input_ids.size() elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] else: raise ValueError( "You have to specify either input_ids or inputs_embeds") device = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: attention_mask = torch.ones(input_shape, device=device) # Since attention_mask is 1.0 for positions we want to attend and 0.0 for # masked positions, this operation will create a tensor which is 0.0 for # positions we want to attend and -10000.0 for masked positions. # Since we are adding it to the raw scores before the softmax, this is # effectively the same as removing these entirely. extended_attention_mask = attention_mask == 0 embedding_output, position_ids = self.embeddings( input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds) embedding_output = embedding_output * (attention_mask.unsqueeze(-1).type_as(embedding_output)) rel_pos_bias = self.get_rel_pos_bias(input_ids).repeat(input_ids.size(0), 1, 1) if self.config.rel_pos_bins > 0 else None seq_len = input_ids.size(1) if rel_pos_bias is not None and extended_attention_mask is not None: # merge key_padding_mask and attn_mask rel_pos_bias = rel_pos_bias.view(input_ids.size(0), -1, seq_len, seq_len) rel_pos_bias.masked_fill_( extended_attention_mask.unsqueeze(1).unsqueeze(2), float("-inf") ) rel_pos_bias = rel_pos_bias.view(-1, seq_len, seq_len) extended_attention_mask = None encoder_outputs = self.encoder( embedding_output, attention_mask=extended_attention_mask, split_lengths=split_lengths, rel_pos=rel_pos_bias) sequence_output = encoder_outputs[0] # add hidden_states and attentions if they are here outputs = (sequence_output, ) + encoder_outputs[1:] if self.scl_head is None: # sequence_output, pooled_output, (hidden_states), (attentions) return outputs else: pooled_output = self.scl_head(sequence_output) return sequence_output, pooled_output class COCOLMClassificationHead(nn.Module): """Head for sentence-level classification tasks.""" def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.dropout = nn.Dropout(config.cls_dropout_prob) self.out_proj = nn.Linear(config.hidden_size, config.num_labels) def forward(self, features, **kwargs): x = features[:, 0, :] # take <s> token (equiv. to [CLS]) x = self.dropout(x) x = self.dense(x) x = get_activation("gelu")(x) x = self.dropout(x) x = self.out_proj(x) return x class COCOLMForSequenceClassification(COCOLMPreTrainedModel): def __init__(self, config): super().__init__(config) self.config = config self.num_labels = config.num_labels self.cocolm = COCOLMModel(config) self.classifier = COCOLMClassificationHead(config) self.init_weights() def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, labels=None, ): outputs = self.cocolm( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, ) logits = self.classifier(outputs[0]) # add hidden states and attention if they are here outputs = (logits,) + outputs[2:] if labels is not None: if self.num_labels == 1: # We are doing regression loss_fct = nn.MSELoss() loss = loss_fct(logits.view(-1), labels.view(-1)) else: loss_fct = nn.CrossEntropyLoss() loss = loss_fct( logits.view(-1, self.num_labels), labels.view(-1)) outputs = (loss,) + outputs return outputs # (loss), logits, (hidden_states), (attentions) class PoolerLogits(nn.Module): """ Compute SQuAD start logits from sequence hidden states. Args: config (:class:`~transformers.PretrainedConfig`): The config used by the model, will be used to grab the :obj:`hidden_size` of the model. """ def __init__(self, hidden_size): super().__init__() self.dense = nn.Linear(hidden_size, 1) self.dense.weight.data.normal_(mean=0.0, std=0.02) self.dense.bias.data.zero_() def forward( self, hidden_states, p_mask = None ): """ Args: hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, seq_len, hidden_size)`): The final hidden states of the model. p_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, seq_len)`, `optional`): Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token should be masked. Returns: :obj:`torch.FloatTensor`: The start logits for SQuAD. """ x = self.dense(hidden_states).squeeze(-1) if p_mask is not None: x.masked_fill_(p_mask, float('-inf')) return x class SQuADHead(nn.Module): def __init__(self, hidden_size): super().__init__() self.start_logits = PoolerLogits(hidden_size) self.end_logits = PoolerLogits(hidden_size) def forward( self, hidden_states, start_positions=None, end_positions=None, p_mask = None, ): """ Args: hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, seq_len, hidden_size)`): Final hidden states of the model on the sequence tokens. start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Positions of the first token for the labeled span. end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Positions of the last token for the labeled span. is_impossible (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Whether the question has a possible answer in the paragraph or not. p_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, seq_len)`, `optional`): Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token should be masked. Returns: """ start_logits = self.start_logits(hidden_states, p_mask=p_mask) end_logits = self.end_logits(hidden_states, p_mask=p_mask) if start_positions is not None and end_positions is not None: def loss_fct(logits, targets): return F.nll_loss( F.log_softmax( logits.view(-1, logits.size(-1)), dim=-1, dtype=torch.float32, ), targets.view(-1), reduction='sum', ) start_loss = loss_fct(start_logits, start_positions) end_loss = loss_fct(end_logits, end_positions) total_loss = (start_loss + end_loss) * 0.5 return total_loss else: return start_logits, end_logits class COCOLMForQuestionAnswering(COCOLMPreTrainedModel): def __init__(self, config): super(COCOLMForQuestionAnswering, self).__init__(config) self.num_labels = config.num_labels self.cocolm = COCOLMModel(config) self.qa_outputs = SQuADHead(config.hidden_size) self.init_weights() def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, start_positions=None, end_positions=None): outputs = self.cocolm(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds) sequence_output = outputs[0] squad_outputs = self.qa_outputs(sequence_output, start_positions, end_positions) outputs = (squad_outputs,) + outputs[2:] return outputs
COCO-LM/huggingface/cocolm/modeling_cocolm.py/0
{ "file_path": "COCO-LM/huggingface/cocolm/modeling_cocolm.py", "repo_id": "COCO-LM", "token_count": 16630 }
200
--- title: ClimaX template: home.html --- <!-- Welcome to CliMax -->
ClimaX/docs/index.md/0
{ "file_path": "ClimaX/docs/index.md", "repo_id": "ClimaX", "token_count": 26 }
201
# year_strings = [ # '185001010600-187001010000', # '187001010600-189001010000', # '189001010600-191001010000', # '191001010600-193001010000', # '193001010600-195001010000', # '195001010600-197001010000', # '197001010600-199001010000', # '199001010600-201001010000', # '201001010600-201501010000' # ] if config['output_type'] == '6hrPlev': year_strings = [f'{y}01010300-{y+4}12312100' for y in range(1850, 2015, 5)] elif config['output_type'] == 'E3hr': year_strings = [f'{y}01010130-{y+4}12312230' for y in range(1850, 2015, 5)] else: year_strings = [f'{y}01010600-{y+5}01010000' for y in range(1850, 2015, 5)] print(config) #v20190815 rule download: output: "{dataset}/raw/{name}/{name}_{year_str}_raw.nc", shell: "wget {config[server_prefix]}/MPI-M/MPI-ESM1-2-HR/historical/{config[" "run]}/{config[output_type]}/" "{config[cmip_name]}/gn/{config[version]}/" "{config[cmip_name]}_{config[output_type]}_MPI-ESM1-2-HR_historical_{config[run]}_gn_{wildcards.year_str}.nc " "-O {wildcards.dataset}/raw/{config[name]}/{config[name]}_{wildcards.year_str}_raw.nc" # http://esgf-data1.llnl.gov/thredds/fileServer/css03_data/CMIP6/CMIP/MPI-M/MPI-ESM1-2-HR/historical/r1i1p1f1/6hrPlevPt/tas/gn/v20190815/tas_6hrPlevPt_MPI-ESM1-2-HR_historical_r1i1p1f1_gn_185001010600-185501010000.nc # https://esgf.ceda.ac.uk/thredds/fileServer/esg_cmip6/CMIP6/CMIP/MPI-M/MPI-ESM1-2-HR/historical/r1i1p1f1/6hrPlevPt/uas/gn/v20190710/uas_6hrPlevPt_MPI-ESM1-2-HR_historical_r1i1p1f1_gn_185001010600-185501010000.nc rule regrid: input: "{dataset}/raw/{name}/{name}_{year_str}_raw.nc" output: "{dataset}/{res}deg/{name}/{name}_{year_str}_{res}deg.nc.tmp" shell: "python ../../src/data_preprocessing/regrid.py \ --input_fns {input} \ --output_dir {wildcards.dataset}/{wildcards.res}deg/{wildcards.name} \ --ddeg_out {wildcards.res} \ --cmip 1 \ --rename {config[cmip_name]} {config[era_name]} \ --file_ending nc.tmp" rule delete: input: expand("{{dataset}}/{res}deg/{{name}}/{{name}}_{{year_str}}_{res}deg.nc.tmp", res=config['res']), output: expand("{{dataset}}/{res}deg/{{name}}/{{name}}_{{year_str}}_{res}deg.nc", res=config['res']) priority: 100 run: for i, o in zip(input, output): shell("mv {i} {o}") # shell("rm {wildcards.dataset}/raw/{wildcards.name}/{wildcards.name}_{wildcards.year_str}_raw.nc"), rule all: input: expand("{datadir}/{res}deg/{name}/{name}_{year_str}_{res}deg.nc", datadir=config['datadir'], res=config['res'], name=config['name'], year_str=year_strings)
ClimaX/snakemake_configs/MPI-ESM/Snakefile/0
{ "file_path": "ClimaX/snakemake_configs/MPI-ESM/Snakefile", "repo_id": "ClimaX", "token_count": 1520 }
202
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from typing import Any import torch from pytorch_lightning import LightningModule from climax.arch import ClimaX from climax.utils.lr_scheduler import LinearWarmupCosineAnnealingLR from climax.utils.metrics import lat_weighted_mse class PretrainModule(LightningModule): """Lightning module for pretraining the ClimaX model. Args: net (ClimaX): ClimaX model. lr (float, optional): Learning rate. beta_1 (float, optional): Beta 1 for AdamW. beta_2 (float, optional): Beta 2 for AdamW. weight_decay (float, optional): Weight decay for AdamW. warmup_steps (int, optional): Number of warmup steps. max_steps (int, optional): Number of total steps. warmup_start_lr (float, optional): Starting learning rate for warmup. eta_min (float, optional): Minimum learning rate. """ def __init__( self, net: ClimaX, lr: float = 5e-4, beta_1: float = 0.9, beta_2: float = 0.95, weight_decay: float = 1e-5, warmup_steps: int = 10000, max_steps: int = 200000, warmup_start_lr: float = 1e-8, eta_min: float = 1e-8, ): super().__init__() self.save_hyperparameters(logger=False, ignore=["net"]) self.net = net def set_lat_lon(self, lat, lon): self.lat = lat self.lon = lon def training_step(self, batch: Any, batch_idx: int): x, y, lead_times, variables, out_variables = batch loss_dict, _ = self.net.forward(x, y, lead_times, variables, out_variables, [lat_weighted_mse], lat=self.lat) loss_dict = loss_dict[0] for var in loss_dict.keys(): self.log( "train/" + var, loss_dict[var], on_step=True, on_epoch=False, prog_bar=True, ) loss = loss_dict["loss"] return loss def configure_optimizers(self): decay = [] no_decay = [] for name, m in self.named_parameters(): if "var_embed" in name or "pos_embed" in name or "time_pos_embed" in name: no_decay.append(m) else: decay.append(m) optimizer = torch.optim.AdamW( [ { "params": decay, "lr": self.hparams.lr, "betas": (self.hparams.beta_1, self.hparams.beta_2), "weight_decay": self.hparams.weight_decay, }, { "params": no_decay, "lr": self.hparams.lr, "betas": (self.hparams.beta_1, self.hparams.beta_2), "weight_decay": 0, }, ] ) lr_scheduler = LinearWarmupCosineAnnealingLR( optimizer, self.hparams.warmup_steps, self.hparams.max_steps, self.hparams.warmup_start_lr, self.hparams.eta_min, ) scheduler = {"scheduler": lr_scheduler, "interval": "step", "frequency": 1} return {"optimizer": optimizer, "lr_scheduler": scheduler}
ClimaX/src/climax/pretrain/module.py/0
{ "file_path": "ClimaX/src/climax/pretrain/module.py", "repo_id": "ClimaX", "token_count": 1644 }
203
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import torch import torch.nn as nn import torch.nn.functional as F from models.networks.base_network import BaseNetwork from models.networks.normalization import get_nonspade_norm_layer import util.util as util class MultiscaleDiscriminator(BaseNetwork): @staticmethod def modify_commandline_options(parser, is_train): parser.add_argument('--netD_subarch', type=str, default='n_layer', help='architecture of each discriminator') parser.add_argument('--num_D', type=int, default=2, help='number of discriminators to be used in multiscale') opt, _ = parser.parse_known_args() # define properties of each discriminator of the multiscale discriminator subnetD = util.find_class_in_module(opt.netD_subarch + 'discriminator', \ 'models.networks.discriminator') subnetD.modify_commandline_options(parser, is_train) return parser def __init__(self, opt): super().__init__() self.opt = opt for i in range(opt.num_D): subnetD = self.create_single_discriminator(opt) self.add_module('discriminator_%d' % i, subnetD) def create_single_discriminator(self, opt): subarch = opt.netD_subarch if subarch == 'n_layer': netD = NLayerDiscriminator(opt) else: raise ValueError('unrecognized discriminator subarchitecture %s' % subarch) return netD def downsample(self, input): return F.avg_pool2d(input, kernel_size=3, stride=2, padding=[1, 1], count_include_pad=False) def forward(self, input): result = [] get_intermediate_features = not self.opt.no_ganFeat_loss for name, D in self.named_children(): out = D(input) if not get_intermediate_features: out = [out] result.append(out) input = self.downsample(input) return result class NLayerDiscriminator(BaseNetwork): @staticmethod def modify_commandline_options(parser, is_train): parser.add_argument('--n_layers_D', type=int, default=4, help='# layers in each discriminator') return parser def __init__(self, opt): super().__init__() self.opt = opt kw = 4 padw = int((kw - 1.0) / 2) nf = opt.ndf input_nc = self.compute_D_input_nc(opt) norm_layer = get_nonspade_norm_layer(opt, opt.norm_D) sequence = [[nn.Conv2d(input_nc, nf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, False)]] for n in range(1, opt.n_layers_D): nf_prev = nf nf = min(nf * 2, 512) stride = 1 if n == opt.n_layers_D - 1 else 2 if n == opt.n_layers_D - 1: dec = [] nc_dec = nf_prev for _ in range(opt.n_layers_D - 1): dec += [nn.Upsample(scale_factor=2), norm_layer(nn.Conv2d(nc_dec, int(nc_dec//2), kernel_size=3, stride=1, padding=1)), nn.LeakyReLU(0.2, False)] nc_dec = int(nc_dec // 2) dec += [nn.Conv2d(nc_dec, opt.semantic_nc, kernel_size=3, stride=1, padding=1)] self.dec = nn.Sequential(*dec) sequence += [[norm_layer(nn.Conv2d(nf_prev, nf, kernel_size=kw, stride=stride, padding=padw)), nn.LeakyReLU(0.2, False)]] sequence += [[nn.Conv2d(nf, 1, kernel_size=kw, stride=1, padding=padw)]] for n in range(len(sequence)): self.add_module('model' + str(n), nn.Sequential(*sequence[n])) def compute_D_input_nc(self, opt): input_nc = opt.label_nc + opt.output_nc if opt.contain_dontcare_label: input_nc += 1 return input_nc def forward(self, input): results = [input] seg = None cam_logit = None for name, submodel in self.named_children(): if 'model' not in name: continue x = results[-1] intermediate_output = submodel(x) results.append(intermediate_output) get_intermediate_features = not self.opt.no_ganFeat_loss if get_intermediate_features: retu = results[1:] else: retu = results[-1] return retu
CoCosNet-v2/models/networks/discriminator.py/0
{ "file_path": "CoCosNet-v2/models/networks/discriminator.py", "repo_id": "CoCosNet-v2", "token_count": 2207 }
204
# Code Search ## Data Preprocess Both training and validation datasets are created in a way that positive and negative samples are balanced. Negative samples consist of balanced number of instances with randomly replaced NL and PL. We follow the official evaluation metric to calculate the Mean Reciprocal Rank (MRR) for each pair of test data (c, w) over a fixed set of 999 distractor codes. You can use the following command to download the preprocessed training and validation dataset and preprocess the test dataset by yourself. The preprocessed testing dataset is very large, so only the preprocessing script is provided. ```shell mkdir data data/codesearch cd data/codesearch gdown https://drive.google.com/uc?id=1xgSR34XO8xXZg4cZScDYj2eGerBE9iGo unzip codesearch_data.zip rm codesearch_data.zip cd ../../codesearch python process_data.py cd .. ``` ## Fine-Tune We fine-tuned the model on 2*P100 GPUs. ```shell cd codesearch lang=php #fine-tuning a language-specific model for each programming language pretrained_model=microsoft/codebert-base #Roberta: roberta-base python run_classifier.py \ --model_type roberta \ --task_name codesearch \ --do_train \ --do_eval \ --eval_all_checkpoints \ --train_file train.txt \ --dev_file valid.txt \ --max_seq_length 200 \ --per_gpu_train_batch_size 32 \ --per_gpu_eval_batch_size 32 \ --learning_rate 1e-5 \ --num_train_epochs 8 \ --gradient_accumulation_steps 1 \ --overwrite_output_dir \ --data_dir ../data/codesearch/train_valid/$lang \ --output_dir ./models/$lang \ --model_name_or_path $pretrained_model ``` ## Inference and Evaluation Inference ```shell lang=php #programming language idx=0 #test batch idx python run_classifier.py \ --model_type roberta \ --model_name_or_path microsoft/codebert-base \ --task_name codesearch \ --do_predict \ --output_dir ./models/$lang \ --data_dir ../data/codesearch/test/$lang \ --max_seq_length 200 \ --per_gpu_train_batch_size 32 \ --per_gpu_eval_batch_size 32 \ --learning_rate 1e-5 \ --num_train_epochs 8 \ --test_file batch_${idx}.txt \ --pred_model_dir ./models/$lang/checkpoint-best/ \ --test_result_dir ./results/$lang/${idx}_batch_result.txt ``` Evaluation ```shell python mrr.py ```
CodeBERT/CodeBERT/codesearch/README.md/0
{ "file_path": "CodeBERT/CodeBERT/codesearch/README.md", "repo_id": "CodeBERT", "token_count": 732 }
205
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Fine-tuning the library models for language modeling on a text file (GPT, GPT-2, BERT, RoBERTa). GPT and GPT-2 are fine-tuned using a causal language modeling (CLM) loss while BERT and RoBERTa are fine-tuned using a masked language modeling (MLM) loss. """ from __future__ import absolute_import, division, print_function import argparse import logging import os import pickle import random import torch import numpy as np from itertools import cycle import json from model import Model from torch.utils.data import DataLoader, SequentialSampler, RandomSampler,TensorDataset from torch.utils.data.distributed import DistributedSampler from transformers import AdamW, get_linear_schedule_with_warmup, RobertaConfig, RobertaModel, RobertaTokenizer from dataset import TextDataset import torch.multiprocessing torch.multiprocessing.set_sharing_strategy('file_system') logger = logging.getLogger(__name__) def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed) def train(args, train_datasets, eval_dataset, model, tokenizer): """ Train the model """ args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) train_samplers = [RandomSampler(train_dataset) for train_dataset in train_datasets] train_dataloaders = [cycle(DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size,drop_last = True,num_workers = 0)) for train_dataset,train_sampler in zip(train_datasets,train_samplers)] model.to(args.device) if args.local_rank not in [-1, 0]: torch.distributed.barrier() # Prepare optimizer and schedule (linear warmup and decay) no_decay = ['bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay}, {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0} ] optimizer = AdamW(optimizer_grouped_parameters, lr = args.learning_rate, eps = args.adam_epsilon) scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps = args.warmup_steps, num_training_steps = args.max_steps) # use reintialized scheduler and opitmizer actually checkpoint_last = os.path.join(args.output_dir, 'checkpoint-last') scheduler_last = os.path.join(checkpoint_last, 'scheduler.pt') optimizer_last = os.path.join(checkpoint_last, 'optimizer.pt') if os.path.exists(scheduler_last): scheduler.load_state_dict(torch.load(scheduler_last, map_location="cpu")) if os.path.exists(optimizer_last): optimizer.load_state_dict(torch.load(optimizer_last, map_location="cpu")) if args.local_rank == 0: torch.distributed.barrier() # using fp16 to accelerate training if args.fp16: try: from apex import amp except ImportError: raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.") model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level) # multi-gpu training (should be after apex fp16 initialization) if args.n_gpu > 1: model = torch.nn.DataParallel(model) # Distributed training (should be after apex fp16 initialization) if args.local_rank != -1: model = torch.nn.parallel.DistributedDataParallel(model, device_ids = [args.local_rank%args.gpu_per_node], output_device = args.local_rank%args.gpu_per_node, find_unused_parameters = True) # Train! logger.warning("***** Running training *****") logger.warning(" Num examples = %d",sum([len(train_dataset) for train_dataset in train_datasets]) * ( torch.distributed.get_world_size() if args.local_rank != -1 else 1)) logger.warning(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size) logger.warning(" Total train batch size (w. parallel, distributed & accumulation) = %d", args.train_batch_size * args.gradient_accumulation_steps * ( torch.distributed.get_world_size() if args.local_rank != -1 else 1)) logger.warning(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps) logger.warning(" Total optimization steps = %d", args.max_steps) global_step = args.start_step losses, contras_losses, align_losses, dual_losses, step = [], [], [], [], 0 model.zero_grad() set_seed(args) # Added here for reproducibility (even between python 2 and 3) probs = [0.34,0.33,0.33] while True: train_dataloader = np.random.choice(train_dataloaders, 1, p=probs)[0] batch = next(train_dataloader) model.train() step+=1 # forward dual_gen_ids, dual_gen_type_ids =[x.to(args.device) for x in batch] loss, dual_loss, align_loss, contras_loss = model(dual_gen_ids, dual_gen_type_ids) # store loss losses.append(loss.item()) if contras_loss != 0: contras_losses.append(contras_loss) if align_loss != 0: align_losses.append(align_loss) if dual_loss != 0: dual_losses.append(dual_loss) if args.n_gpu > 1: loss = loss.mean() # mean() to average on multi-gpu parallel training # backward if args.gradient_accumulation_steps > 1: loss = loss / args.gradient_accumulation_steps if args.fp16: with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm) else: loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm) # update model if (step + 1) % args.gradient_accumulation_steps == 0: optimizer.step() optimizer.zero_grad() scheduler.step() global_step += 1 if global_step %100 == 0: logger.warning("steps: %s dual: %s", global_step, round(np.mean(dual_losses),3), ) losses, contras_losses, align_losses, dual_losses = [], [], [], [] # evaluate model and save model if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0: checkpoint_prefix = 'checkpoint' results = evaluate(args, model, tokenizer,eval_dataset) for key, value in results.items(): logger.warning(" %s = %s", key, round(value,6)) # Save model checkpoint output_dir = os.path.join(args.output_dir, '{}-{}-{}'.format(checkpoint_prefix, global_step, round(results['loss'], 6))) if not os.path.exists(output_dir): os.makedirs(output_dir) model_to_save = model.module.encoder if hasattr(model,'module') else model.encoder model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) torch.save(args, os.path.join(output_dir, 'training_args.bin')) logger.warning("Saving model checkpoint to %s", output_dir) last_output_dir = os.path.join(args.output_dir, 'checkpoint-last') if not os.path.exists(last_output_dir): os.makedirs(last_output_dir) model_to_save.save_pretrained(last_output_dir) tokenizer.save_pretrained(last_output_dir) idx_file = os.path.join(last_output_dir, 'idx_file.txt') with open(idx_file, 'w', encoding='utf-8') as idxf: idxf.write(str(0) + '\n') torch.save(optimizer.state_dict(), os.path.join(last_output_dir, "optimizer.pt")) torch.save(scheduler.state_dict(), os.path.join(last_output_dir, "scheduler.pt")) logger.warning("Saving optimizer and scheduler states to %s", last_output_dir) step_file = os.path.join(last_output_dir, 'step_file.txt') with open(step_file, 'w', encoding='utf-8') as stepf: stepf.write(str(global_step) + '\n') if args.max_steps > 0 and global_step > args.max_steps: break def evaluate(args, model, tokenizer, eval_dataset,prefix=""): """ Evaluate the model """ eval_output_dir = args.output_dir if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]: os.makedirs(eval_output_dir) args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) eval_dataloader = DataLoader(eval_dataset, sampler = SequentialSampler(eval_dataset), batch_size = args.eval_batch_size, num_workers = 4, drop_last = True) # Eval! logger.warning("***** Running evaluation *****") logger.warning(" Num examples = %d", len(eval_dataset)) logger.warning(" Batch size = %d", args.eval_batch_size) model.eval() losses, contras_losses, align_losses, dual_losses = [], [], [], [] for batch in eval_dataloader: dual_gen_ids, dual_gen_type_ids =[x.to(args.device) for x in batch] with torch.no_grad(): loss, dual_loss, align_loss, contras_loss = model(dual_gen_ids, dual_gen_type_ids) losses.append(loss.item()) if contras_loss != 0: contras_losses.append(contras_loss) if align_loss != 0: align_losses.append(align_loss) if dual_loss != 0: dual_losses.append(dual_loss) result = { "loss": round(np.mean(losses),4), "dual": round(np.mean(dual_losses),4), } return result def main(): parser = argparse.ArgumentParser() ## Required parameters parser.add_argument("--train_data_path", default=None, type=str, required=True, help="The input training data path") parser.add_argument("--another_train_data_path", default=None, type=str, required=True, help="The input training data path") parser.add_argument("--third_train_data_path", default=None, type=str, required=True, help="The input training data path") parser.add_argument("--eval_data_path", default=None, type=str, help="The input evaluating data path") parser.add_argument("--output_dir", default=None, type=str, required=True, help="The output directory where the model predictions and checkpoints will be written.") parser.add_argument("--data_cache_dir", default=None, type=str, required=True, help="The output directory where data cache will be written.") parser.add_argument("--reload_dir", default=None, type=str, help="The directory where the model checkpoints will be reloaded from.") ## Other parameters parser.add_argument("--model_name_or_path", default=None, type=str, help="The model checkpoint for weights initialization.") parser.add_argument("--config_name", default=None, type=str, help="Optional pretrained config name or path if not the same as model_name_or_path") parser.add_argument("--tokenizer_name", default=None, type=str, help="Optional pretrained tokenizer name or path if not the same as model_name_or_path") parser.add_argument("--block_size", default=1024, type=int, help="Optional input sequence length after tokenization." "The training dataset will be truncated in block of this size for training." "Default to the model max input length for single sentence inputs (take into account special tokens).") parser.add_argument("--per_gpu_train_batch_size", default=4, type=int, help="Batch size per GPU/CPU for training.") parser.add_argument("--per_gpu_eval_batch_size", default=4, type=int, help="Batch size per GPU/CPU for evaluation.") parser.add_argument('--gradient_accumulation_steps', type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.") parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.") parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight deay if we apply some.") parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.") parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") parser.add_argument("--max_steps", default=-1, type=int, help="If > 0: set total number of training steps to perform. Override num_train_epochs.") parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.") parser.add_argument('--save_steps', type=int, default=50, help="Save checkpoint every X updates steps.") parser.add_argument('--seed', type=int, default=42, help="random seed for initialization") parser.add_argument('--fp16', action='store_true', help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit") parser.add_argument('--fp16_opt_level', type=str, default='O1', help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html") parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank") parser.add_argument("--node_index", type=int, default=-1, help="For distributed training: local_rank") parser.add_argument("--gpu_per_node", type=int, default=-1, help="For distributed training: local_rank") parser.add_argument('--server_ip', type=str, default='', help="For distant debugging.") parser.add_argument('--server_port', type=str, default='', help="For distant debugging.") args = parser.parse_args() # Setup distant debugging if needed if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print("Waiting for debugger attach") ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True) ptvsd.wait_for_attach() # Setup CUDA, GPU & distributed training if args.local_rank == -1: device = torch.device("cuda" if torch.cuda.is_available() else "cpu") args.n_gpu = torch.cuda.device_count() else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs torch.cuda.set_device(args.local_rank) device = torch.device("cuda", args.local_rank) import datetime torch.distributed.init_process_group(backend='nccl',timeout=datetime.timedelta(0,1800000)) args.local_rank+=args.node_index*args.gpu_per_node args.n_gpu = 1 args.device = device # Setup logging logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO if args.local_rank in [-1, 0] else logging.INFO) #logging.WARN if args.local_rank not in [-1, 0]: torch.distributed.barrier() args.log_file = os.path.join(args.output_dir, 'log.txt') if not os.path.exists(args.output_dir): os.makedirs(args.output_dir) if os.path.exists(args.log_file): logfile = logging.FileHandler(args.log_file, 'a') else: logfile = logging.FileHandler(args.log_file, 'w') fmt = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', '%m/%d/%Y %H:%M:%S %p') logfile.setFormatter(fmt) logger.addHandler(logfile) if args.local_rank == 0: torch.distributed.barrier() logger.warning("Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", args.local_rank, device, args.n_gpu, bool(args.local_rank != -1), args.fp16) # Set seed set_seed(args) # Load pretrained model and tokenizer if args.local_rank not in [-1, 0]: torch.distributed.barrier() args.start_step = 0 model_name_or_path = args.model_name_or_path tokenizer = RobertaTokenizer.from_pretrained(model_name_or_path if args.tokenizer_name is None else args.tokenizer_name) config = RobertaConfig.from_pretrained(model_name_or_path if args.config_name is None else args.config_name) model = RobertaModel.from_pretrained(model_name_or_path,config=config) # add special tokens special_tokens_list = ['<line>','<state>','</state>','<dictsep>','<output>','<function>','<singleline>','<tutorial>','<codenet>','<indent>','<dedent>'] for i in range(200): special_tokens_list.append('<' + str(i) + '>') special_tokens_dict = {'additional_special_tokens': special_tokens_list} tokenizer.add_special_tokens(special_tokens_dict) model.resize_token_embeddings(len(tokenizer)) model = Model(model,config,tokenizer,args) if args.local_rank == 0: torch.distributed.barrier() logger.warning("Training/evaluation parameters %s", args) if args.local_rank == -1: local_rank = 0 world_size = 1 else: local_rank = args.local_rank world_size = torch.distributed.get_world_size() # reload and preprocess data train_datasets = [] train_datasets.append(TextDataset(tokenizer, args, args.train_data_path, local_rank, world_size, logger, "train", prefix="codenet")) train_datasets.append(TextDataset(tokenizer, args, args.another_train_data_path, local_rank, world_size, logger, "train", prefix="tutorial")) train_datasets.append(TextDataset(tokenizer, args, args.third_train_data_path, local_rank, world_size, logger, "train", prefix="singleline")) eval_dataset = TextDataset(tokenizer, args, args.eval_data_path, local_rank, world_size, logger, "eval","codenet") # Training train(args, train_datasets, eval_dataset, model, tokenizer) if __name__ == "__main__": main()
CodeBERT/CodeExecutor/pretrain/run.py/0
{ "file_path": "CodeBERT/CodeExecutor/pretrain/run.py", "repo_id": "CodeBERT", "token_count": 8982 }
206
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from evaluator.CodeBLEU.parser import DFG_python, DFG_java, DFG_ruby, DFG_go, DFG_php, DFG_javascript, DFG_csharp from evaluator.CodeBLEU.parser import (remove_comments_and_docstrings, tree_to_token_index, index_to_code_token, tree_to_variable_index) from tree_sitter import Language, Parser import os root_dir = os.path.dirname(__file__) dfg_function = { 'python': DFG_python, 'java': DFG_java, 'ruby': DFG_ruby, 'go': DFG_go, 'php': DFG_php, 'javascript': DFG_javascript, 'c_sharp': DFG_csharp, } def calc_syntax_match(references, candidate, lang): return corpus_syntax_match([references], [candidate], lang) def corpus_syntax_match(references, candidates, lang): JAVA_LANGUAGE = Language(root_dir + '/parser/my-languages.so', lang) parser = Parser() parser.set_language(JAVA_LANGUAGE) match_count = 0 total_count = 0 for i in range(len(candidates)): references_sample = references[i] candidate = candidates[i] for reference in references_sample: try: candidate = remove_comments_and_docstrings(candidate, 'java') except: pass try: reference = remove_comments_and_docstrings(reference, 'java') except: pass candidate_tree = parser.parse(bytes(candidate, 'utf8')).root_node reference_tree = parser.parse(bytes(reference, 'utf8')).root_node def get_all_sub_trees(root_node): node_stack = [] sub_tree_sexp_list = [] depth = 1 node_stack.append([root_node, depth]) while len(node_stack) != 0: cur_node, cur_depth = node_stack.pop() sub_tree_sexp_list.append([cur_node.sexp(), cur_depth]) for child_node in cur_node.children: if len(child_node.children) != 0: depth = cur_depth + 1 node_stack.append([child_node, depth]) return sub_tree_sexp_list cand_sexps = [x[0] for x in get_all_sub_trees(candidate_tree)] ref_sexps = get_all_sub_trees(reference_tree) # print(cand_sexps) # print(ref_sexps) for sub_tree, depth in ref_sexps: if sub_tree in cand_sexps: match_count += 1 total_count += len(ref_sexps) score = match_count / total_count return score
CodeBERT/CodeReviewer/code/evaluator/CodeBLEU/syntax_match.py/0
{ "file_path": "CodeBERT/CodeReviewer/code/evaluator/CodeBLEU/syntax_match.py", "repo_id": "CodeBERT", "token_count": 1383 }
207
pip install torch==1.9.0+cu111 torchvision==0.10.0+cu111 torchaudio==0.9.0 -f https://download.pytorch.org/whl/torch_stable.html pip install --upgrade scipy transformers tqdm fuzzywuzzy tree_sitter datasets lang=$1 #programming language lr=2e-4 batch_size=16 beam_size=5 source_length=3968 target_length=128 global_length=64 window_size=512 output_dir=saved_models/$1 epochs=10 pretrained_model=microsoft/longcoder-base mkdir -p $output_dir python run.py \ --do_train \ --do_eval \ --lang $1 \ --output_dir $output_dir \ --model_name_or_path $pretrained_model \ --filename microsoft/LCC_$1 \ --max_source_length $source_length \ --max_target_length $target_length \ --max_global_length $global_length \ --window_size $window_size \ --beam_size $beam_size \ --train_batch_size $batch_size \ --eval_batch_size $batch_size \ --learning_rate $lr \ --num_train_epochs $epochs 2>&1| tee $output_dir/train.log reload_model=$output_dir/checkpoint-best-acc/model.bin python run.py \ --do_test \ --lang $1 \ --load_model_path $reload_model \ --model_name_or_path $pretrained_model \ --filename microsoft/LCC_$1 \ --output_dir $output_dir \ --max_source_length $source_length \ --max_target_length $target_length \ --max_global_length $global_length \ --window_size $window_size \ --beam_size $beam_size \ --train_batch_size $batch_size \ --eval_batch_size $batch_size \ --learning_rate $lr \ --num_train_epochs $epochs 2>&1| tee $output_dir/test.log
CodeBERT/LongCoder/run.sh/0
{ "file_path": "CodeBERT/LongCoder/run.sh", "repo_id": "CodeBERT", "token_count": 555 }
208
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Fine-tuning the library models for language modeling on a text file (GPT, GPT-2, BERT, RoBERTa). GPT and GPT-2 are fine-tuned using a causal language modeling (CLM) loss while BERT and RoBERTa are fine-tuned using a masked language modeling (MLM) loss. """ from __future__ import absolute_import import os import sys import pickle import torch import json import random import logging import argparse import numpy as np from io import open from itertools import cycle import torch.nn as nn from model import Seq2Seq from tqdm import tqdm, trange from torch.utils.data import DataLoader, Dataset, SequentialSampler, RandomSampler,TensorDataset from torch.utils.data.distributed import DistributedSampler from tqdm import tqdm from fuzzywuzzy import fuzz import re import multiprocessing from transformers import (WEIGHTS_NAME, AdamW, get_linear_schedule_with_warmup, RobertaConfig, RobertaModel, RobertaTokenizer) cpu_cont = 16 logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt = '%m/%d/%Y %H:%M:%S', level = logging.INFO) logger = logging.getLogger(__name__) class Example(object): """A single training/test example.""" def __init__(self, idx, source, target, ): self.idx = idx self.source = source self.target = target def read_examples(filename): """Read examples from filename.""" examples=[] lang = filename.split("/")[-2] with open(filename,encoding="utf-8") as f: for idx, line in enumerate(f): if ".txt" in filename: inputs=line.strip().replace("<EOL>","</s>").split() inputs=inputs[1:] inputs=" ".join(inputs) outputs=[] else: js=json.loads(line) inputs=js["input"].replace("<EOL>","</s>").split() inputs=inputs[1:] inputs=" ".join(inputs) outputs=js["gt"] if 'id' in js: idx = js['id'] examples.append( Example( idx = idx, source = inputs, target = outputs, ) ) return examples class InputFeatures(object): """A single training/test features for a example.""" def __init__(self, example_id, source_ids, ): self.example_id = example_id self.source_ids = source_ids def post_process(code): code = code.replace("<string","<STR_LIT").replace("<number","<NUM_LIT").replace("<char","<CHAR_LIT") code = code.replace("<NUM_LIT>", "0").replace("<STR_LIT>", "").replace("<CHAR_LIT>", "") pattern = re.compile(r"<(STR|NUM|CHAR)_LIT:(.*?)>", re.S) lits = re.findall(pattern, code) for lit in lits: code = code.replace(f"<{lit[0]}_LIT:{lit[1]}>", lit[1]) return code def tokenize(item): source, max_length, tokenizer = item source_tokens = [x for x in tokenizer.tokenize(source) if x!='\u0120'] source_tokens = ["<s>","<decoder-only>","</s>"]+source_tokens[-(max_length-3):] source_ids = tokenizer.convert_tokens_to_ids(source_tokens) padding_length = max_length - len(source_ids) source_ids+=[tokenizer.pad_token_id]*padding_length return source_tokens,source_ids def convert_examples_to_features(examples, tokenizer, args,pool=None,stage=None): features = [] if stage=="train": max_length = args.max_source_length+args.max_target_length else: max_length = args.max_source_length sources = [(x.source,max_length,tokenizer) for x in examples] if pool is not None: tokenize_tokens = pool.map(tokenize,tqdm(sources,total=len(sources))) else: tokenize_tokens = [tokenize(x) for x in sources] for example_index, (source_tokens,source_ids) in enumerate(tokenize_tokens): #source if example_index < 5: if stage=='train': logger.info("*** Example ***") logger.info("idx: {}".format(example_index)) logger.info("source_tokens: {}".format([x.replace('\u0120','_') for x in source_tokens])) logger.info("source_ids: {}".format(' '.join(map(str, source_ids)))) features.append( InputFeatures( example_index, source_ids, ) ) return features def set_seed(seed=42): random.seed(seed) os.environ['PYHTONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True def main(): parser = argparse.ArgumentParser() ## Required parameters parser.add_argument("--model_name_or_path", default=None, type=str, required=True, help="Path to pre-trained model: e.g. roberta-base" ) parser.add_argument("--output_dir", default=None, type=str, required=True, help="The output directory where the model predictions and checkpoints will be written.") parser.add_argument("--load_model_path", default=None, type=str, help="Path to trained model: Should contain the .bin files" ) ## Other parameters parser.add_argument("--train_filename", default=None, type=str, help="The train filename. Should contain the .jsonl files for this task.") parser.add_argument("--dev_filename", default=None, type=str, help="The dev filename. Should contain the .jsonl files for this task.") parser.add_argument("--test_filename", default=None, type=str, help="The test filename. Should contain the .jsonl files for this task.") parser.add_argument("--lang", default="python", type=str, help="Source language") parser.add_argument("--config_name", default="", type=str, help="Pretrained config name or path if not the same as model_name") parser.add_argument("--tokenizer_name", default="", type=str, help="Pretrained tokenizer name or path if not the same as model_name") parser.add_argument("--max_source_length", default=64, type=int, help="The maximum total source sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded.") parser.add_argument("--max_target_length", default=32, type=int, help="The maximum total target sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded.") parser.add_argument("--do_train", action='store_true', help="Whether to run training.") parser.add_argument("--do_eval", action='store_true', help="Whether to run eval on the dev set.") parser.add_argument("--do_test", action='store_true', help="Whether to run eval on the dev set.") parser.add_argument("--do_lower_case", action='store_true', help="Set this flag if you are using an uncased model.") parser.add_argument("--no_cuda", action='store_true', help="Avoid using CUDA when available") parser.add_argument("--train_batch_size", default=8, type=int, help="Batch size per GPU/CPU for training.") parser.add_argument("--eval_batch_size", default=8, type=int, help="Batch size per GPU/CPU for evaluation.") parser.add_argument('--gradient_accumulation_steps', type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.") parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.") parser.add_argument("--beam_size", default=10, type=int, help="beam size for beam search") parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight deay if we apply some.") parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.") parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") parser.add_argument("--num_train_epochs", default=3, type=int, help="Total number of training epochs to perform.") parser.add_argument("--max_steps", default=-1, type=int, help="If > 0: set total number of training steps to perform. Override num_train_epochs.") parser.add_argument("--eval_steps", default=-1, type=int, help="") parser.add_argument("--train_steps", default=-1, type=int, help="") parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.") parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank") parser.add_argument('--seed', type=int, default=42, help="random seed for initialization") pool = multiprocessing.Pool(cpu_cont) # print arguments args = parser.parse_args() logger.info(args) # Setup CUDA, GPU device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu") args.n_gpu = torch.cuda.device_count() logger.warning("Process rank: %s, device: %s, n_gpu: %s", args.local_rank, device, args.n_gpu) args.device = device # Set seed set_seed(args.seed) # make dir if output_dir not exist if os.path.exists(args.output_dir) is False: os.makedirs(args.output_dir) config =RobertaConfig.from_pretrained(args.model_name_or_path) config.is_decoder = True tokenizer = RobertaTokenizer.from_pretrained(args.model_name_or_path) #budild model encoder = RobertaModel.from_pretrained(args.model_name_or_path,config=config) if args.lang == "python": eos_ids = [tokenizer.sep_token_id] else: eos_ids = [tokenizer.convert_tokens_to_ids('Ġ;'), tokenizer.convert_tokens_to_ids('Ġ}'), tokenizer.convert_tokens_to_ids('Ġ{')] model=Seq2Seq(encoder=encoder,decoder=encoder,config=config, beam_size=args.beam_size,max_length=args.max_target_length, sos_id=tokenizer.cls_token_id,eos_id=eos_ids) if args.load_model_path is not None: logger.info("reload model from {}".format(args.load_model_path)) model.load_state_dict(torch.load(args.load_model_path)) model.to(device) if args.local_rank != -1: # Distributed training try: from apex.parallel import DistributedDataParallel as DDP except ImportError: raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.") model = DDP(model) elif args.n_gpu > 1: # multi-gpu training model = torch.nn.DataParallel(model) if args.do_train: # Prepare training data loader train_examples = read_examples(args.train_filename) train_features = convert_examples_to_features(train_examples, tokenizer,args, pool, stage='train') all_source_ids = torch.tensor([f.source_ids for f in train_features], dtype=torch.long) train_data = TensorDataset(all_source_ids) if args.local_rank == -1: train_sampler = RandomSampler(train_data) else: train_sampler = DistributedSampler(train_data) train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size//args.gradient_accumulation_steps) num_train_optimization_steps = args.train_steps # Prepare optimizer and schedule (linear warmup and decay) no_decay = ['bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay}, {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0} ] optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=int(len(train_dataloader)*args.num_train_epochs*0.1), num_training_steps=len(train_dataloader)*args.num_train_epochs) #Start training logger.info("***** Running training *****") logger.info(" Num examples = %d", len(train_examples)) logger.info(" Batch size = %d", args.train_batch_size) logger.info(" Step per epoch = %d", len(train_examples)//args.train_batch_size) logger.info(" Num epoch = %d", args.num_train_epochs) model.train() dev_dataset={} nb_tr_examples, nb_tr_steps,tr_loss,global_step,best_acc,best_loss = 0, 0,0,0,0,1e6 losses = [] for epoch in range(args.num_train_epochs): for idx,batch in enumerate(train_dataloader): batch = tuple(t.to(device) for t in batch) source_ids = batch[0] loss,_,_ = model(source_ids,True) if args.n_gpu > 1: loss = loss.mean() # mean() to average on multi-gpu. losses.append(loss.item()) if args.gradient_accumulation_steps > 1: loss = loss / args.gradient_accumulation_steps tr_loss += loss.item() train_loss=round(tr_loss*args.gradient_accumulation_steps/(nb_tr_steps+1),4) if (idx+1)%100==0: logger.info("epoch {} step {} loss {}".format(epoch,idx+1,round(np.mean(losses[-100:]),4))) nb_tr_examples += source_ids.size(0) nb_tr_steps += 1 loss.backward() if (nb_tr_steps + 1) % args.gradient_accumulation_steps == 0: #Update parameters optimizer.step() optimizer.zero_grad() scheduler.step() global_step += 1 if args.do_eval: #Eval model with dev dataset tr_loss = 0 nb_tr_examples, nb_tr_steps = 0, 0 eval_flag=False eval_examples = read_examples(args.dev_filename.replace(".json",".txt")) eval_features = convert_examples_to_features(eval_examples, tokenizer, args,stage='dev') all_source_ids = torch.tensor([f.source_ids for f in eval_features], dtype=torch.long) eval_data = TensorDataset(all_source_ids) eval_sampler = SequentialSampler(eval_data) eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size) logger.info("***** Running evaluation *****") logger.info(" Num examples = %d", len(eval_examples)) logger.info(" Batch size = %d", args.eval_batch_size) model.eval() dev_losses = [] for batch in eval_dataloader: batch = tuple(t.to(device) for t in batch) source_ids = batch[0] with torch.no_grad(): loss,_,_ = model(source_ids,True) if args.n_gpu > 1: loss = loss.mean() # mean() to average on multi-gpu. dev_losses.append(loss.item()) eval_examples = read_examples(args.dev_filename) eval_features = convert_examples_to_features(eval_examples, tokenizer, args,stage='dev') all_source_ids = torch.tensor([f.source_ids for f in eval_features], dtype=torch.long) eval_data = TensorDataset(all_source_ids) eval_sampler = SequentialSampler(eval_data) eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size) logger.info(" Num examples = %d", len(eval_examples)) logger.info(" Batch size = %d", args.eval_batch_size) p=[] for batch in eval_dataloader: batch = tuple(t.to(device) for t in batch) source_ids = batch[0] with torch.no_grad(): preds = model(source_ids=source_ids) for pred in preds: t=pred[0].cpu().numpy() t=list(t) if 0 in t: t=t[:t.index(0)] text = tokenizer.decode(t,clean_up_tokenization_spaces=False) if args.lang == "java" and "{" in text: text = text[:text.index("{")] if args.lang == "python" and "</s>" in text: text = text[:text.index("</s>")] p.append(text) model.train() EM = 0.0 edit_sim = 0.0 total = len(p) for ref,gold in zip(p,eval_examples): pred = post_process(ref.strip()) gt = post_process(gold.target) edit_sim += fuzz.ratio(pred, gt) if pred.split() == gt.split(): EM += 1 dev_acc = round(EM/total*100, 2) logger.info(" %s = %s "%("loss",round(np.mean(dev_losses),4))) logger.info(" %s = %s "%("Acc",str(dev_acc))) logger.info(" %s = %s "%("Edit sim",str(round(edit_sim/total, 2)))) logger.info(" "+"*"*20) if dev_acc>best_acc: logger.info(" Best acc:%s",dev_acc) logger.info(" "+"*"*20) best_acc=dev_acc # Save best checkpoint for best bleu output_dir = os.path.join(args.output_dir, 'checkpoint-best-acc') if not os.path.exists(output_dir): os.makedirs(output_dir) model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self output_model_file = os.path.join(output_dir, "pytorch_model.bin") torch.save(model_to_save.state_dict(), output_model_file) if args.do_test: files=[] if args.test_filename is not None: files.append(args.test_filename) for idx,file in enumerate(files): logger.info("Test file: {}".format(file)) eval_examples = read_examples(file) eval_features = convert_examples_to_features(eval_examples, tokenizer, args,stage='test') all_source_ids = torch.tensor([f.source_ids for f in eval_features], dtype=torch.long) eval_data = TensorDataset(all_source_ids) # Calculate bleu eval_sampler = SequentialSampler(eval_data) eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size) model.eval() p=[] for batch in tqdm(eval_dataloader,total=len(eval_dataloader)): batch = tuple(t.to(device) for t in batch) source_ids = batch[0] with torch.no_grad(): preds = model(source_ids=source_ids) for pred in preds: t=pred[0].cpu().numpy() t=list(t) if 0 in t: t=t[:t.index(0)] text = tokenizer.decode(t,clean_up_tokenization_spaces=False) if args.lang == "java" and "{" in text: text = text[:text.index("{")] if args.lang == "python" and "</s>" in text: text = text[:text.index("</s>")] p.append(text) model.train() EM = 0.0 edit_sim = 0.0 total = len(p) with open(os.path.join(args.output_dir, 'predictions.txt'),"w") as f: for ref,gold in zip(p,eval_examples): pred = post_process(ref.strip()) gt = post_process(gold.target) edit_sim += fuzz.ratio(pred, gt) if pred.split() == gt.split(): EM += 1 f.write(ref.strip()+"\n") dev_acc = round(EM/total*100, 2) logger.info(" %s = %s "%("Acc",str(dev_acc))) logger.info(" %s = %s "%("Edit sim",str(round(edit_sim/total, 2)))) if __name__ == "__main__": main()
CodeBERT/UniXcoder/downstream-tasks/code-completion/run.py/0
{ "file_path": "CodeBERT/UniXcoder/downstream-tasks/code-completion/run.py", "repo_id": "CodeBERT", "token_count": 11216 }
209
# CodeT: Code Generation with Generated Tests # Overview In the paper, we present **CodeT** (for **Code** Generation with Generated **T**ests), a simple yet effective approach to empower large pre-trained language models for code generation, which could achieve surprising improvements over previous methods. For example, we improve the pass@1 on HumanEval to 65.8%, an increase of absolute 18.8% on the OpenAI *code-davinci-002* model, and an absolute 20+% improvement over previous state-of-the-art results. ![Fig1](./figs/illustration.jpg) <center>Fig 1. The illustration of CodeT. Both the code solutions and the test cases are generated by the pre-trained language model. The best code solution is then selected by a dual execution agreement.</center> ![Fig2](./figs/preliminary.jpg) <center>Fig 2. Code generation and test case generation: an example from the HumanEval benchmark. (Example input-output cases are removed from the context.)</center> CodeT leverages large language models to generate both the code solutions and the test cases. We believe a solution could get support from both the test cases and the other solutions. The more test cases a solution can pass, and the more test-driven siblings the solution has, the better the solution is. Hence, We execute the code solutions using the test cases and chooses the best solution based on such dual execution agreement. ## Project This project contains the basic components of CodeT and a main entry point, here is an overview: ```shell |-- main.py # the main entry point to use CodeT |-- src |-- postprocess.py # handle code solution and test case post-processing |-- _execution.py # perform execution with the given code solutions and test cases |-- execution.py # wrapper of the execution process |-- agreement.py # perform dual execution agreement of CodeT |-- evaluation.py # calculate pass@k results for baseline and CodeT |-- io_utils.py # simple utils for file reading/writing |-- data |-- dataset # contains the input data for code solution and test case generation |-- HumanEval_for_code_generation.jsonl |-- HumanEval_for_test_case_generation.jsonl |-- MBPP_sanitized_for_code_generation.jsonl |-- MBPP_sanitized_for_test_case_generation.jsonl |-- APPS_zeroshot_for_code_generation.zip |-- APPS_zeroshot_for_test_case_generation.jsonl |-- CodeContests_zeroshot_for_code_generation.jsonl |-- CodeContests_zeroshot_for_test_case_generation.jsonl |-- generated_data # contains the output data by pre-trained language models |-- HumanEval_codegen16B_temp0.8_topp0.95_num100_max300_code_solution.jsonl |-- HumanEval_codegen16B_temp0.8_topp0.95_num100_max300_test_case.jsonl |-- HumanEval_davinci002_temp0.8_topp0.95_num100_max300_code_solution.jsonl |-- HumanEval_davinci002_temp0.8_topp0.95_num100_max300_test_case.jsonl |-- HumanEval_incoder6B_temp0.8_topp0.95_num100_max300_code_solution.jsonl |-- HumanEval_incoder6B_temp0.8_topp0.95_num100_max300_test_case.jsonl |-- MBPP_codegen16B_temp0.8_topp0.95_num100_max300_code_solution.jsonl |-- MBPP_codegen16B_temp0.8_topp0.95_num100_max300_test_case.jsonl |-- MBPP_davinci002_temp0.8_topp0.95_num100_max300_code_solution.jsonl |-- MBPP_davinci002_temp0.8_topp0.95_num100_max300_test_case.jsonl |-- MBPP_incoder6B_temp0.8_topp0.95_num100_max300_code_solution.jsonl |-- MBPP_incoder6B_temp0.8_topp0.95_num100_max300_test_case.jsonl |-- APPS_zeroshot_davinci002_temp0.8_topp0.95_num50_max300_code_solution.zip |-- APPS_zeroshot_davinci002_temp0.8_topp0.95_num50_max300_test_case.zip |-- CodeContests_zeroshot_davinci002_temp0.8_topp0.95_num50_max300_test_case.jsonl |-- CodeContests_zeroshot_davinci002_temp0.8_topp0.95_num1000_max300_code_solution.zip ``` # Quickstart ## Prepare Environment First, you should set up a python environment. This code base has been tested under python 3.7. After installing python 3.7, we strongly recommend you to use `virtualenv` to manage the python environment. You could use following commands to create an environment `venv` and activate it. ```bash $ python3.7 -m venv venv $ source venv/bin/activate $ pip install -r requirements.txt ``` ## Prepare Data First, you can find our processed HumanEval and MBPP benchmarks in the `data/dataset` directory, including the data for code solution and test case generation. Then you may reproduce the results of InCoder and CodeGen on the HumanEval benchmark using the data we provide in the `data/generated_data` directory. Or you can feed the input data to the code generation models (e.g. [CodeGen](https://github.com/salesforce/CodeGen) and [InCoder](https://github.com/dpfried/incoder)) to generate code solutions and test cases. Here is an example of the HumanEval benchmark: ```json { "task_id": "HumanEval/23", "prompt": "\n\ndef strlen(string: str) -> int:\n \"\"\" Return length of given string\n \"\"\"\n", "entry_point": "strlen", "canonical_solution": " return len(string)\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate('') == 0\n assert candidate('x') == 1\n assert candidate('asdasnakj') == 9\n" } ``` And the model output should look like this: ```json { "prompt": "\n\ndef strlen(string: str) -> int:\n \"\"\" Return length of given string\n \"\"\"\n", "samples": [" length = 0\n for char in string:\n length += 1\n return length\n\n", " count = 0\n for _ in string:\n count += 1\n return count\n\n", " return len(string)\n", " length = 0\n for _ in string:\n length += 1\n return length\n"] } ``` ## Use CodeT You may use the script `main.py` to run CodeT, which automatically performs post-processing, dual execution agreement, and pass@k evaluation. Before running the script, you need to specify several arguments: ```bash python main.py --source_path_for_solution PATH_1 # model input file in .jsonl format --predict_path_for_solution PATH_2 # model output file in .jsonl format --source_path_for_test PATH_3 # model input file in .jsonl format --predict_path_for_test PATH_4 # model output file in .jsonl format --cache_dir PATH_5 # the directory to store the cache files (execution results) --timeout NUMBER # how many seconds to wait during execution for each test case (default 0.1) --test_case_limit NUMBER # first n test cases per sample (default 5) ``` # Citation If our work is useful for you, please consider citing our paper: ```bibtex @misc{https://doi.org/10.48550/arxiv.2207.10397, doi = {10.48550/ARXIV.2207.10397}, url = {https://arxiv.org/abs/2207.10397}, author = {Chen, Bei and Zhang, Fengji and Nguyen, Anh and Zan, Daoguang and Lin, Zeqi and Lou, Jian-Guang and Chen, Weizhu}, keywords = {Computation and Language (cs.CL), Artificial Intelligence (cs.AI), Programming Languages (cs.PL), Software Engineering (cs.SE), FOS: Computer and information sciences, FOS: Computer and information sciences}, title = {CodeT: Code Generation with Generated Tests}, publisher = {arXiv}, year = {2022}, copyright = {arXiv.org perpetual, non-exclusive license} } ``` # Contributing This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments. # License Please note that this repo is under [MIT License](LICENSE). # Trademarks This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow [Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general). Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.
CodeT/CodeT/README.md/0
{ "file_path": "CodeT/CodeT/README.md", "repo_id": "CodeT", "token_count": 2949 }
210
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from collections import defaultdict, Counter import logging import math logging.basicConfig( format="SystemLog: [%(asctime)s][%(name)s][%(levelname)s] - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO, ) logger = logging.getLogger(__name__) class DataManager: def __init__(self, dual_exec_results, sampled_code_by_task, sampled_test_case_by_task, limit): logger.info('handling dual exec results') self.dual_exec_results = dual_exec_results self.sampled_code_by_task = sampled_code_by_task self.sampled_test_case_by_task = sampled_test_case_by_task self.limit = limit self.solution_frequency_by_task = defaultdict(Counter) self.test_case_frequency_by_task = dict() self.passed_unique_solutions_by_task = defaultdict(set) self.passed_unique_test_cases_by_task = defaultdict(set) self.passed_solution_test_case_pairs_by_task = defaultdict(set) self.solution_string_to_id_range_by_task = dict() self.test_case_string_to_id_range_by_task = dict() self.solution_id_to_string_by_task = dict() self.test_case_id_to_string_by_task = dict() self.expanded_passed_solution_test_case_pairs_by_task = defaultdict(list) self._get_solution_frequency() logger.info('got solution frequency') self._get_test_case_frequency() logger.info('got test case frequency') self._get_passed_solution_test_case_pairs_by_task() logger.info('got passed solution test case pairs by task') self._get_solution_and_test_case_ids() logger.info('got solution and test case ids') self._get_expanded_dual_exec_result() logger.info('got expanded dual exec results') def _get_solution_frequency(self): for sample in self.sampled_code_by_task: task_id = sample['task_id'] completion = sample['completion'] self.solution_frequency_by_task[task_id][completion] += 1 def _get_test_case_frequency(self): for task_id in self.sampled_test_case_by_task.keys(): task_test_cases = [ cases_per_sample[:self.limit] for cases_per_sample in self.sampled_test_case_by_task[task_id] ] task_test_cases = sum(task_test_cases, []) self.test_case_frequency_by_task[task_id] = Counter(task_test_cases) def _get_passed_solution_test_case_pairs_by_task(self): for result in self.dual_exec_results: if not result['passed']: continue for idx, test_case in enumerate(result['test_cases']): if result['result'][idx] != True: continue if test_case not in self.test_case_frequency_by_task[result['task_id']]: continue self.passed_solution_test_case_pairs_by_task[result['task_id']].add((result['completion'], test_case)) self.passed_unique_solutions_by_task[result['task_id']].add(result['completion']) self.passed_unique_test_cases_by_task[result['task_id']].add(test_case) def _build_string_to_id_range(self, frequency_dict, limited_values): id_ranges = dict() start_id = 0 for key, value in frequency_dict.items(): if key not in limited_values: continue id_ranges[key] = range(start_id, start_id + value) start_id += value return id_ranges def _build_id_to_string(self, str_to_id_range): id_to_string = dict() for string in str_to_id_range.keys(): for idx in str_to_id_range[string]: id_to_string[idx] = string return id_to_string def _get_solution_and_test_case_ids(self): for task_id in self.solution_frequency_by_task.keys(): self.solution_string_to_id_range_by_task[task_id] = self._build_string_to_id_range(self.solution_frequency_by_task[task_id], self.passed_unique_solutions_by_task[task_id]) self.test_case_string_to_id_range_by_task[task_id] = self._build_string_to_id_range(self.test_case_frequency_by_task[task_id], self.passed_unique_test_cases_by_task[task_id]) self.solution_id_to_string_by_task[task_id] = self._build_id_to_string(self.solution_string_to_id_range_by_task[task_id]) self.test_case_id_to_string_by_task[task_id] = self._build_id_to_string(self.test_case_string_to_id_range_by_task[task_id]) def _get_expanded_by_id_range(self, solution_id_range, test_case_id_range): result = list() for solution_id in solution_id_range: for test_case_id in test_case_id_range: result.append((solution_id, test_case_id)) return result def _get_expanded_dual_exec_result(self): for task_id in self.passed_solution_test_case_pairs_by_task.keys(): for solution_str, test_case_str in self.passed_solution_test_case_pairs_by_task[task_id]: solution_id_range = self.solution_string_to_id_range_by_task[task_id][solution_str] test_case_id_range = self.test_case_string_to_id_range_by_task[task_id][test_case_str] self.expanded_passed_solution_test_case_pairs_by_task[task_id] += self._get_expanded_by_id_range(solution_id_range, test_case_id_range) class DualAgreement: def __init__(self, data_manager): self.data_manager = data_manager self.dual_exec_results_by_task = data_manager.expanded_passed_solution_test_case_pairs_by_task self.solution_id_to_string_by_task = data_manager.solution_id_to_string_by_task self.solution_passed_cases_by_task = defaultdict(defaultdict) self.caseset_passed_solutions_by_task = defaultdict(defaultdict) self._get_solution_passed_case_set() logger.info('got solution passed case sets') self._get_caseset_passed_solutions() logger.info('got case set passed solutions') def _get_solution_passed_case_set(self): for task_id in self.dual_exec_results_by_task: for solution, test_case in self.dual_exec_results_by_task[task_id]: if solution in self.solution_passed_cases_by_task[task_id]: self.solution_passed_cases_by_task[task_id][solution].append(test_case) else: self.solution_passed_cases_by_task[task_id][solution] = [test_case] def _get_caseset_passed_solutions(self): for task_id in self.solution_passed_cases_by_task.keys(): for solution in self.solution_passed_cases_by_task[task_id].keys(): case_set = tuple(sorted(self.solution_passed_cases_by_task[task_id][solution])) # case_set: set of (test_case, score) if case_set in self.caseset_passed_solutions_by_task[task_id]: self.caseset_passed_solutions_by_task[task_id][case_set].append(solution) else: self.caseset_passed_solutions_by_task[task_id][case_set] = [solution] def get_sorted_solutions_without_iter(self): logger.info('Start to get sorted solutions without iter') # caseset_passed_solutions = {task_id: {case_set: [solution]}} ranked_solutions_by_task = defaultdict(list) for task_id in self.caseset_passed_solutions_by_task.keys(): flatted_case_set_passed_solutions = [] for case_set in self.caseset_passed_solutions_by_task[task_id].keys(): solution_set = self.caseset_passed_solutions_by_task[task_id][case_set] solution_set_score = math.sqrt(len(solution_set)) case_set_score = len(case_set) solution_str_set = [self.solution_id_to_string_by_task[task_id][solution] for solution in solution_set] flatted_case_set_passed_solutions.append((solution_str_set, case_set_score*solution_set_score)) ranked_solutions_by_task[task_id] = sorted(flatted_case_set_passed_solutions, key=lambda x: x[1], reverse=True) return ranked_solutions_by_task
CodeT/CodeT/src/agreement.py/0
{ "file_path": "CodeT/CodeT/src/agreement.py", "repo_id": "CodeT", "token_count": 3811 }
211
# RepoCoder: Repository-Level Code Completion Through Iterative Retrieval and Generation # Overview In the paper, we present **RepoCoder**, a simple, generic, and effective framework to tackle the repository-level code completion task, which is to continue writing the unfinished code based on a broader context of the repository. RepoCoder incorporates a similarity-based retriever, a pre-trained code language model, and a novel iterative retrieval-generation paradigm. It streamlines the overall process and eliminates the need for heuristic rules, static code analysis, data labeling, and model re-training in previous studies. ![framework](./figs/framework.png) <center> Figure 1. The illustration of our RepoCoder framework. </center> We also present a new benchmark, **RepoEval**, for the repository-level code completion task, which consists of the latest and high-quality real-world repositories covering line, API invocation, and function body completion scenarios. We test the performance of RepoCoder and show that it significantly improves the zero-shot code completion baseline by over 10% and consistently outperforms the vanilla retrieval-augmented code completion approach. ## Project This project contains the basic components of RepoCoder. Here is an overview: ```shell |-- make_window.py # slice the repository files and the model predictions into code snippets |-- build_vector.py # build the vector representation for the code snippets |-- search_code.py # search relevant code snippets with the vector representation |-- build_prompt.py # build the prompt with the unfinished code and the retrieved code snippets |-- run_pipeline.py # run the code completion pipeline |-- compute_score.py # evaluate the performance of the code completion |-- utils.py # utility functions |-- datasets/datasets.zip # the input data for the code completion task |-- function_level_completion_4k_context_codex.test.jsonl |-- function_level_completion_2k_context_codex.test.jsonl |-- line_level_completion_4k_context_codex.test.jsonl |-- line_level_completion_2k_context_codex.test.jsonl |-- line_level_completion_2k_context_codegen.test.jsonl |-- line_level_completion_1k_context_codegen.test.jsonl |-- api_level_completion_4k_context_codex.test.jsonl |-- api_level_completion_2k_context_codex.test.jsonl |-- api_level_completion_2k_context_codegen.test.jsonl |-- api_level_completion_1k_context_codegen.test.jsonl |-- repositories # the checkpoints of repositories used to build our benchmark |-- function_level.zip |-- CarperAI_trlx |-- lucidrains_imagen-pytorch |-- deepmind_tracr |-- leopard-ai_betty |-- google_lightweight_mmm |-- amazon-science_patchcore-inspection |-- facebookresearch_omnivore |-- maxhumber_redframes |-- line_and_api_level.zip |-- pytorch_rl |-- opendilab_ACE |-- google_vizier |-- awslabs_fortuna |-- huggingface_evaluate |-- huggingface_diffusers |-- nerfstudio-project_nerfstudio |-- alibaba_FederatedScope ``` We utilize a private library to handle the execution and evaluation of the function-level completion. Due to the license issue, we cannot release the code. However, we provide the data for the function-level completion task in `datasets/datasets.zip` and `repositories/function_level.zip`. # Quickstart ## Prepare Environment First, we should set up a python environment. This code base has been tested under python 3.8. ```bash $ conda create -n repocoder python=3.8 $ conda activate repocoder $ pip install -r requirements.txt ``` ## Run the Code Completion 1. The `run_RG1_and_oracle_method` function in `run_pipeline.py` shows the process of building the prompts for vanilla retrieval-augmented generation (RG1) and the Oracle method. The generated prompts are listed in a .jsonl file, where each line contains the content in the following format: ```json { "prompt": "...the retrieved code snippets and unfinished code...", "metadata": { "task_id": "repo_name/idx", "ground_truth": "ground truth completion", "fpath_tuple": ["path", "to", "target file"], "context_start_lineno": 0, "line_no": 10, } } ``` 2. Then we can call the model to generate completions and organize the results in the following format: ```json { "prompt": "...the retrieved code snippets and unfinished code...", "choices": [{"text": "...generated completion without repeating the input prompt..."}], "metadata": {} } ``` 3. Next, we can evaluate the performance of the code completion with the `compute_score.py` script. The script will compute the Exact Match and Edit Similarity scores. 4. After that, we can use the `run_RepoCoder_method` function in `run_pipeline.py` to run a second iteration of retrieval-generation, which is our proposed RepoCoder approach, using the prediction file of RG1. And finally, we can evaluate the performance of RepoCoder as introduced in Step 3. # Citation If our work is useful, please consider citing our paper: ```bibtex @article{zhang2023repocoder, title={RepoCoder: Repository-Level Code Completion Through Iterative Retrieval and Generation}, author={Zhang, Fengji and Chen, Bei and Zhang, Yue and Liu, Jin and Zan, Daoguang and Mao, Yi and Lou, Jian-Guang and Chen, Weizhu}, journal={arXiv preprint arXiv:2303.12570}, year={2023} } ``` # Contributing This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments. # License Please note that this repo is under [MIT License](LICENSE). # Trademarks This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow [Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general). Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.
CodeT/RepoCoder/README.md/0
{ "file_path": "CodeT/RepoCoder/README.md", "repo_id": "CodeT", "token_count": 1968 }
212
# Cognitive Service Powershell context ## Using Speech Synthesis This project includes speech synthesized playback for your query outputs using the azure cognitive services speech cli. As noted in the previous section about contexts, this is a certain behavior of the model that is included in the sample `powershell-voice-cognitive-service.txt` file available in the `contexts` folder. Before running any speech synthesis output from the model, you have to do a couple of steps to set it up: ### Set up Azure Speech Service Speech Service is part of the larger Cognitive Services suite and helps you enable applications in areas of speech-to-text, text-to-speech, and speech translation. Here we want it primarily for the text-to-speech functionality. 1. Go to the Cognitive Services Hub in the Azure Portal 2. Create a new Speech Service: You may choose the default values for setting it up 3. Save the API Key and Region for further use ### Set up Azure Speech CLI Follow the instructions in [Azure Speech CLI Quickstart](https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/spx-basics?tabs=windowsinstall%2Cterminal) to install the prerequisites If you are setting up for the first time, here is what you may have to do: 1. Download [.NET Core 3.1 SDK](https://docs.microsoft.com/en-us/dotnet/core/install/windows) and [Microsoft Visual C++ Redistributable for Visual Studio 2019](https://support.microsoft.com/help/2977003/the-latest-supported-visual-c-downloads) 2. Install speech CLI in PowerShell using this command: `dotnet tool install --global Microsoft.CognitiveServices.Speech.CLI` 3. Use the subscription key and region that you obtained from the Cognitive Services Speech Service page and input into the following commands `spx config @key --set SUBSCRIPTION-KEY` `spx config @region --set REGION` ### Load the example speech context file Load the example Cognitive Services speech context file using ` # load context powershell-voice-cognitive-service.txt ` and then hit `Ctrl + G` to let the Codex CLI load the file And that's it! To get started with an example, go ahead and type `# whats the meaning of life`. You can develop your own context with more speech functions as mentioned in the previous section.
Codex-CLI/contexts/CognitiveServiceContext.md/0
{ "file_path": "Codex-CLI/contexts/CognitiveServiceContext.md", "repo_id": "Codex-CLI", "token_count": 565 }
213
### # PowerShell script to setup Codex CLI for PowerShell ### param ( [Parameter()] [System.IO.FileInfo] [ValidateScript( { if (-Not ($_ | Test-Path) ) { throw "Folder does not exist. Did you clone the Codex CLI repo?" } return $true })] [string]$RepoRoot = (Get-Location), [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [SecureString] $OpenAIApiKey, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] $OpenAIOrganizationId, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] $OpenAIEngineId ) $plugInScriptPath = Join-Path $RepoRoot -ChildPath "scripts\powershell_plugin.ps1" $codexQueryPath = Join-Path $RepoRoot -ChildPath "src\codex_query.py" $openAIConfigPath = Join-Path $RepoRoot -ChildPath "src\openaiapirc" # The major version of PowerShell $PSMajorVersion = $PSVersionTable.PSVersion.Major # Convert secure string to plain text if ($PSMajorVersion -lt 7) { $binaryString = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($OpenAIApiKey); $openAIApiKeyPlainText = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($binaryString); } else { $openAIApiKeyPlainText = ConvertFrom-SecureString -SecureString $OpenAIApiKey -AsPlainText } # Check the access with OpenAI API Write-Host "Checking OpenAI access..." $enginesApiUri = "https://api.openai.com/v1/engines" $response = $null try { if ($PSMajorVersion -lt 7) { $response = (Invoke-WebRequest -Uri $enginesApiUri -Headers @{"Authorization" = "Bearer $openAIApiKeyPlainText"; "OpenAI-Organization" = "$OpenAIOrganizationId"}) } else { $response = (Invoke-WebRequest -Uri $enginesApiUri -Authentication Bearer -Token $OpenAIApiKey -Headers @{"OpenAI-Organization" = "$OpenAIOrganizationId"}) } } catch { $statusCode = $_.Exception.Response.StatusCode.value__ Write-Error "Failed to access OpenAI api [$statusCode]. Please check your OpenAI API key (https://beta.openai.com/account/api-keys) and Organization ID (https://beta.openai.com/account/org-settings)." exit 1 } # Check if target engine is available to the user if ($null -eq (($response.Content | ConvertFrom-Json).data | Where-Object {$_.id -eq $OpenAIEngineId})) { Write-Error "Cannot find OpenAI engine: $OpenAIEngineId. Please check the OpenAI engine id (https://beta.openai.com/docs/engines/codex-series-private-beta) and your Organization ID (https://beta.openai.com/account/org-settings)." exit 1 } # Create new PowerShell profile if doesn't exist. The profile type is for current user and current host. # To learn more about PowerShell profile, please refer to # https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_profiles if (!(Test-Path -Path $PROFILE)) { New-Item -Type File -Path $PROFILE -Force } else { # Clean up the content before append new one. This allow users to setup multiple times without running cleanup script (Get-Content -Path $PROFILE -Raw) -replace "(?ms)### Codex CLI setup - start.*?### Codex CLI setup - end", "" | Set-Content -Path $PROFILE Write-Host "Removed previous setup script from $PROFILE." } # Add our plugin script into PowerShell profile. It involves three steps: # 1. Read the plugin script content, # 2. Replace hardcode variable with the actual path to codex_query.py, # 3. Add the plugin script to the content of PowerShell profile. (Get-Content -Path $plugInScriptPath) -replace "{{codex_query_path}}", $codexQueryPath | Add-Content -Path $PROFILE Write-Host "Added plugin setup to $PROFILE." # Create OpenAI configuration file to store secrets if (!(Test-Path -Path $openAIConfigPath)) { New-Item -Type File -Path $openAIConfigPath -Force } Set-Content -Path $openAIConfigPath "[openai] organization_id=$OpenAIOrganizationId secret_key=$openAIApiKeyPlainText engine=$OpenAIEngineId" Write-Host "Updated OpenAI configuration file with secrets." Write-Host -ForegroundColor Blue "Codex CLI PowerShell (v$PSMajorVersion) setup completed. Please open a new PowerShell session, type in # followed by your natural language command and hit Ctrl+G!"
Codex-CLI/scripts/powershell_setup.ps1/0
{ "file_path": "Codex-CLI/scripts/powershell_setup.ps1", "repo_id": "Codex-CLI", "token_count": 1412 }
214
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: large_face_list_face.py Description: Large Face List Face section of the Cognitive Face API. """ from . import util def add(image, large_face_list_id, user_data=None, target_face=None): """Add a face to a large face list. The input face is specified as an image with a `target_face` rectangle. It returns a `persisted_face_id` representing the added face, and `persisted_face_id` will not expire. Args: image: A URL or a file path or a file-like object represents an image. large_face_list_id: Valid character is letter in lower case or digit or '-' or '_', maximum length is 64. user_data: Optional parameter. User-specified data about the large face list for any purpose. The maximum length is 1KB. target_face: Optional parameter. A face rectangle to specify the target face to be added into the large face list, in the format of "left,top,width,height". E.g. "10,10,100,100". If there are more than one faces in the image, `target_face` is required to specify which face to add. No `target_face` means there is only one face detected in the entire image. Returns: A new `persisted_face_id`. """ url = 'largefacelists/{}/persistedFaces'.format(large_face_list_id) headers, data, json = util.parse_image(image) params = { 'userData': user_data, 'targetFace': target_face, } return util.request( 'POST', url, headers=headers, params=params, json=json, data=data) def delete(large_face_list_id, persisted_face_id): """Delete an existing face from a large face list (given by a `persisted_face_id` and a `large_face_list_id`). Persisted image related to the face will also be deleted. Args: large_face_list_id: Valid character is letter in lower case or digit or '-' or '_', maximum length is 64. persisted_face_id: `persisted_face_id` of an existing face. Valid character is letter in lower case or digit or '-' or '_', maximum length is 64. Returns: An empty response body. """ url = 'largefacelists/{}/persistedFaces/{}'.format(large_face_list_id, persisted_face_id) return util.request('DELETE', url) def get(large_face_list_id, persisted_face_id): """Retrieve information about a persisted face (specified by `persisted_face_id` and a `large_face_list_id`). Args: large_face_list_id: Valid character is letter in lower case or digit or '-' or '_', maximum length is 64. persisted_face_id: `persisted_face_id` of an existing face. Valid character is letter in lower case or digit or '-' or '_', maximum length is 64. Returns: The target persisted face's information (`persisted_face_id` and `user_data`). """ url = 'largefacelists/{}/persistedFaces/{}'.format(large_face_list_id, persisted_face_id) return util.request('GET', url) def list(large_face_list_id, start=None, top=None): """Retrieve information (`persisted_face_id` and `user_data`) about existing persisted faces in a large face list. Args: start: Optional parameter. List large face lists from the least `large_face_list_id` greater than the "start". It contains no more than 64 characters. Default is empty. top: The number of large face lists to list, ranging in [1, 1000]. Default is 1000. Returns: An array of persisted faces and their information (`persisted_face_id` and `user_data`). """ url = 'largefacelists/{}/persistedFaces'.format(large_face_list_id) params = { 'start': start, 'top': top, } return util.request('GET', url, params=params) def update(large_face_list_id, persisted_face_id, user_data=None): """Update a persisted face's `user_data` field in a large face list. Args: large_face_list_id: largeFaceListId of an existing large face list. person. person_id: `person_id` of the target person. persisted_face_id: `persisted_face_id` of the target face, which is persisted and will not expire. user_data: Optional parameter. Attach `user_data` to person's persisted face. The size limit is 1KB. Returns: An empty response body. """ url = 'largefacelists/{}/persistedFaces/{}'.format(large_face_list_id, persisted_face_id) json = { 'userData': user_data, } return util.request('PATCH', url, json=json)
Cognitive-Face-Python/cognitive_face/large_face_list_face.py/0
{ "file_path": "Cognitive-Face-Python/cognitive_face/large_face_list_face.py", "repo_id": "Cognitive-Face-Python", "token_count": 1976 }
215
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: test_person_group.py Description: Unittests for Person Group section of the Cognitive Face API. """ import uuid import unittest import cognitive_face as CF from . import util class TestPersonGroup(unittest.TestCase): """Unittests for Person Group section.""" def test_person_group(self): """Unittests for `person_group.create`, `person_group.train`, `person_group.update`, `person_group.get_status` and `person_group.delete`. """ person_group_id = str(uuid.uuid1()) res = CF.person_group.create(person_group_id) print(res) self.assertIsInstance(res, dict) util.wait() # Fake a person and a face to satisfy training. res = CF.person.create(person_group_id, 'TempPerson') person_id = res['personId'] image = '{}PersonGroup/Family1-Dad/Family1-Dad3.jpg'.format( util.BASE_URL_IMAGE) res = CF.person.add_face(image, person_group_id, person_id) res = CF.person_group.train(person_group_id) print(res) self.assertIsInstance(res, dict) util.wait() res = CF.person_group.update(person_group_id, 'name') print(res) self.assertIsInstance(res, dict) util.wait() res = CF.person_group.get_status(person_group_id) print(res) self.assertIsInstance(res, dict) util.wait() res = CF.person_group.delete(person_group_id) print(res) self.assertIsInstance(res, dict) util.wait() def test_get(self): """Unittest for `person_group.get`.""" res = CF.person_group.get(util.DataStore.person_group_id) print(res) self.assertIsInstance(res, dict) util.wait() def test_lists(self): """Unittest for `person_group.lists`.""" res = CF.person_group.lists() print(res) self.assertIsInstance(res, list) util.wait()
Cognitive-Face-Python/cognitive_face/tests/test_person_group.py/0
{ "file_path": "Cognitive-Face-Python/cognitive_face/tests/test_person_group.py", "repo_id": "Cognitive-Face-Python", "token_count": 894 }
216
[nosetests] exe=1 verbosity=2
Cognitive-Face-Python/setup.cfg/0
{ "file_path": "Cognitive-Face-Python/setup.cfg", "repo_id": "Cognitive-Face-Python", "token_count": 15 }
217
DUMPY_STRING_FOR_EMPTY_ANS = "no answer"
ContextualSP/adaptershare/data_utils/my_statics.py/0
{ "file_path": "ContextualSP/adaptershare/data_utils/my_statics.py", "repo_id": "ContextualSP", "token_count": 19 }
218
import os import argparse import random from sys import path path.append(os.getcwd()) from experiments.superglue.superglue_utils import save, TASKS, LOAD_FUNCS def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--data_dir', type=str, default='data directory') parser.add_argument('--task', type=str, default='CB') args = parser.parse_args() return args def main(args): task = args.task.lower() assert task in TASKS, "don't support {}".format(task) files = TASKS[task] laod_function = LOAD_FUNCS[task] for file in files: data = laod_function(os.path.join(args.data_dir, file)) assert len(data) > 0 filename, extension = os.path.splitext(file) fin = os.path.join(args.data_dir, file) prefix = os.path.join(args.data_dir, "{}".format(filename)) columns = len(data[0]) labels = [str(sample["label"]) for sample in data] input0 = [sample["premise"] for sample in data] input1 = [sample["hypothesis"] for sample in data] if columns > 3 else None input2 = [sample["hypothesis_extra"] for sample in data] if "hypothesis_extra" in data[0] else None has_answer = "answer" in data[0] answers = [sample["answer"] for sample in data] if has_answer else None flabel = "{}.label".format(prefix) save(labels, flabel) finput0 = "{}.raw.input0".format(prefix) save(input0, finput0) if input1: finput1 = "{}.raw.input1".format(prefix) save(input1, finput1) if input2: finput2 = "{}.raw.input2".format(prefix) save(input2, finput2) if answers: fanswers = "{}.answer".format(prefix) save(answers, fanswers) uids = [str(sample["uid"]) for sample in data] fuid = "{}.id".format(prefix) save(uids, fuid) if __name__ == '__main__': args = parse_args() main(args)
ContextualSP/adaptershare/experiments/superglue/superglue_fairseq.py/0
{ "file_path": "ContextualSP/adaptershare/experiments/superglue/superglue_fairseq.py", "repo_id": "ContextualSP", "token_count": 862 }
219
# coding=utf-8 # Copyright (c) Microsoft. All rights reserved. import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.parameter import Parameter class LayerNorm(nn.Module): # ref: https://github.com/pytorch/pytorch/issues/1959 # :https://arxiv.org/pdf/1607.06450.pdf def __init__(self, hidden_size, eps=1e-4): super(LayerNorm, self).__init__() self.alpha = Parameter(torch.ones(1, 1, hidden_size)) # gain g self.beta = Parameter(torch.zeros(1, 1, hidden_size)) # bias b self.eps = eps def forward(self, x): """ Args: :param x: batch * len * input_size Returns: normalized x """ mu = torch.mean(x, 2, keepdim=True).expand_as(x) sigma = torch.std(x, 2, keepdim=True).expand_as(x) return (x - mu) / (sigma + self.eps) * self.alpha.expand_as( x ) + self.beta.expand_as(x)
ContextualSP/adaptershare/module/sub_layers.py/0
{ "file_path": "ContextualSP/adaptershare/module/sub_layers.py", "repo_id": "ContextualSP", "token_count": 446 }
220
#!/bin/bash usage() { echo "Usage: ${0} [-g|--gpu_num] [-o|--output_dir] [-m|--model_dir] [-tr|--train_datasets] [-te|--test_datasets] [-ls|--log_step] [-ss|--save_step]" 1>&2 exit 1 } while [ $# -gt 0 ] do key=${1} case ${key} in -g|--gpu_num) GPU_NUM=${2} shift 2 ;; -o|--output_dir) OUT_DIR=${2} shift 2 ;; -m|--model_dir) M_DIR=${2} shift 2 ;; -tr|--train_datasets) TRAIN=${2} shift 2 ;; -te|--test_datasets) TEST=${2} shift 2 ;; -ls|--log_step) LOG_STEP=${2} shift 2 ;; -ss|--save_step) SAVE_STEP=${2} shift 2 ;; *) usage shift ;; esac done N_GPUS="1" if [ ! -z "$GPU_NUM" ]; then N_GPUS=$GPU_NUM fi if [ ! -z "$TRAIN" ]; then TRAIN=$TRAIN fi if [ ! -z "$TEST" ]; then TEST=$TEST fi if [ ! -z "$LOG_STEP" ]; then LOG_STEP=$LOG_STEP fi if [ ! -z "$SAVE_STEP" ]; then SAVE_STEP=$SAVE_STEP fi NOW=$(date +"%Y%m%d%H%M") ADAPTER_DIR="/mnt/chenzhi/checkpoints/nlu_downstream/adapterdiff/${TRAIN}" OUTPUT_DIR=$ADAPTER_DIR if [ ! -z "$OUT_DIR" ]; then OUTPUT_DIR=$OUT_DIR fi MODEL_DIR="bert-large-uncased" if [ ! -z "$M_DIR" ]; then MODEL_DIR=$M_DIR fi echo "Run Name: $RUN_NAME" echo "Model Dir:" $MODEL_DIR echo "Output Dir:" $OUTPUT_DIR Run_Command_Args=" --init_checkpoint $MODEL_DIR" Run_Command_Args="$Run_Command_Args --train_datasets ${TRAIN}" Run_Command_Args="$Run_Command_Args --test_datasets ${TEST}" Run_Command_Args="$Run_Command_Args --log_per_updates $LOG_STEP" Run_Command_Args="$Run_Command_Args --save_per_updates_on true" Run_Command_Args="$Run_Command_Args --save_per_updates $SAVE_STEP" Run_Command_Args="$Run_Command_Args --epochs 10" Run_Command_Args="$Run_Command_Args --batch_size 8" Run_Command_Args="$Run_Command_Args --batch_size_eval 8" Run_Command_Args="$Run_Command_Args --grad_accumulation_step 2" Run_Command_Args="$Run_Command_Args --output_dir $OUTPUT_DIR" Run_Command_Args="$Run_Command_Args --adapter_cache_path $OUTPUT_DIR" Run_Command_Args="$Run_Command_Args --min_intra_simiarity 2" Run_Command_Args="$Run_Command_Args --max_interference_degree 0" echo $Run_Command_Args CUDA_VISIBLE_DEVICES=0 python adapter_diff_train.py $Run_Command_Args
ContextualSP/adaptershare/scripts/adapter_diff_train.sh/0
{ "file_path": "ContextualSP/adaptershare/scripts/adapter_diff_train.sh", "repo_id": "ContextualSP", "token_count": 1092 }
221
#!/bin/bash set -e set -x SRCDIR=`dirname $0` CODEDIR=`dirname $SRCDIR` WORKDIR=`mktemp -d $SRCDIR/mt-dnn-tests-XXX` mkdir -p $WORKDIR/mt_dnn_models mkdir -p $WORKDIR/checkpoints function delete { rm -rf $1 } # tests begin here i=0 for hparams in "" ; do # train python $CODEDIR/train.py --data_dir $CODEDIR/tests/sample_data/output --task_def $CODEDIR/tests/mnli_task_def.yml --init_checkpoint bert-base-uncased --transformer_cache $WORKDIR/mt_dnn_models/cache --batch_size 20 --batch_size_eval 20 --bert_dropout_p 0 --output_dir $WORKDIR/checkpoints/mt_dnn_results/ --log_file $WORKDIR/checkpoints/mt_dnn_results/log.log --optimizer adamax --train_datasets mnli --test_datasets mnli_matched --learning_rate 5e-5 --log_per_updates 1 --epochs 2 --grad_accumulation_step 2 # check if result files exist if [ ! -f $WORKDIR/checkpoints/mt_dnn_results/model_0.pt ] && [ ! -f $WORKDIR/checkpoints/mt_dnn_results/model_1.pt ]; then echo "Checkpoint files not found!" exit 1 fi # load model and resume training python $CODEDIR/train.py --data_dir $CODEDIR/tests/sample_data/output --task_def $CODEDIR/tests/mnli_task_def.yml --init_checkpoint bert-base-uncased --transformer_cache $WORKDIR/mt_dnn_models/cache --batch_size 20 --batch_size_eval 20 --bert_dropout_p 0 --output_dir $WORKDIR/checkpoints/mt_dnn_results/ --log_file $WORKDIR/checkpoints/mt_dnn_results/log.log --optimizer adamax --train_datasets mnli --test_datasets mnli_matched --learning_rate 5e-5 --log_per_updates 1 --epochs 2 --grad_accumulation_step 2 --resume --model_ckpt $WORKDIR/checkpoints/mt_dnn_results/model_1.pt i=$((i+1)) done trap "delete $WORKDIR" TERM
ContextualSP/adaptershare/tests/test.sh/0
{ "file_path": "ContextualSP/adaptershare/tests/test.sh", "repo_id": "ContextualSP", "token_count": 680 }
222
python eval.py \ --checkpoint checkpoints/wtq_grounding_model/model.pt \ --data_path data/wtq_grounding/dev \ --threshold 0.15
ContextualSP/awakening_latent_grounding/eval_wtq_ground.sh/0
{ "file_path": "ContextualSP/awakening_latent_grounding/eval_wtq_ground.sh", "repo_id": "ContextualSP", "token_count": 55 }
223
import os import torch import torch.nn as nn from transformers import BertTokenizer, AdamW, get_linear_schedule_with_warmup from models import * from utils import * from datetime import datetime import logging from dataclasses import dataclass, field @dataclass class TrainingArgs: learning_rate: float = field(default=3e-5, metadata={"help": "The initial learning rate for Adam."}) non_bert_learning_rate: float = field(default=1e-3, metadata={"help": "The initial learning rate for non-BERT parameters."}) weight_decay: float = field(default=0.0, metadata={"help": "Weight decay if we apply some."}) adam_epsilon: float = field(default=1e-8, metadata={"help": "Epsilon for Adam optimizer."}) max_grad_norm: float = field(default=1.0, metadata={"help": "Max gradient norm."}) dropout: float = field(default=0.3) label_smoothing: bool = field(default=True) fp16: bool = field(default=False) train_batch_size: int = field(default=16, metadata={"help": "Training batch size"}) eval_batch_size: int = field(default=32, metadata={"help": "Evaluation batch size"}) num_train_epochs: int = field(default=10, metadata={"help": "Training epochs"}) max_encode_length: int = field(default=512) warmup_steps: int = field(default=0, metadata={"help": "Warmup steps"}) alw_func: str = field(default='const_0.0') logging_steps: int = field(default=100) evaluate_steps: int = field(default=1000) accumulation_steps: int = field(default=1) model: str = field(default='AlignmentModel') bert_version: str = field(default="bert-base-uncased", metadata={"help": "Training epochs"}) checkpoint: str = field(default=None) data_dir: str = field(default="data/slsql", metadata={"help": "input data dir"}) out_dir: str = field(default='out', metadata={'help': 'output data dir'}) sampling: bool = field(default=False) device: str = field(default='cpu') seed: int = field(default=123) def get_logger(log_dir: str, version: str): os.makedirs(log_dir, exist_ok=True) logging_file = os.path.join(log_dir, '{}.log'.format(version)) logging.basicConfig(level=logging.INFO, format='%(asctime)s\t%(levelname)-8s %(message)s', datefmt='%m-%d %H:%M:%S', filename=logging_file, filemode='w') # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() console.setLevel(logging.INFO) # set a format which is simpler for console use formatter = logging.Formatter('%(asctime)s\t%(message)s') # tell the handler to use this format console.setFormatter(formatter) logger = logging.getLogger("") logger.addHandler(console) return logger def set_seed(seed=123): import random import numpy as np random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) class Trainer: args: TrainingArgs model: nn.Module logger: logging.Logger device: torch.device version: str def __init__(self, args: TrainingArgs): set_seed() self.args = args self.version = "{}_{}".format(args.model, datetime.now().strftime("%Y%m%d%H%M")) if self.args.sampling: self.version = "Sampling_" + self.version self.args.evaluate_steps = 100 self.logger = get_logger(os.path.join(self.args.out_dir, self.version), self.args.model) self.device = torch.device(args.device) self.model = load_model_from_checkpoint(**self.args.__dict__) open(os.path.join(self.args.out_dir, self.version, "config.json"), 'w', encoding='utf-8').write( json.dumps(self.args.__dict__, indent=4, sort_keys=True) + '\n') self.logger.info("save training config over.") for key, val in self.args.__dict__.items(): self.logger.info("{} = {}".format(key, val)) def get_train_and_eval_iter(self): bert_version = self.args.bert_version.replace("hfl/", "") train_paths = [os.path.join(self.args.data_dir, f"train.{bert_version}.json")] dev_paths = [os.path.join(self.args.data_dir, f"dev.{bert_version}.json")] tokenizer = BertTokenizer.from_pretrained(self.args.bert_version) self.logger.info("load BERT tokenizer from {} over.".format(self.args.bert_version)) data_loader_func = get_data_iterator_func(self.args.model) if self.args.sampling: train_iter = data_loader_func(train_paths, tokenizer, self.args.train_batch_size, self.device, False, True, self.args.max_encode_length, sampling_size=self.args.train_batch_size * 100) dev_iter = data_loader_func(dev_paths, tokenizer, self.args.eval_batch_size, self.device, False, False, self.args.max_encode_length, sampling_size=self.args.train_batch_size * 20) else: train_iter = data_loader_func(train_paths, tokenizer, self.args.train_batch_size, self.device, False, True, self.args.max_encode_length) dev_iter = data_loader_func(dev_paths, tokenizer, self.args.eval_batch_size, self.device, False, False, self.args.max_encode_length) self.logger.info("load train iterator over, size = {}".format(len(train_iter.batch_sampler))) self.logger.info("load dev iterator over, size = {}".format(len(dev_iter.batch_sampler))) return train_iter, dev_iter def evaluate(self, dev_iter: DataLoader, saved_file=None): model = self.model model.eval() evaluator = get_evaluator_class(self.args.model)() with torch.no_grad(): for batch_inputs in dev_iter: batch_inputs['label_smoothing'] = self.args.label_smoothing batch_outputs = model.compute_loss(**batch_inputs) evaluator.add_batch(batch_inputs, batch_outputs) saved_path = os.path.join(self.args.out_dir, self.version, saved_file) if saved_file is not None else None eval_result = evaluator.get_metrics(saved_path) model.train() self.logger.info("Evaluate over:\n{}".format( "\n".join([f"{k} = {v:.4f}" if isinstance(v, float) else f"{k} {v}" for k, v in eval_result.items()]))) return eval_result def _parse_loss_weight_function(self, strategy: str): if is_float(strategy): w = float(strategy) return lambda _: w if strategy.startswith("linear"): start, end = strategy.replace("linear_", "").split('-') start, end = int(start), int(end) return lambda x: min(1.0, max(0.0, (x - start) / end)) else: raise NotImplementedError(f"not supported ALW function: {strategy}") def train(self): train_iter, dev_iter = self.get_train_and_eval_iter() num_train_steps = self.args.num_train_epochs * int(len(train_iter)) self.logger.info("num_train_steps = {}".format(num_train_steps)) global_step = int(self.args.checkpoint.split('/')[-1].split('.')[1].replace('step_', "")) if self.args.checkpoint is not None else 0 start_epoch = global_step // len(train_iter) params = [] params_bert = [] for name, param in self.model.named_parameters(): if param.requires_grad: if 'bert' in name: params_bert.append(param) else: params.append(param) optimizer = AdamW([{'params': params_bert}, {'params': params, 'lr': 1e-3}], lr=self.args.learning_rate, eps=self.args.adam_epsilon) if self.args.fp16: try: from apex import amp except ImportError: raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.") self.logger.info("Enable fp16 optimization ...") self.model, optimizer = amp.initialize(self.model, optimizer, opt_level="O2") scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=num_train_steps) self.model.train() loss_weight_funcs = { 'align_loss': self._parse_loss_weight_function(self.args.alw_func), } grad_accumulation_count = 0 for epoch in range(start_epoch, self.args.num_train_epochs): logging_loss = defaultdict(float) for batch_inputs in train_iter: global_step += 1 grad_accumulation_count += 1 batch_inputs['label_smoothing'] = self.args.label_smoothing for loss_type in loss_weight_funcs: batch_inputs[loss_type + "_weight"] = loss_weight_funcs[loss_type](epoch + 1) outputs = self.model.compute_loss(**batch_inputs) loss = outputs['loss'] / self.args.accumulation_steps if self.args.fp16: with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() else: loss.backward() if grad_accumulation_count % self.args.accumulation_steps == 0: if self.args.fp16: torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), self.args.max_grad_norm) else: torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.args.max_grad_norm) optimizer.step() scheduler.step() optimizer.zero_grad() logging_loss['total_loss'] += loss.item() * self.args.accumulation_steps for loss_type in loss_weight_funcs: if loss_type in outputs: logging_loss[loss_type] += outputs[loss_type].item() if global_step % self.args.logging_steps == 0: avg_loss = logging_loss['total_loss'] / self.args.logging_steps loss_string = "total loss: {:.4f}; ".format(avg_loss) for loss_type in loss_weight_funcs: if loss_type in logging_loss: loss_string += "{} : {:.4f} ({:.3f}); ".format(loss_type, logging_loss[ loss_type] / self.args.logging_steps, loss_weight_funcs[loss_type](epoch + 1)) self.logger.info( "Epoch: {}, Step: {}/{}, {}".format(epoch + 1, global_step, len(train_iter) * (epoch + 1), loss_string)) logging_loss = defaultdict(float) if global_step % self.args.evaluate_steps == 0: self.logger.info("Evaluating step {} ...".format(global_step)) eval_metrics = self.evaluate(dev_iter, saved_file='eval.step_{}.txt'.format(global_step)) saved_path = os.path.join(self.args.out_dir, self.version, "{}.step_{}.acc_{:.3f}.pt".format( self.args.model, global_step, eval_metrics['overall accuracy'])) torch.save(self.model.state_dict(), saved_path) self.logger.info("Save checkpoint to {}".format(saved_path)) self.logger.info("***** Running training over *****") def parse_args(): import argparse parser = argparse.ArgumentParser() parser.add_argument('-lr', '--learning_rate', help='learning rate', type=float, default=5e-5) parser.add_argument('-model', '--model', help='model', default='SpiderAlignmentModel') parser.add_argument('-bert', '--bert_version', help='bert version', default='bert-base-uncased') parser.add_argument('-train_bs', '--train_batch_size', help='train batch size', type=int, default=10) parser.add_argument('-eval_bs', '--eval_batch_size', help='eval batch size', type=int, default=10) parser.add_argument('-max_enc_length', '--max_encode_length', help='sequence max encode length', type=int, default=512) parser.add_argument('-num_epochs', '--num_train_epochs', default=30, type=int) parser.add_argument('-label_smoothing', '--label_smoothing', action='store_true', default=False) parser.add_argument('-sampling', '--sampling', action='store_true') # if finetune, use this. parser.add_argument('-ckpt', '--checkpoint', default=None) parser.add_argument('-alw', '--alw_func', default='0.1') parser.add_argument('-data', '--data_dir', default=os.getenv("PT_DATA_DIR", default='data/slsql')) parser.add_argument('-out_dir', '--out_dir', default=os.getenv("PT_OUTPUT_DIR", default='pt')) parser.add_argument('-acc_steps', '--accumulation_steps', type=int, default=1) parser.add_argument('-dropout', '--dropout', type=float, default=0.3) parser.add_argument('-fp16', '--fp16', action='store_true') parser.add_argument('-gpu', '--device', default='cuda:0' if torch.cuda.is_available() else 'cpu') args = parser.parse_args() training_args = TrainingArgs(**dict(args._get_kwargs())) return training_args if __name__ == '__main__': args = parse_args() trainer = Trainer(args) trainer.train() pass
ContextualSP/awakening_latent_grounding/train.py/0
{ "file_path": "ContextualSP/awakening_latent_grounding/train.py", "repo_id": "ContextualSP", "token_count": 6300 }
224
from .element_wise import ElementWiseMatrixAttention
ContextualSP/incomplete_utterance_rewriting/src/similar_functions/__init__.py/0
{ "file_path": "ContextualSP/incomplete_utterance_rewriting/src/similar_functions/__init__.py", "repo_id": "ContextualSP", "token_count": 12 }
225
from src.components.nl_modiifer import NLModifier from src.components.question_generator import QuestionGenerator
ContextualSP/interactive_text_to_sql/src/components/__init__.py/0
{ "file_path": "ContextualSP/interactive_text_to_sql/src/components/__init__.py", "repo_id": "ContextualSP", "token_count": 31 }
226
import io vector_file_path = 'data/common/wiki-news-300d-1M-subword.vec' def load_vectors(fname): fin = io.open(fname, 'r', encoding='utf-8', newline='\n', errors='ignore') n, d = map(int, fin.readline().split()) data = {} for line in fin: tokens = line.rstrip().split(' ') data[tokens[0]] = map(float, tokens[1:]) return data
ContextualSP/interactive_text_to_sql/src/utils/fasttext.py/0
{ "file_path": "ContextualSP/interactive_text_to_sql/src/utils/fasttext.py", "repo_id": "ContextualSP", "token_count": 160 }
227
import json import sys import copy from itertools import combinations, permutations from random import choice, choices, shuffle import math import argparse from multiprocessing import Pool import multiprocessing from collections import Counter from functools import reduce from math import gcd from random import sample parser = argparse.ArgumentParser() parser.add_argument("--max_number", type=int, default=100000, help="max number each dataset.") parser.add_argument("--corpus_file", type=str, default='../corpus/pretraining_corpus_scene.txt', help="corpus file") args = parser.parse_args() fw = open(args.corpus_file, 'w') def lcm(numbers): return reduce((lambda x, y: int(x * y / gcd(x, y))), numbers) def obtain_action_weight(actions): temp = Counter([item.split()[0] for item in actions]) lcm_value = lcm(temp.values()) temp = {item:int(lcm_value / temp[item]) for item in temp} action_weight = [temp[item.strip().split()[0]] for item in actions] return action_weight def random_sampling(candidate_list, n, weights=None): result_list = [] for _ in range(n): result = choices(candidate_list, k=1, weights=weights)[0] result_list.append(result) return result_list def postpreprocess_scene(states): states = ' | '.join(states.split()) return states def scene_executor(slots, actions): slots = copy.deepcopy(slots) for action in actions: splits = action.split() if splits[0] == 'appear_person': if slots[int(splits[1])-1].split(':')[1] == '__': slots[int(splits[1])-1] = '{}:{}_'.format(slots[int(splits[1])-1].split(':')[0], splits[2]) else: return 'Failed: already has a person here' elif splits[0] == 'appear_hat': if slots[int(splits[1])-1].split(':')[1][0] == '_': return 'Failed: No person here' else: if slots[int(splits[1])-1].split(':')[1][1] == '_': slots[int(splits[1])-1] = slots[int(splits[1])-1][:-1] + splits[2] else: return 'Failed: already has a hat here' elif splits[0] == 'remove_person': if slots[int(splits[1])-1].split(':')[1][1] != '_': return 'Failed: please remove hat in this position first.' else: if slots[int(splits[1])-1].split(':')[1][0] == '_': return 'Failed: no person requires to remove here.' else: slots[int(splits[1])-1] = '{}:__'.format(slots[int(splits[1])-1].split(':')[0]) elif splits[0] == 'remove_hat': if slots[int(splits[1])-1].split(':')[1][0] == '_': return 'Failed: no person here.' else: if slots[int(splits[1])-1].split(':')[1][1] == '_': return 'Failed: no hat here.' else: slots[int(splits[1])-1] = slots[int(splits[1])-1][:-1] + '_' else: return 'Failed: No such function:{}'.format(splits[0]) return slots def scene_state_generator(): state_element = ['b', 'g', 'o', 'p', 'r', 'y'] * 2 all_states = list(permutations(state_element, 2)) all_states = list(set([''.join(item) for item in all_states if not (item[0]=='_' and item[1]!='_')])) content = ['{}'.format(item) for i,item in enumerate(random_sampling(all_states, 2))] position = sample(list(range(1,11)), 2) state_dict = dict(zip([str(item) for item in position], content)) for key in list(range(1,11)): if str(key) not in state_dict: state_dict[str(key)] = '__' states = ['{}:{}'.format(key, value) for key, value in state_dict.items()] states.sort(key=lambda x:int(x.split(':')[0])) # states = ' '.join(states) return states def obtain_valid_actions_scene(states): action_list = [] states = [item.strip().split(':')[1] for item in states] for i in range(len(states)): if states[i][0] == '_': action_list.extend(['appear_person {} {}'.format(str(i+1), item) for item in ['b', 'g', 'o', 'p', 'r', 'y']]) else: if states[i][1] == '_': action_list.extend(['appear_hat {} {}'.format(str(i+1), item) for item in ['b', 'g', 'o', 'p', 'r', 'y']]) action_list.append('remove_person {}'.format(str(i+1))) else: action_list.append('remove_hat {}'.format(str(i+1))) return list(set(action_list)) def scene_corpus_generation(inputs): total_number, action_number_range = inputs state_element = ['b', 'g', 'o', 'p', 'r', 'y', '_'] * 2 all_states = list(permutations(state_element, 2)) all_states = list(set([''.join(item) for item in all_states if not (item[0]=='_' and item[1]!='_')])) all_states_weight = [6 if '_' in item else 1 for item in all_states] index = all_states.index('__') all_states_weight[index] = 64 all_actions = ['appear_person {} {}'.format(str(i+1),j) for i in range(10) for j in ['b', 'g', 'o', 'p', 'r', 'y']] all_actions += ['appear_hat {} {}'.format(str(i+1),j) for i in range(10) for j in ['b', 'g', 'o', 'p', 'r', 'y']] all_actions += ['remove_person {}'.format(str(i+1)) for i in range(10)] all_actions += ['remove_hat {}'.format(str(i+1)) for i in range(10)] count = 0 print('Begin generating scene corpus.') while True: # prev_states = ['{}:{}'.format(str(i+1), item) for i,item in enumerate(random_sampling(all_states, 10, weights=all_states_weight))] prev_states = scene_state_generator() states_this_step = prev_states index = 0 action_list = [] step_this_case = choice(action_number_range) while index < step_this_case: all_valid_actions = obtain_valid_actions_scene(states_this_step) action_weight = obtain_action_weight(all_valid_actions) action = random_sampling(all_valid_actions, 1, weights=action_weight) states_this_step = scene_executor(states_this_step, action) assert isinstance(states_this_step, list) action_list.extend(action) index += 1 curr_states = states_this_step prev_states = postpreprocess_scene(' '.join(prev_states)) actions = ' '.join(action_list) curr_states = postpreprocess_scene(' '.join(curr_states)) item_row = '\t'.join([actions, prev_states, curr_states]) fw.write(item_row) fw.write('\n') count += 1 if count % 10000 == 0: print('Finish generating {} cases'.format(count)) if count >= total_number: break if __name__ == '__main__': total_number_list = [int(args.max_number * 0.3), int(args.max_number * 0.4), int(args.max_number * 0.2), int(args.max_number * 0.1)] action_number_range_list = [list(range(1,6)), list(range(6,11)), list(range(11,16)), list(range(16,21))] cores = multiprocessing.cpu_count() print("Using {} cores".format(cores)) pool = Pool(cores) for total_number, action_number_range in zip(total_number_list, action_number_range_list): res = pool.map(scene_corpus_generation, zip([int(total_number // cores) * cores], [action_number_range]*cores)) # scene_corpus_generation(int(args.max_number * 0.3), list(range(1,6))) # scene_corpus_generation(int(args.max_number * 0.4), list(range(6,11))) # scene_corpus_generation(int(args.max_number * 0.2), list(range(11,16))) # scene_corpus_generation(int(args.max_number * 0.1), list(range(16,21)))
ContextualSP/lemon/corpus_generation/scene_corpus_generation.py/0
{ "file_path": "ContextualSP/lemon/corpus_generation/scene_corpus_generation.py", "repo_id": "ContextualSP", "token_count": 3406 }
228
import os from collections import defaultdict, deque, OrderedDict from contextlib import contextmanager from os.path import join import logging import tensorflow as tf import time from keras import backend as K class TensorDebugger(object): """Debug your TensorFlow model. EXAMPLE BELOW: tf.reset_default_graph() tdb = TensorDebugger() # define a graph, register some nodes x = tf.placeholder(tf.int32, name='x') zs = [] for k in range(10): y = tf.constant(k, name='y') tdb.register('y', y) # register with any name you want; we just called it 'y' z = x * y zs.append(z) g = tf.constant(12, name='g') h = tf.constant(10, name='h') tdb.register('g', g, force_run=True) tdb.register('h', h) total = tf.reduce_sum(tf.pack(zs)) sess = tf.InteractiveSession() fetches = [total] feed_dict = {x: 10} # replace your sess.run recall with tdb.debug # result = sess.run(fetches, feed_dict) result, bp_results = tdb.debug(sess, fetches, feed_dict) print 'result:', result print 'bp_results:', bp_results # result: [450] # bp_results: {'y': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 'g': 12} # notice that we collected every value of 'y' in the for-loop # we didn't collect 'h', because it wasn't on the execution path to compute fetches # we collected 'g' even though it's not on execution path, because we marked it as force_run sess.close() """ DEFAULT = None @classmethod def default(cls): if cls.DEFAULT is None: cls.DEFAULT = TensorDebugger() return cls.DEFAULT def __init__(self, g=None): self.name_to_nodes = defaultdict(list) self.name_to_placeholders = defaultdict(list) if g is None: self.g = tf.get_default_graph() self.namestack = [] @property def dependency_graph(self): """Build a dependency graph. Returns: a dict. Each key is the name of a node (Tensor or Operation) and each value is a set of dependencies (other node names) """ deps = defaultdict(set) for op in self.g.get_operations(): # the op depends on its input tensors for input_tensor in op.inputs: deps[op.name].add(input_tensor.name) # the op depends on the output tensors of its control_dependency ops for control_op in op.control_inputs: for output_tensor in control_op.outputs: deps[op.name].add(output_tensor.name) # the op's output tensors depend on the op for output_tensor in op.outputs: deps[output_tensor.name].add(op.name) return deps def ancestors(self, op_name, deps): """Get all nodes upstream of the current node.""" explored = set() queue = deque([op_name]) while len(queue) != 0: current = queue.popleft() for parent in deps[current]: if parent in explored: continue explored.add(parent) queue.append(parent) return explored def register(self, name, node, force_run=False): """Register a name for a node. If multiple nodes are registered to the same name, TensorFlowDebugger saves all nodes as a list, in the order that they were registered. This is convenient if you want to register all nodes constructed in a for-loop under the same name. E.g. for k in range(10): x = tf.constant(k) debugger.register('x', x) """ # TODO(kelvin): deal with SparseTensor placeholder = node.op.node_def.op == 'Placeholder' # TODO(kelvin): remove this hack node.force_run = force_run name_tuple = tuple(self.namestack + [name]) if placeholder: # deal with placeholders separately, because they can't be directly fetched lookup = self.name_to_placeholders else: lookup = self.name_to_nodes lookup[name_tuple].append(node) # TODO(kelvin): somehow make it optional to specify a name? # We could use introspection to get the name of the variable... return node @contextmanager def namescope(self, name): self.namestack.append(name) yield self.namestack.pop() def debug(self, sess, fetches, feed_dict): """Like Session.run, but also returns debug values. Args: sess: Session object fetches: same as Session.run feed_dict: same as Session.run Will ONLY compute values of breakpoints that are on the execution path defined by fetches. Returns: results: same as what's returned by Session.run bp_results: a dictionary mapping breakpoints to their values If a single breakpoint maps to multiple nodes, the "value" for that breakpoint will be a list of the values of all nodes mapping to that breakpoint, in the order that the nodes were registered. """ single_fetch = not isinstance(fetches, list) # as a new list if single_fetch: fetches = [fetches] else: fetches = list(fetches) # compute all ancestors of the fetches deps = self.dependency_graph # compute dependencies ancestors = set() for fetch in fetches: name = fetch if isinstance(fetch, str) else fetch.name anc = self.ancestors(name, deps) ancestors.update(anc) # give each fetch a name orig_fetch = '__orig_fetch__' names = [orig_fetch] * len(fetches) # add debug nodes to fetches for name, cand_nodes in self.name_to_nodes.items(): # filter nodes by those on execution path nodes = [] for cand in cand_nodes: if cand.name in ancestors or cand.force_run: nodes.append(cand) fetches.extend(nodes) names.extend([name] * len(nodes)) # get all values all_results = sess.run(fetches, feed_dict) # extract out results results = [] # original results bp_results = defaultdict(list) # breakpoint results for name, result in zip(names, all_results): if name == orig_fetch: results.append(result) else: bp_results[name].append(result) # get placeholder values directly from feed_dict for name, placeholders in self.name_to_placeholders.items(): for placeholder in placeholders: if placeholder in feed_dict: key = placeholder elif placeholder.name in feed_dict: key = placeholder.name else: if placeholder.force_run: raise ValueError("Tried to force-run {}, but no value provided.".format(placeholder.name)) continue # placeholder wasn't fed bp_results[name].append(feed_dict[key]) if single_fetch: results = results[0] # unwrap single-item lists and single-item name tuples unwrap = lambda l: l[0] if len(l) == 1 else l bp_results = {unwrap(k): unwrap(v) for k, v in bp_results.items()} return results, bp_results class Saver(object): """A light wrapper around the TensorFlow Saver. This object is different in a few ways: - it has its save directory specified up front. - it is able to identify the latest checkpoint even if the directory was moved between the last save and reload. - it always uses the default session """ def __init__(self, save_dir, *args, **kwargs): """Create a Saver. Args: save_dir (str): directory to save checkpoints args (list): args to pass to the tf.train.Saver constructor kwargs (dict): kwargs to pass to the tf.train.Saver constructor """ self._save_dir = save_dir self._saver = tf.train.Saver(*args, **kwargs) self._prev_save_time = time.time() def save(self, step): """Save. Args: step (int): train step number """ path = join(self._save_dir, 'weights') self._saver.save(tf.get_default_session(), path, step) self._prev_save_time = time.time() def interval_save(self, step, interval): """If more than specified interval of time has elapsed since last save, then save. Args: step (int): train step number interval (int): interval of time, in seconds. """ if time.time() - self._prev_save_time >= interval: self.save(step) def restore(self, step_or_ckpt=None): """Restore variables. Args: step_or_ckpt (int|str): if int, restores the checkpoint associated with that step. If str, restores checkpoint at that path. If None, restores the latest checkpoint. Default is None. """ if step_or_ckpt is None: ckpt = self.latest_checkpoint elif isinstance(step_or_ckpt, int): ckpt = self.checkpoint_paths[step_or_ckpt] elif isinstance(step_or_ckpt, str): ckpt = step_or_ckpt else: raise TypeError(step_or_ckpt) sess = tf.get_default_session() self._saver.restore(sess, ckpt) @property def checkpoint_paths(self): """A map from step number to checkpoint path. Returns: OrderedDict[int, str] """ log_path = join(self._save_dir, 'checkpoint') if not os.path.exists(log_path): logging.warn('No checkpoint log found at {}'.format(log_path)) return OrderedDict() # without any checkpoint log, we assume that there are no checkpoints # load the checkpoints log with open(log_path, 'r') as f: logs = list(l.strip() for l in f) d = OrderedDict() for i, line in enumerate(logs): key, val = line.split(': ') if i == 0: assert key == 'model_checkpoint_path' continue # this one is redundant else: assert key == 'all_model_checkpoint_paths' orig_path = val[1:-1] # strip quotation marks _, f_name = os.path.split(orig_path) correct_path = join(self._save_dir, f_name) step = int(correct_path.split('-')[-1]) d[step] = correct_path return d @property def latest_checkpoint(self): ckpts = self.checkpoint_paths if len(ckpts) == 0: # what if there are no checkpoints raise IOError("No checkpoint to restore.") latest_step = max(ckpts.keys()) return ckpts[latest_step] class TensorBoardLogger(object): def __init__(self, log_dir): self.g = tf.Graph() self.summaries = {} self.sess = tf.Session(graph=self.g) self.summ_writer = tf.summary.FileWriter(log_dir, flush_secs=5) def log_proto(self, proto, step_num): """Log a Summary protobuf to the event file. Args: proto: a Summary protobuf step_num: the iteration number at which this value was logged """ self.summ_writer.add_summary(proto, step_num) return proto def log(self, key, val, step_num): """Directly log a scalar value to the event file. Args: key (string): a name for the value val: a float step_num: the iteration number at which this value was logged """ try: ph, summ = self.summaries[key] except KeyError: # if we haven't defined a variable for this key, define one with self.g.as_default(): ph = tf.placeholder(tf.float32, (), name=key) # scalar summ = tf.summary.scalar(key, ph) self.summaries[key] = (ph, summ) summary_str = self.sess.run(summ, {ph: val}) self.summ_writer.add_summary(summary_str, step_num) return val def assert_shape(variable, shape): """Assert that a TensorFlow Variable has a particular shape. Args: variable: TF Variable shape: a TensorShape, Dimension or tuple """ variable.get_shape().assert_is_compatible_with(shape) def guarantee_initialized_variables(session, variables=None): """Guarantee that all the specified variables are initialized. If a variable is already initialized, leave it alone. Otherwise, initialize it. If no variables are specified, checks all variables in the default graph. Args: variables (list[tf.Variable]) """ name_to_var = {v.op.name: v for v in tf.global_variables() + tf.local_variables()} uninitialized_variables = list(name_to_var[name] for name in session.run(tf.report_uninitialized_variables(variables))) init_op = tf.variables_initializer(uninitialized_variables) session.run(init_op) return uninitialized_variables def assert_broadcastable(low_tensor, high_tensor): low_shape = tf.shape(low_tensor) high_shape = tf.shape(high_tensor) low_rank = tf.rank(low_tensor) # assert that shapes are compatible high_shape_prefix = tf.slice(high_shape, [0], [low_rank]) assert_op = tf.assert_equal(high_shape_prefix, low_shape, name="assert_shape_prefix") return assert_op def expand_dims_for_broadcast(low_tensor, high_tensor): """Expand the dimensions of a lower-rank tensor, so that its rank matches that of a higher-rank tensor. This makes it possible to perform broadcast operations between low_tensor and high_tensor. Args: low_tensor (Tensor): lower-rank Tensor with shape [s_0, ..., s_p] high_tensor (Tensor): higher-rank Tensor with shape [s_0, ..., s_p, ..., s_n] Note that the shape of low_tensor must be a prefix of the shape of high_tensor. Returns: Tensor: the lower-rank tensor, but with shape expanded to be [s_0, ..., s_p, 1, 1, ..., 1] """ orig_shape = tf.shape(low_tensor) orig_rank = tf.rank(low_tensor) target_rank = tf.rank(high_tensor) # assert that shapes are compatible assert_op = assert_broadcastable(low_tensor, high_tensor) with tf.control_dependencies([assert_op]): pad_shape = tf.tile([1], [target_rank - orig_rank]) new_shape = tf.concat(0, [orig_shape, pad_shape]) result = tf.reshape(low_tensor, new_shape) # add static shape information high_shape_static = high_tensor.get_shape() low_shape_static = low_tensor.get_shape() extra_rank = high_shape_static.ndims - low_shape_static.ndims result_dims = list(low_shape_static.dims) + [tf.Dimension(1)] * extra_rank result_shape = tf.TensorShape(result_dims) result.set_shape(result_shape) return result def broadcast(tensor, target_tensor): """Broadcast a tensor to match the shape of a target tensor. Args: tensor (Tensor): tensor to be tiled target_tensor (Tensor): tensor whose shape is to be matched """ rank = lambda t: t.get_shape().ndims assert rank(tensor) == rank(target_tensor) # TODO: assert that tensors have no overlapping non-unity dimensions orig_shape = tf.shape(tensor) target_shape = tf.shape(target_tensor) # if dim == 1, set it to target_dim # else, set it to 1 tiling_factor = tf.select(tf.equal(orig_shape, 1), target_shape, tf.ones([rank(tensor)], dtype=tf.int32)) broadcasted = tf.tile(tensor, tiling_factor) # Add static shape information broadcasted.set_shape(target_tensor.get_shape()) return broadcasted def gather_2d(tensor, i, j): """2D version of tf.gather. The equivalent in Numpy would be tensor[i, j, :] Args: tensor (Tensor): a Tensor of rank at least 2 i (Tensor): row indices j (Tensor): column indices of same shape as i, or broadcastable to the same shape """ rank = lambda t: t.get_shape().ndims # get static shape info assert rank(tensor) >= 2 assert rank(i) == rank(j) dims_static = tensor.get_shape() # get dynamic shape info shape = tf.shape(tensor) dims = tf.split(0, rank(tensor), shape) rows, cols = dims[:2] new_dims = [rows * cols] + dims[2:] new_shape = tf.concat(0, new_dims) tensor_flat = tf.reshape(tensor, new_shape) # annotate with static shape new_shape_static = tf.TensorShape([dims_static[0] * dims_static[1]] + list(dims_static[2:])) tensor_flat.set_shape(new_shape_static) k = i * cols + j vals = tf.gather(tensor_flat, k) return vals @contextmanager def clean_session(): """Create a new Graph, bind the graph to a new Session, and make that session the default.""" graph = tf.Graph() # create a fresh graph with tf.Session(graph=graph) as sess: K.set_session(sess) # bind Keras yield sess
ContextualSP/lemon/executor/gtd/ml/utils.py/0
{ "file_path": "ContextualSP/lemon/executor/gtd/ml/utils.py", "repo_id": "ContextualSP", "token_count": 7407 }
229
import pytest from gtd.log import Metadata, SyncedMetadata class TestMetadata(object): @pytest.fixture def m(self): m = Metadata() m['a'] = 10 # this is overwritten m['b'] = 'test' # namescope setitem with m.name_scope('c'): m['foo'] = 140 # nested setitem m['a.foo'] = 120 m['c.bar'] = 'what' return m def test_getitem(self, m): assert m['b'] == 'test' def test_nested_getitem(self, m): assert m['a.foo'] == 120 assert m['c.foo'] == 140 def test_namescope_getitem(self, m): with m.name_scope('c'): assert m['bar'] == 'what' def test_nested_metadata(self, m): m_sub = m['a'] assert isinstance(m_sub, Metadata) assert m_sub['foo'] == 120 def test_contains(self, m): assert 'b' in m assert 'bar' not in m assert 'c.bar' in m class TestSyncedMetadata(TestMetadata): # run all the metadata tests def test_syncing(self, tmpdir): meta_path = str(tmpdir.join('meta.txt')) s = SyncedMetadata(meta_path) with s.name_scope('job'): s['memory'] = 128 s2 = SyncedMetadata(meta_path) # reload the file assert s2['job.memory'] == 128
ContextualSP/lemon/executor/gtd/tests/test_log.py/0
{ "file_path": "ContextualSP/lemon/executor/gtd/tests/test_log.py", "repo_id": "ContextualSP", "token_count": 624 }
230
import numpy as np from collections import Sequence, Counter from abc import ABCMeta, abstractmethod from gtd.chrono import verboserate from gtd.utils import flatten from strongsup.parse_case import ParseCase, ParsePath from strongsup.utils import epsilon_greedy_sample, softmax from strongsup.utils import sample_with_replacement from strongsup.decoder import NormalizationOptions class Beam(Sequence): """A Sequence of ParsePaths. In each ParsePath, each ParseCase must have already have a decision. Usually paths in a Beam are unique, but this is not required (e.g., BatchedReinforce uses Beams with repeated paths). """ __slots__ = ['_paths'] @classmethod def initial_beam(self, context): """Return the initial beam for the context. Args: context (Context) Returns: Beam """ return Beam([ParsePath.empty(context)]) def __init__(self, paths): self._paths = paths def __getitem__(self, i): return self._paths[i] def __len__(self): return len(self._paths) def __str__(self): return 'Beam' + str(self._paths) __repr__ = __str__ def append(self, path): self._paths.append(path) @property def terminated(self): """Whether all paths are terminated.""" return all(path.terminated for path in self._paths) def get_terminated(self): """Get only the terminated paths.""" return Beam([path for path in self._paths if path.terminated]) def get_num_iterations(iterations_per_utterance, examples): """Returns the number of iterations to run for in this batch of examples Args: iterations_per_utterance (int): iterations per utterance config examples (list[Example]) Returns: int: number of iterations """ return iterations_per_utterance * max( [len(ex.context.utterances) for ex in examples]) class ExplorationPolicy(object, metaclass=ABCMeta): """For given examples, search for candidate ParseCase based on some exploration policy. An ExplorationPolicy will be called by the decoder. Since Examples are passed in, an ExplorationPolicy can choose to 'cheat' and use the answer or gold logical form to aid the exploration. This is totally fine during training. """ def __init__(self, decoder, config, normalization, train): """ Args: decoder (Decoder) config (Config) normalization (NormalizationOptions) train (bool): train or test policy """ self._decoder = decoder self._config = config self._normalization = normalization self._train = train @abstractmethod def get_beams(self, examples, verbose=False): """Return a beam of scored ParseCases for each example. Args: examples (list[Example]): List of examples verbose (bool): Verbosity Returns: list[Beam] of length len(examples). """ raise NotImplementedError @abstractmethod def get_intermediate_beams(self, examples, verbose=False): """Return the final beam along with intermediate beams / exploration states. Args: examples (list[Example]): List of examples verbose (bool): Verbosity Returns: list[Beam], list[list[Beam]] Each list has length len(examples). Each sublist i in the second output contains the intermediate beams for example i. """ raise NotImplementedError def _ranker(self, path): """Assigns a score to a ParsePath depending on the configs Return the log unnormalized probability of the ParsePath. The returned value can be used to rank ParsePaths. For local normalization, the method returns the log-probability. For global normalization, the method returns the cumulative logit. Args: path (ParsePath): path to be scored Return: float: the score """ if self._normalization == NormalizationOptions.LOCAL: return path.log_prob elif self._normalization == NormalizationOptions.GLOBAL: return path.score else: raise ValueError( 'Unknown normalization type: {}'.format(self._normalization)) ################################ # Beam search class BeamSearchExplorationPolicy(ExplorationPolicy): def __init__(self, decoder, config, normalization, train): super(BeamSearchExplorationPolicy, self).__init__( decoder, config, normalization, train) if not train: assert not config.independent_utterance_exploration assert config.exploration_epsilon == 0 def get_beams(self, examples, verbose=False): beams = [Beam.initial_beam(ex.context) for ex in examples] num_iterations = get_num_iterations( self._config.iterations_per_utterance, examples) if verbose: iterations = verboserate(list(range(num_iterations)), desc='Performing beam search') else: iterations = range(num_iterations) for _ in iterations: beams = self.advance(beams) return beams def get_intermediate_beams(self, examples, verbose=False): beams = [Beam.initial_beam(ex.context) for ex in examples] intermediates = [[] for _ in examples] num_iterations = get_num_iterations( self._config.iterations_per_utterance, examples) if verbose: iterations = verboserate(list(range(num_iterations)), desc='Performing beam search') else: iterations = range(num_iterations) for _ in iterations: for ex_idx, beam in enumerate(beams): intermediates[ex_idx].append(beam) beams = self.advance(beams) return beams, intermediates def advance(self, beams): """Advance a batch of beams. Args: beams (list[Beam]): a batch of beams Returns: list[Beam]: a new batch of beams (in the same order as the input beams) """ # Gather everything needed to be scored # For efficiency, pad so that the number of cases from each beam # is equal to beam_size. cases_to_be_scored = [] new_paths = [] for beam in beams: # terminated stores terminated paths # which do not count toward the beam size limit terminated = [] # unterminated stores unterminated paths and a partial ParseCase # containing the possible candidate choices unterminated = [] num_cases_to_be_scored = 0 #print '@' * 40 for path in beam: if path.terminated: terminated.append(path) else: case = path.extend() unterminated.append((path, case)) cases_to_be_scored.append(case) num_cases_to_be_scored += 1 new_paths.append((terminated, unterminated)) # Pad to beam_size assert num_cases_to_be_scored <= self._config.beam_size if beam: while num_cases_to_be_scored < self._config.beam_size: case = ParseCase.initial(beam[0].context) cases_to_be_scored.append(case) num_cases_to_be_scored += 1 # for exploration, use a parser which pretends like every utterance # is the first utterance it is seeing ignore_previous_utterances = \ self._config.independent_utterance_exploration # Use the ParseModel to score self._decoder.parse_model.score(cases_to_be_scored, ignore_previous_utterances, self._decoder.caching) # Read the scores and create new paths new_beams = [] #print '=' * 40 for terminated, unterminated in new_paths: #print '-' * 20 new_unterminated = [] for path, case in unterminated: for choice in case.choices: clone = case.copy_with_decision(choice) denotation = clone.denotation # Filter out the cases with invalid denotation if not isinstance(denotation, Exception): path = clone.path if path.terminated: try: # Test if the denotation can be finalized path.finalized_denotation #print 'FOUND [T]', clone.path.decisions, denotation, denotation.utterance_idx, path.finalized_denotation terminated.append(path) except ValueError as e: #print 'FOUND [BAD T]', e pass elif self._decoder.path_checker(path): #print 'FOUND', clone.path.decisions, denotation, denotation.utterance_idx new_unterminated.append(path) else: #print 'PRUNED', clone.path.decisions, denotation, denotation.utterance_idx pass else: #print 'BAD', clone.path.decisions, denotation pass # Sort the paths terminated.sort(key=self._ranker, reverse=True) new_unterminated.sort(key=self._ranker, reverse=True) # Prune to beam size with exploration epsilon = self._config.exploration_epsilon selected = epsilon_greedy_sample( new_unterminated, min(self._config.beam_size, len(new_unterminated)), epsilon=epsilon) # Create a beam from the remaining paths new_beams.append(Beam(terminated + selected)) return new_beams ################################ # Stale Beam Search class BeamMetaInfo(object): """Wrapper around a Beam that includes metadata for BeamMap""" def __init__(self, beam, age): self._beam = beam self._age = age @property def beam(self): return self._beam @property def age(self): return self._age def increment_age(self): self._age += 1 class BeamMap(object): """Maintains a map between Example and stale Beams""" def __init__(self): self._map = {} # example --> BeamMetaInfo def contains(self, example): """Returns if example is in the map Args: example (Example) Returns: bool: True if example in map """ return example in self._map def get_beam_age(self, example): """Returns how old the beam for this example is Args: example (Example) Returns: int: the age """ assert self.contains(example) return self._map[example].age def increment_age(self, example): """Increments the age of the beam associated with this example Args: example (Example) """ assert example in self._map self._map[example].increment_age() def set_beam(self, example, beam): """Sets the beam associated with this example. Args: example (Example) beam (Beam) """ self._map[example] = BeamMetaInfo(beam, 1) def get_beam(self, example): """Returns the beam associated with this example. Args: example (Example) Returns: Beam """ assert example in self._map return self._map[example].beam class StaleBeamSearch(ExplorationPolicy): """Performs beam search every max_age iterations. On the other iterations, returns the stale beams. NOTE: Does not recalculate scores Args: decoder (Decoder) config (Config) normalization (NormalizationOptions) fresh_policy (ExplorationPolicy): the policy that runs to obtain fresh beams train (bool): train or test policy """ def __init__(self, decoder, config, normalization, train): if not train: raise ValueError( "Stale Beam Search should only be used at train time") super(StaleBeamSearch, self).__init__( decoder, config, normalization, train) self._fresh_policy = get_exploration_policy( decoder, config.fresh_policy, normalization, train) self._max_age = self._config.max_age # iterations till refresh self._beam_map = BeamMap() def get_beams(self, examples, verbose=False): expired_examples = [] # Needs to be updated with BeamSearch fresh_beams = [] # Fetched from cache fresh_indices = [] # True @i if example i is fresh for example in examples: # Non-existent or expired if not self._beam_map.contains(example) or \ self._beam_map.get_beam_age(example) >= self._max_age: fresh_indices.append(False) expired_examples.append(example) else: # Still fresh self._beam_map.increment_age(example) fresh_indices.append(True) fresh_beams.append(self._beam_map.get_beam(example)) # Recalculate expired beams if len(expired_examples) > 0: recalculated_beams = self._fresh_policy.get_beams( expired_examples, verbose) else: recalculated_beams = [] # Cache recalculated beams for expired_example, recalculated_beam in zip( expired_examples, recalculated_beams): self._beam_map.set_beam(expired_example, recalculated_beam) # Put beams back in correct order beams = [] for fresh in fresh_indices: if fresh: beams.append(fresh_beams.pop(0)) else: beams.append(recalculated_beams.pop(0)) return beams def get_intermediate_beams(self, examples, verbose=False): return self._fresh_policy.get_intermediate_beams( examples, verbose=verbose) ################################ # Gamma Sampling ABC class GammaSamplingExplorationPolicy(ExplorationPolicy, metaclass=ABCMeta): """Creates a beam using some form of sampling.""" def __init__(self, decoder, config, normalization, train): if not train: raise ValueError( "Sampling Exploration should only be used at train time.") super(GammaSamplingExplorationPolicy, self).__init__( decoder, config, normalization, train) assert config.exploration_epsilon is None def get_beams(self, examples, verbose=False): terminated = [set() for _ in examples] # initialize beams beams = [[ParsePath.empty(ex.context)] for ex in examples] # put all probability mass on the root distributions = [[1] for _ in examples] num_iterations = get_num_iterations( self._config.iterations_per_utterance, examples) iterations = range(num_iterations) if verbose: iterations = verboserate( iterations, desc='Performing randomized search') for _ in iterations: terminated, beams, distributions = self.advance( terminated, beams, distributions) return [Beam(sorted(list(paths), key=self._ranker, reverse=True)) for paths in terminated] def get_intermediate_beams(self, examples, verbose=False): intermediates = [[] for _ in examples] terminated = [set() for ex in examples] particles = [[ParsePath.empty(ex.context)] for ex in examples] distributions = [[1] for _ in range(len(examples))] num_iterations = get_num_iterations( self._config.iterations_per_utterance, examples) if verbose: iterations = verboserate(list(range(num_iterations)), desc='Performing randomized search') else: iterations = range(num_iterations) for _ in iterations: for ex_idx, (beam, terminated_set) in enumerate( zip(particles, terminated)): intermediates[ex_idx].append(Beam( sorted(terminated_set, key=self._ranker, reverse=True) + sorted(beam, key=self._ranker, reverse=True))) terminated, particles, distributions = self.advance( terminated, particles, distributions) return [Beam(sorted(list(paths), key=self._ranker, reverse=True)) for paths in terminated], intermediates def advance(self, terminated, beams, empirical_distributions): """Advance a batch of beams. Args: terminated (list[set(ParsePath)]): a batch of all the terminated paths found so far for each beam. beams (list[list[ParsePath]]): a batch of beams. All paths on all beams have the same length (all should be unterminated) empirical_distributions (list[list[float]]): a batch of distributions over the corresponding beams. Returns: list[set[ParsePath]]: a batch of terminated beams (in the same order as the input beams) list[list[ParsePath]]: a batch of new beams all extended by one time step list[list[float]]: the new empirical distributions over these particles """ # nothing on the beams should be terminated # terminated paths should be in the terminated set for beam in beams: for path in beam: assert not path.terminated path_extensions = [[path.extend() for path in beam] for beam in beams] # for exploration, use a parser which pretends like every utterance # is the first utterance it is seeing ignore_previous_utterances = \ self._config.independent_utterance_exploration # Use the ParseModel to score self._decoder.parse_model.score(flatten(path_extensions), ignore_previous_utterances, self._decoder.caching) new_beams = [] new_distributions = [] gamma = self._config.exploration_gamma for terminated_set, cases, distribution in zip( terminated, path_extensions, empirical_distributions): new_path_log_probs = [] paths_to_sample_from = [] for case, path_prob in zip(cases, distribution): for continuation in case.valid_continuations( self._decoder.path_checker): # Add all the terminated paths if continuation.terminated: terminated_set.add(continuation) else: # Sample from unterminated paths new_path_log_probs.append( gamma * continuation[-1].log_prob + np.log(path_prob)) paths_to_sample_from.append(continuation) if len(paths_to_sample_from) == 0: new_beams.append([]) new_distributions.append([]) continue new_path_probs = softmax(new_path_log_probs) new_particles, new_distribution = self._sample( paths_to_sample_from, new_path_probs) new_beams.append(new_particles) new_distributions.append(new_distribution) return terminated, new_beams, new_distributions @abstractmethod def _sample(self, paths_to_sample_from, path_probs): """Sample from set of valid paths to sample from according to policy. Args: paths_to_sample_from (list[ParsePath]): the valid paths in next beam path_probs (list[float]): gamma sharpened probs of each path Returns: list[ParsePath]: the paths that are sampled according to this policy list[float]: the new probabilities associated with these paths for the next iteration """ raise NotImplementedError ################################ # Particle filter class ParticleFiltering(GammaSamplingExplorationPolicy): """Estimates an empirical distribution from gamma-sharpened distribution given by ParseModel. Samples from that empirical distribution. 1. Sample from empirical distribution p_hat (until get beam_size unique) 2. Extend particles using true distribution Args: decoder (Decoder) config (Config) normalization (NormalizationOptions) """ def _sample(self, paths_to_sample_from, path_probs): # Samples without replacement. New particles have empirical # distribution according to their frequency. num_to_sample = min( self._config.beam_size, len(paths_to_sample_from)) sampled_particles = sample_with_replacement( paths_to_sample_from, path_probs, num_to_sample) new_particle_counts = Counter(sampled_particles) new_particles = list(new_particle_counts.keys()) new_distribution = np.array(list(new_particle_counts.values())) new_distribution = list( new_distribution / float(np.sum(new_distribution))) return new_particles, new_distribution ################################ # Gamma Randomized Search class GammaRandomizedSearch(GammaSamplingExplorationPolicy): def _sample(self, paths_to_sample_from, path_probs): # Samples without replacement num_to_sample = min( self._config.beam_size, len(paths_to_sample_from), sum(p > 0 for p in path_probs) ) chosen_indices = np.random.choice( range(len(paths_to_sample_from)), size=num_to_sample, replace=False, p=path_probs) new_particles = [ paths_to_sample_from[index] for index in chosen_indices] # Distribution is just gamma sharpened and normalized path probs new_distribution = softmax( [self._config.exploration_gamma * path.log_prob for path in new_particles]) return new_particles, new_distribution ################################ # Batched REINFORCE class BatchedReinforce(ExplorationPolicy): """Exploration policy that sample K independent paths for each example (where K = beam size). - The paths comes from the model distribution p(z|x) with possible modifications using gamma or epsilon. - Specifically the next predicate is sampled from * gamma-softmaxed p(choice) with probability 1 - epsilon * uniform over choices with probability epsilon - Choices that cannot be executed are not considered. - Paths that cannot be extended are discarded by default. * Turn on "zombie_mode" to keep them on the beam for negative update - There are two ways to handle terminated paths: * Default: The last predicate must be sampled like other predicates * termination_lookahead: For any choice that terminates the path, apply it and add the terminated path to the beam. Still keep extending the original path. Possible configs: - beam_size (int) - independent_utterance_exploration (bool) - exploration_gamma (float) - exploration_epsilon (float) - termination_lookahead (bool) - zombie_mode (bool) """ def __init__(self, decoder, config, normalization, train): if not train: raise ValueError( "Batched REINFORCE should only be used at train time") super(BatchedReinforce, self).__init__( decoder, config, normalization, train) def get_beams(self, examples, verbose=False): return self.get_intermediate_beams(examples, verbose)[0] def get_intermediate_beams(self, examples, verbose=False): # Start with beam_size empty paths for each example beams = [Beam([ParsePath.empty(ex.context) for _ in range(self._config.beam_size)]) for ex in examples] intermediates = [[] for _ in examples] num_iterations = get_num_iterations( self._config.iterations_per_utterance, examples) if verbose: iterations = verboserate(list(range(num_iterations)), desc='Batched REINFORCE') else: iterations = range(num_iterations) for _ in iterations: for ex_idx, beam in enumerate(beams): intermediates[ex_idx].append(beam) beams = self.advance(beams) return beams, intermediates def advance(self, beams): """Advance a batch of beams. Args: beams (list[Beam]): a batch of beams Returns: list[Beam]: a new batch of beams (in the same order as the input beams) """ # Extend a new case for each unterminated path cases_to_be_scored = [] extending = [] for beam in beams: terminated, unterminated = [], [] for path in beam: if path.terminated: terminated.append(path) else: case = path.extend() cases_to_be_scored.append(case) unterminated.append((path, case)) extending.append((terminated, unterminated)) # Score them ignore_previous_utterances = \ self._config.independent_utterance_exploration self._decoder.parse_model.score( cases_to_be_scored, ignore_previous_utterances, False) # Read the scores and create new paths all_new_beams = [] for new_beam, unterminated in extending: for old_path, case in unterminated: valid_choice_indices = [] valid_new_paths = [] for index, choice in enumerate(case.choices): clone = case.copy_with_decision(choice) denotation = clone.denotation # Filter out the cases with invalid denotation if not isinstance(denotation, Exception): new_path = clone.path # Filter out invalid paths if new_path.terminated: if new_path.finalizable: # With termination_lookahead, add it to beam if self._config.termination_lookahead: new_beam.append(new_path) else: valid_choice_indices.append(index) valid_new_paths.append(new_path) elif self._decoder.path_checker(new_path): valid_choice_indices.append(index) valid_new_paths.append(new_path) if valid_choice_indices: # Sample a choice epsilon = self._config.exploration_epsilon gamma = self._config.exploration_gamma if np.random.random() > epsilon: probs = softmax([case.choice_logits[i] * gamma for i in valid_choice_indices]) else: probs = ([1. / len(valid_choice_indices)] * len(valid_choice_indices)) selected_index = np.random.choice( list(range(len(valid_new_paths))), p=probs) new_beam.append(valid_new_paths[selected_index]) elif self._config.zombie_mode and len(old_path): # Make a zombie copy of the last previous ParseCase new_beam.append(old_path.zombie_clone()) all_new_beams.append(Beam(new_beam)) return all_new_beams ################################ # Main method def get_exploration_policy(decoder, config, normalization, train): """Returns the ExplorationPolicy corresponding to the config.exploration_policy entry. Args: decoder (Decoder): The Decoder config (Config): Should be the config specified in the Decoder normalization (NormalizationOptions): The normalization train (bool): Whether the policy should be train or test Returns: ExplorationPolicy """ if config.type == "beam-search": return BeamSearchExplorationPolicy(decoder, config, normalization, train) elif config.type == "particle-filtering": return ParticleFiltering(decoder, config, normalization, train) elif config.type == "gamma-randomized-search": return GammaRandomizedSearch(decoder, config, normalization, train) elif config.type == "stale-beam-search": return StaleBeamSearch(decoder, config, normalization, train) elif config.type == "batched-reinforce": return BatchedReinforce(decoder, config, normalization, train) else: raise ValueError( "{} does not specify a valid ExplorationPolicy".format( config.type))
ContextualSP/lemon/executor/strongsup/exploration_policy.py/0
{ "file_path": "ContextualSP/lemon/executor/strongsup/exploration_policy.py", "repo_id": "ContextualSP", "token_count": 13697 }
231
# from gtd.utils import cached_property from strongsup.executor import Executor, Denotation from strongsup.rlong.value import RLongStateValue from strongsup.rlong.state import RLongObject ################################ # Denotation class RLongDenotation(tuple, Denotation): """A pretty lightweight class representing the intermediate denotation.""" __slots__ = () def __new__(self, world_state, command_history, execution_stack): """Create a new RLongDenotation. Args: world_state (RLongState): Current states of the objects command_history (list[tuple]): List of actions and arguments execution_stack (list[object]): Used for building arguments for the next action """ return tuple.__new__(RLongDenotation, (world_state, command_history, execution_stack)) @property def world_state(self): return self[0] @property def command_history(self): return self[1] @property def execution_stack(self): return self[2] @property def utterance_idx(self): return len(self[1]) ################################ # Executor class RLongExecutor(Executor): """Stack-based executor for alchemy, scene, and tangrams domains. """ def __init__(self, initial_state, debug=False): self.initial_state = initial_state self.debug = debug def execute(self, y_toks, old_denotation=None): """Return the intermediate denotation of the formula. Args: y_toks (list[Predicate]): the formula fragment to be executed old_denotation (Denotation): If specified, continue execution from this intermediate denotation. Returns: Denotation The denotation is not finalized. Throws: Exception if the formula is malformed. """ if not old_denotation: denotation = RLongDenotation(self.initial_state, [], []) else: assert isinstance(old_denotation, tuple) denotation = RLongDenotation( old_denotation.world_state, old_denotation.command_history, old_denotation.execution_stack[:]) if self.debug: print(('Executing: {} (old deno: {})'.format(y_toks, denotation))) for predicate in y_toks: denotation = self.apply(predicate.name, denotation) if self.debug: print((predicate, denotation)) return denotation def execute_predicate(self, predicate, old_denotation=None): if not old_denotation: denotation = RLongDenotation(self.initial_state, [], []) else: assert isinstance(old_denotation, tuple) denotation = RLongDenotation( old_denotation.world_state, old_denotation.command_history, old_denotation.execution_stack[:]) return self.apply(predicate.name, denotation) STACK_NOT_EMPTY = ValueError('Cannot finalize: Stack not empty') def finalize(self, denotation): """Return the finalized denotation as list[Value]. Return None if the denotation cannot be finalized. For rlong domain, a denotation can be finalized if the stack is empty. The result will be a list of a single RLongValue. """ if denotation.execution_stack: raise RLongExecutor.STACK_NOT_EMPTY return [RLongStateValue(denotation.world_state)] ################################ # Apply def apply(self, name, denotation): """Return a new denotation. The execution stack can be modified directly. But the world state and command history cannot be modified directly; a new Denotation object must be created. This happens only when an action is performed. Args: name (str): The next predicate name denotation (RLongDenotation): Current denotation Returns: RLongDenotation can be the same object as the input argument if only the execution stack is modified """ if len(name) == 1 and name[0].isalpha(): # Color: Push onto the stack denotation.execution_stack.append(name) return denotation elif name[0] == '-' or name[0].isdigit(): # Number: Push onto the stack denotation.execution_stack.append(int(name)) return denotation elif name[0] == 'X': # Fraction: Push onto the stack denotation.execution_stack.append(name) return denotation elif name == 'all-objects': # All objects: Push onto the stack denotation.execution_stack.append(denotation.world_state.all_objects) return denotation elif name[0] == 'P': # Property: Join with the value value = denotation.execution_stack.pop() result = denotation.world_state.apply_join(value, name[1:]) assert result, 'Empty result' denotation.execution_stack.append(result) return denotation elif name[0] == 'D': # Double-Property: Join with the values value2 = denotation.execution_stack.pop() value1 = denotation.execution_stack.pop() result = denotation.world_state.apply_double_join( value1, value2, name[1:]) assert result, 'Empty result' denotation.execution_stack.append(result) return denotation elif name[0] == 'A': # Perform action new_state, history_entry = denotation.world_state.apply_action( name[1:], denotation.execution_stack) return RLongDenotation(new_state, denotation.command_history + [history_entry], denotation.execution_stack) elif name == 'index': # Perform indexing on a list of objects number = denotation.execution_stack.pop() assert isinstance(number, int) objects = denotation.execution_stack.pop() assert isinstance(objects, list) if number > 0: # Because the LF uses 1-based indexing denotation.execution_stack.append(objects[number - 1]) else: # Negative indices: count from the right denotation.execution_stack.append(objects[number]) return denotation elif name[0] == 'H': # History slot number = denotation.execution_stack.pop() assert isinstance(number, int) # Pull out the argument command = denotation.command_history[ number - 1 if number > 0 else number] if name == 'H0': # Get the action and execute argument = command[0] new_state, history_entry = denotation.world_state.apply_action( argument, denotation.execution_stack) return RLongDenotation(new_state, denotation.command_history + [history_entry], denotation.execution_stack) elif name == 'HUndo': # Get the opposite and execute argument = denotation.world_state.reverse_action(command[0]) new_state, history_entry = denotation.world_state.apply_action( argument, denotation.execution_stack) return RLongDenotation(new_state, denotation.command_history + [history_entry], denotation.execution_stack) else: # Just push onto the stack argument = command[int(name[1:])] if not isinstance(argument, (int, str)): assert isinstance(argument, RLongObject) argument = denotation.world_state.resolve_argument(argument) denotation.execution_stack.append(argument) return denotation else: raise ValueError('Unknown predicate {}'.format(name))
ContextualSP/lemon/executor/strongsup/rlong/executor.py/0
{ "file_path": "ContextualSP/lemon/executor/strongsup/rlong/executor.py", "repo_id": "ContextualSP", "token_count": 3694 }
232
"""Generate predicates based on the context (utterance + graph) - FuzzyMatchGenerator: Generate predicates that fuzzily match an utterance span. - NERValueGenerator: Generate predicates from NER values (numbers, dates, etc.) detected in the utterance - FloatingPredicatesGenerator: Generate predicates that do not anchor to utterance spans """ import re from abc import ABCMeta, abstractmethod import Levenshtein from strongsup.predicate import Predicate from strongsup.predicates_computer import PredicatesComputer from strongsup.tables.graph import NULL_CELL from strongsup.tables.predicate import WikiTablePredicate, FIXED_PREDICATES class Generator(object, metaclass=ABCMeta): @abstractmethod def get_predicates(self, tokens): """Return a dict mapping each matched predicate z to a list M[z] where M[z][i] indicates how well predicate z matches input token x[i]. Args: tokens: A list of tokens of the utterance. """ pass ################################ # FuzzyMatchGenerator class PredicateInfo(object): def __init__(self, predicate, original_string, partial_match=False): self.predicate = predicate self.original_string = str(original_string) self.normalized_string = re.sub('[^a-z0-9]', '', original_string.lower()) if partial_match: self.partials = set() if len(original_string) > FuzzyMatchGenerator.PARTIAL_MAX_PREDICATE_LENGTH: return tokens = re.sub('[^a-z0-9]', ' ', original_string.lower()).strip().split() for i in range(len(tokens)): for j in range(i + 1, len(tokens) + 1): self.partials.add(''.join(tokens[i:j])) class FuzzyMatchGenerator(Generator): """Compute possible string (or substring) matches between predicates from the graph and token spans from the utterance. """ # Possible options: # - Do not consider the match if the score is less than this: SIMILARITY_THRESHOLD = 0.8 # - Do not consider phrases matching > this number of predicates: # (likely a stop word) MAX_MATCHES = 5 # For partial matches (match a part of the predicate's string) # - Do not do partial match if the token span is shorter than this: PARTIAL_MIN_SPAN_LENGTH = 3 # - Do not do partial match for predicates longer than this: PARTIAL_MAX_PREDICATE_LENGTH = 70 def __init__(self, predicate_to_strings, partial_match=False): """Create a new TablesFuzzyMatcher for the given set of predicates. Args: predicate_to_strings: A dict from each predicate name (e.g., fb:cell.dr_who) to the original string ("Dr. Who") partial_match: Whether to perform partial match (allows the token span to match consecutive words from the predicate: e.g., allows fb:cell.dr_who to match "who") """ self.partial_match = partial_match self.predicate_infos = {} for predicate, original_string in predicate_to_strings.items(): self.predicate_infos[predicate] = PredicateInfo( predicate, original_string, partial_match) def get_predicates(self, tokens): """Return a dict mapping each fuzzy matched predicate z to a list M[z] where M[z][i] indicates how well predicate z matches input word x[i]. Args: tokens: A list of string tokens. """ tokens = [re.sub('[^a-z0-9]', '', token.lower()) for token in tokens] matches = {} for predicate_info in list(self.predicate_infos.values()): matches[predicate_info.predicate] = [0.0] * len(tokens) for i in range(len(tokens)): for j in range(i + 1, len(tokens) + 1): phrase = ''.join(tokens[i:j]) predicates_matching_phrase = {} for predicate_info in list(self.predicate_infos.values()): score = similarity_ratio(phrase, predicate_info.normalized_string) if (self.partial_match and predicate_info.partials and len(phrase) >= self.PARTIAL_MIN_SPAN_LENGTH): part_score = max(similarity_ratio(phrase, part) for part in predicate_info.partials) score = max(score, part_score) if score: # Normalize score = ((score - FuzzyMatchGenerator.SIMILARITY_THRESHOLD) / (1. - FuzzyMatchGenerator.SIMILARITY_THRESHOLD)) predicates_matching_phrase[predicate_info.predicate] = score if len(predicates_matching_phrase) <= self.MAX_MATCHES: for predicate, score in list(predicates_matching_phrase.items()): weights = matches[predicate] for k in range(i, j): weights[k] = max(weights[k], score) return dict((predicate, weights) for (predicate, weights) in matches.items() if any(x > 0 for x in weights)) # Helper methods def similarity_ratio(x, y, threshold=FuzzyMatchGenerator.SIMILARITY_THRESHOLD): """Compute the similarity ratio between two strings. If the ratio exceeds the threshold, return it; otherwise, return 0. The similarity ratio is given by 1 - (levenshtein distance with substitution cost = 2) / (total length) """ ratio = Levenshtein.ratio(x, y) return ratio if ratio > threshold else 0. ################################ # NERValueGenerator class NERValueGenerator(Generator): """Compute possible primitive values (numbers and dates) that would be tagged with numerical and temporal NER classes (NUMBER, ORDINAL, DATE, etc.) Given an utterance x and a primitive value z, compute M[z][i] = how well predicate z matches input word x[i] """ def __init__(self): pass def get_predicates(self, tokens): """Return a dict mapping each primitive predicate z to a list M[z] where M[z][i] indicates how well z matches input word x[i]. Args: tokens: A list of string tokens. """ match_weights = {} for i in range(len(tokens)): for predicate, l in hackish_ner(tokens, i): if predicate not in match_weights: match_weights[predicate] = [0.0] * len(tokens) for k in range(i, i + l): match_weights[predicate][k] = 1.0 return match_weights # Helper method WORDS_CARDINAL = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty'] WORDS_ORDINAL = [ 'zeroth', 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth', 'twentieth'] MONTHS = ['', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] MONTHS_SHORT = ['', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] def hackish_ner(tokens, i): """Check if tokens[i:i+l] can be converted into a primitive value. Yield pairs (predicate, length). """ u = tokens[i] # Integers: 1, 20, 450, ... if re.match('^[0-9]+$', u): v = str(int(u)) yield 'N' + v, 1 if len(u) == 4: # Could be a year yield 'D{}-xx-xx'.format(v), 1 # 0.2, 4,596, ... try: v = float(u.replace(',', '')) if int(v) == v: yield 'N' + str(int(v)), 1 else: yield 'N' + str(v), 1 except (ValueError, OverflowError): pass # 1st, 2nd, 3rd, ... match = re.match(r'([0-9]+)(st|nd|rd|th)', u) if match: yield 'N' + str(int(match.group(1))), 1 # one, two, three, ... if u in WORDS_CARDINAL: yield 'N' + str(WORDS_CARDINAL.index(u)), 1 # first, second, third, ... if u in WORDS_ORDINAL: yield 'N' + str(WORDS_ORDINAL.index(u)), 1 # TODO: Handle dates and some more numbers # january, ... # march 6, march 6th, ... # november of 1992, november 1992, ... # "march 6 , 2012", ... # 1800s, 1920's, ... ################################ # FloatingPredicatesGenerator class FloatingPredicatesGenerator(Generator): def __init__(self, graph): self.graph = graph def get_predicates(self, tokens): # Column headers match_weights = {} for predicate in self.graph._columns: match_weights[predicate] = None match_weights['!' + predicate] = None # Empty cell if self.graph.has_id(NULL_CELL): match_weights[NULL_CELL] = None return match_weights ################################ # Infer context predicates using all generator class TablesPredicatesComputer(PredicatesComputer): NER_VALUE_GENERATOR = NERValueGenerator() def __init__(self, graph): """Initialize a predicates computer for the specified graph. Args: graph (TablesKnowledgeGraph) """ self.graph = graph self.generators = [ FloatingPredicatesGenerator(self.graph), FuzzyMatchGenerator(self.graph._original_strings, False), # The following one is kind of slow, so comment out for now. #FuzzyMatchGenerator(self.graph._original_strings, True), self.NER_VALUE_GENERATOR] def compute_predicates(self, tokens): """Infer predicates from the tokens and graph. Return a list of predicates. Args: tokens (list[unicode]) Returns: list[(Predicate, alignment)] where alignment is list[(utterance token index, alignment strength)] """ matches = [] found_predicates = set() for matcher in self.generators: match_weights = matcher.get_predicates(tokens) matches.append(match_weights) found_predicates.update(match_weights) predicates = [(fixed, []) for fixed in FIXED_PREDICATES] for name in found_predicates: predicate = WikiTablePredicate(name, original_string=self.get_original_string(name)) match_weights = self.combine_match_weights( matches, name, tokens) predicates.append((predicate, match_weights)) predicates.sort(key=lambda x: (x[0].types, x[0].name)) return predicates def get_original_string(self, name): """Get the original string. Also works for numbers and dates. Args: name (unicode): predicate name Returns: unicode """ words = [] if self.graph.has_id(name): words.append(self.graph.original_string(name)) elif name[0] == 'N': words.append(name[1:]) elif name[0] == 'D': year, month, day = name[1:].split('-') if year[0] != 'x': words.append(year) if month[0] != 'x': words.append(MONTHS[int(month)].title()) if day[0] != 'x': words.append(day) return ' '.join(words) def combine_match_weights(self, matches, name, tokens): """Helper method for combining match weights. Returns: list[(utterance token index, alignment strength)] """ combined = [0.0] * len(tokens) for match in matches: if name in match and match[name]: for i, x in enumerate(match[name]): combined[i] = max(combined[i], x) return [(i, x) for (i, x) in enumerate(combined) if x] ################################ # Quick test def test(): from dependency.data_directory import DataDirectory from strongsup.tables.world import WikiTableWorld class DummyContext(object): def __init__(self, utterance, context): self.graph = WikiTableWorld(context).graph self.utterance = utterance with open(DataDirectory.wiki_table_questions + '/data/training.tsv') as fin: header = fin.readline().rstrip('\n').split('\t') for i in range(20): stuff = dict(list(zip(header, fin.readline().rstrip('\n').split('\t')))) context = DummyContext(stuff['utterance'].split(), stuff['context']) #print stuff predicates = TablesPredicatesComputer(context.graph).compute_predicates(context) names = [x[0].name for x in predicates] assert len(names) == len(set(names)) #for x, y in sorted(predicates, key=lambda u: (u[0].types_vector, u[0].name)): # print ' ' * 4, x, x.types, y if __name__ == '__main__': test()
ContextualSP/lemon/executor/strongsup/tables/predicates_computer.py/0
{ "file_path": "ContextualSP/lemon/executor/strongsup/tables/predicates_computer.py", "repo_id": "ContextualSP", "token_count": 5837 }
233
from gtd.utils import Bunch from strongsup.example import Example, Context from strongsup.experiment import example_to_supervised_cases from strongsup.tests.utils import PredicateGenerator from strongsup.utils import EOS def test_example_to_supervised_cases(): class DummyTablePath(object): graph = 'GRAPH!' context = Context(DummyTablePath(), 'hello', executor='dummy executor') p = PredicateGenerator(context) context._predicates = [p('a'), p('b'), p('c'), p('d'), p(EOS)] answer = None logical_form = [p('a'), p('b'), p('c'), p('d')] example = Example(context, answer, logical_form) cases = example_to_supervised_cases(example) c0, c1, c2, c3 = cases assert c0.previous_decisions == [] assert c1.previous_decisions == [p('a')] assert c2.previous_decisions == [p('a'), p('b')] assert c3.previous_decisions == [p('a'), p('b'), p('c')] assert c0.decision == p('a') assert c1.decision == p('b') assert c2.decision == p('c') assert c3.decision == p('d')
ContextualSP/lemon/executor/strongsup/tests/test_experiment.py/0
{ "file_path": "ContextualSP/lemon/executor/strongsup/tests/test_experiment.py", "repo_id": "ContextualSP", "token_count": 396 }
234
import json import random import sys from allennlp_reasoning_explainqa.common.constants import CORRECT_OPTION_TAG from allennlp_reasoning_explainqa.training.metrics.confusion_matrix import ( F1MeasureCustomRetrievalEval, ) from allennlp_reasoning_explainqa.training.metrics.explanation_eval import ( ExplanationEval, ) # Sets random seed to a nothing-up-my-sleeve number so that we have # deterministic evaluation scores. random.seed(12345) # Sets random seed to a nothing-up-my-sleeve number so that we have # deterministic evaluation scores. random.seed(12345) def evaluate(prediction_filename, label_filename): chainid_to_label = json.load(open(label_filename, "r")) chain_count = len(chainid_to_label) predictions_lines = open(prediction_filename, "r").readlines() predictions = [json.loads(row) for row in predictions_lines] prediction_count = len(predictions) if chain_count != prediction_count: print( f"Label file {label_filename} has {chain_count} chains, but prediction file {prediction_filename} has {prediction_count} predictions. These must be equal." ) sys.exit(1) f1eval = F1MeasureCustomRetrievalEval(pos_label=1) explanation_eval = ExplanationEval() chain_ids_covered = [] cnt = 0 for row in predictions: assert "score" in row, "Prediction should contain field score" assert "chain_id" in row, "Prediction should contain field chain_id" score = row["score"] chain_id = row["chain_id"] qid = chain_id.strip().split("_")[0] print("qid,chain_id,score = ", qid, chain_id, score) gtlabel = chainid_to_label[chain_id] f1eval(int(gtlabel), score) explanation_eval(qid, CORRECT_OPTION_TAG, int(gtlabel), score) chain_ids_covered.append(chain_id) cnt += 1 assert len(chain_ids_covered) == len( chainid_to_label ), "Found {} chains but expected {} chains".format( len(chain_ids_covered), len(chainid_to_label) ) binclf_performance = f1eval.get_metric(reset=True) print("f1.get_metric() = ", binclf_performance) explanation_performance = explanation_eval.get_metric(reset=True) print("explanation_eval.get_metric() = ", explanation_performance) final_metrics = { "auc_roc": binclf_performance["auc_roc"], "explainP1": explanation_performance["explainP1"], "explainNDCG": explanation_performance["explainNDCG"], } print("=" * 32) print(": auc_roc = ", binclf_performance["auc_roc"]) print(": P1 = ", explanation_performance["explainP1"]) print(": explainNDCG = ", explanation_performance["explainNDCG"]) print("=" * 32) return final_metrics if __name__ == "__main__": prediction_filename = sys.argv[1] label_filename = sys.argv[2] metrics_filename = sys.argv[3] print( f"Evaluating prediction file {prediction_filename} with label file {label_filename}" ) metrics = evaluate(prediction_filename, label_filename) print(f"Writing final metrics to file: {metrics_filename}") json.dump(metrics, open(metrics_filename, "w"))
ContextualSP/lemon/propara_evaluator/aristo-leaderboard/eqasc/code/allennlp_reasoning_explainqa/evaluator/evaluator.py/0
{ "file_path": "ContextualSP/lemon/propara_evaluator/aristo-leaderboard/eqasc/code/allennlp_reasoning_explainqa/evaluator/evaluator.py", "repo_id": "ContextualSP", "token_count": 1196 }
235
from evaluation.metric import Metric from evaluation.evaluation import Evaluation
ContextualSP/lemon/propara_evaluator/aristo-leaderboard/propara/evaluator/evaluation/__init__.py/0
{ "file_path": "ContextualSP/lemon/propara_evaluator/aristo-leaderboard/propara/evaluator/evaluation/__init__.py", "repo_id": "ContextualSP", "token_count": 17 }
236
#!/bin/bash set -euo pipefail echo echo -------------------------------- echo Building image echo -------------------------------- echo set -x docker build -t propara-evaluator-local . set +x echo echo -------------------------------- echo Running echo -------------------------------- echo set -x T=$(mktemp -d /tmp/tmp-XXXXX) docker run \ -v $PWD/testfiles-1:/testfiles-1:ro \ -v $T:/output:rw \ -it propara-evaluator-local \ python3 \ evaluator.py \ --predictions /testfiles-1/predictions.tsv \ --answers /testfiles-1/answers.tsv \ --output /output/metrics.json if [ "$(cat $T/metrics.json)" != '{"precision": 0.743, "recall": 0.43, "f1": 0.545}' ]; then echo File $T/metrics.json looks wrong. exit 1 fi echo $T/metrics.json looks okay. set +x
ContextualSP/lemon/propara_evaluator/aristo-leaderboard/propara/evaluator/test-in-docker.sh/0
{ "file_path": "ContextualSP/lemon/propara_evaluator/aristo-leaderboard/propara/evaluator/test-in-docker.sh", "repo_id": "ContextualSP", "token_count": 281 }
237
## Test case: Too few predictions * answers.tsv has answers to three processes. * predictions.tsv has a prediction of one process. An evaluation on this prediction should abort.
ContextualSP/lemon/propara_evaluator/aristo-leaderboard/propara/evaluator/testfiles-5/README.md/0
{ "file_path": "ContextualSP/lemon/propara_evaluator/aristo-leaderboard/propara/evaluator/testfiles-5/README.md", "repo_id": "ContextualSP", "token_count": 44 }
238
## TRACIE Evaluator This script evaluates NLI predictions against correct inferences and produces 4 accuracy scores described below, and can be used to check that outputs produced for the leaderboard are well formed. ## Example ```sh % python3 evaluator/evaluator.py --question_answers data/train_uniform.jsonl --predictions data/predictions.jsonl --output metrics.json % cat metrics.json {"total_acc": 0.5, "start_acc": 0.5, "end_acc": 0.5, "story_em": 0.0} ``` This uses a dummy prediction file called `predictions.jsonl` which predicts entailments for each example in `train_uniform.jsonl`: ``` {"id":"tracie-train-uniform-0000","label":"entailment"} {"id":"tracie-train-uniform-0001","label":"entailment"} {"id":"tracie-train-uniform-0002","label":"entailment"} {"id":"tracie-train-uniform-0003","label":"entailment"} {"id":"tracie-train-uniform-0004","label":"entailment"} ... ``` ## Output metrics A json file called `metrics.json` will be produced containing the following accuracy scores: ```json {"train_type": "train_iid", "total_acc": 0.5, "start_acc": 0.5, "end_acc": 0.5, "story_em": 0.0} ``` In this file, here is what the fields mean: * `total_acc` is the overall accuracy * `start_acc` is the accuracy of the subset of problems involving event `start` questions * `end_acc` is the subset involving end point questions * `story_em` is the accuracy of getting all questions correct per story
ContextualSP/lemon/propara_evaluator/aristo-leaderboard/tracie/evaluator/README.md/0
{ "file_path": "ContextualSP/lemon/propara_evaluator/aristo-leaderboard/tracie/evaluator/README.md", "repo_id": "ContextualSP", "token_count": 455 }
239
if [ -d "./bookcorpus_conclusion" ] then rm -r ./bookcorpus_conclusion fi mkdir ./bookcorpus_conclusion python conclusion_corpus_construction.py --start 0 --end 500 & python conclusion_corpus_construction.py --start 500 --end 1000 & python conclusion_corpus_construction.py --start 1000 --end 1500 & python conclusion_corpus_construction.py --start 1500 --end 2000 & python conclusion_corpus_construction.py --start 2000 --end 2500 & python conclusion_corpus_construction.py --start 2500 --end 3000 & python conclusion_corpus_construction.py --start 3000 --end 3500 & python conclusion_corpus_construction.py --start 3500 --end 4000 & python conclusion_corpus_construction.py --start 4000 --end 4500 & python conclusion_corpus_construction.py --start 4500 --end 5000 & python conclusion_corpus_construction.py --start 5000 --end 5500 & python conclusion_corpus_construction.py --start 5500 --end 6000 & python conclusion_corpus_construction.py --start 6000 --end 6500 & python conclusion_corpus_construction.py --start 6500 --end 7000 & python conclusion_corpus_construction.py --start 7000 --end 7500 & python conclusion_corpus_construction.py --start 7500 --end 8000 & python conclusion_corpus_construction.py --start 8000 --end 8500 & python conclusion_corpus_construction.py --start 8500 --end 9000 & python conclusion_corpus_construction.py --start 9000 --end 9500 & python conclusion_corpus_construction.py --start 9500 --end 10000 & python conclusion_corpus_construction.py --start 10000 --end 10500 & python conclusion_corpus_construction.py --start 10500 --end 11000 & python conclusion_corpus_construction.py --start 11000 --end 11500 & python conclusion_corpus_construction.py --start 11500 --end 12000 & python conclusion_corpus_construction.py --start 12000 --end 12500 & python conclusion_corpus_construction.py --start 12500 --end 13000 & python conclusion_corpus_construction.py --start 13000 --end 13500 & python conclusion_corpus_construction.py --start 13500 --end 14000 & python conclusion_corpus_construction.py --start 14000 --end 14500 & python conclusion_corpus_construction.py --start 14500 --end 15000 & python conclusion_corpus_construction.py --start 15000 --end 15500 & python conclusion_corpus_construction.py --start 15500 --end 16000 & python conclusion_corpus_construction.py --start 16000 --end 16500 & python conclusion_corpus_construction.py --start 16500 --end 17000 & python conclusion_corpus_construction.py --start 17000 --end 17500 & python conclusion_corpus_construction.py --start 17500 --end 18000 & wait cat ./bookcorpus_conclusion/*.jsonl > ./bookcorpus_conclusion.jsonl rm -r ./bookcorpus_conclusion
ContextualSP/logigan/corpus_construction/mlm_corpus/construct_conclusion.sh/0
{ "file_path": "ContextualSP/logigan/corpus_construction/mlm_corpus/construct_conclusion.sh", "repo_id": "ContextualSP", "token_count": 817 }
240
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoConfig import torch import torch.nn as nn from copy import deepcopy from collections import Counter from datasets import Dataset, load_dataset import numpy as np from transformers import Trainer, TrainingArguments from torch.nn.functional import softmax from parameters16g_es_corpusb import * import os, time import json import datasets import random datasets.set_caching_enabled(False) os.environ["WANDB_DISABLED"] = "true" import argparse parser = argparse.ArgumentParser() parser.add_argument('--model_path', help='Path to load verifier model') parser.add_argument('--output_dir', help='Path to save new checkpoint after training.') parser.add_argument('--local_rank', help='local rank') args = parser.parse_args() VER_MODEL_PATH = args.model_path # if not VER_MODEL_PATH.startswith('checkpoint-'): # files=os.listdir(VER_MODEL_PATH) # for f in files: # if f.startswith('checkpoint-'): VER_MODEL_PATH = os.path.join(VER_MODEL_PATH, f) if args.local_rank == '0': print(f"\nVerifier.py: Using Verifier model from {VER_MODEL_PATH}\n\n") def compute_metrics(predictions): pred_logits, labels = predictions # print(pred_logits.shape) return {"accuracy": 1} def create_ver_infer(pred_dataset, pred): logits, labels = pred[0][:,:2], pred[1] pred_probs = softmax(torch.FloatTensor(logits), dim=-1).numpy()[:, 1] # print(len(pred_probs)) start_idx = 0 if trainer.args.local_rank in [-1,0]: with open(gen_train_iter_path, "w") as f: # Xinyu: Verifier will create train set for generator at current iteration. for i,cs,gs,ids in zip(pred_dataset["input"], pred_dataset["conclusions"], pred_dataset["is_gold"],pred_dataset['selected_ids']): ins_num = min(len(cs), gen_per_device_examples_num) tmp_scores = [float(p) for p in pred_probs[start_idx:start_idx+ins_num]] start_idx += ins_num example = {"input": i, "conclusions": cs, "is_gold": gs, "ver_prob": tmp_scores} json.dump(example, f) f.write("\n") print(f"\n\n\nSuccess: gen_infer.jsonl has been created at {gen_train_iter_path}.\n\n\n") ########################################### data_files = { 'train': ver_train_iter_path, 'infer':gen_train_src_path # 'infer': unlabeled_gen_train_iter_path } datasets = load_dataset('json', data_files=data_files, download_mode="force_redownload") train_dataset = datasets["train"] infer_dataset = datasets["infer"] # Select random subset np.random.seed(int(time.time())) train_dataset = train_dataset.select(np.random.choice(np.arange(len(train_dataset["input"])), ver_train_samples_per_iter, replace=False)) infer_examples = infer_dataset.select(np.random.choice(np.arange(len(infer_dataset["input"])), gen_train_samples_per_iter, replace=False)) #load config config = AutoConfig.from_pretrained(VER_MODEL_PATH) # load tokenizer tokenizer = AutoTokenizer.from_pretrained(VER_MODEL_PATH, use_fast=True) special_tokens=['[SEP]','[MASK]'] if not all([t in tokenizer.vocab for t in special_tokens]): # add speical token only if they are not found special_tokens_dict = {'additional_special_tokens': special_tokens} num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) added_tokens = tokenizer.get_added_vocab() print(f"\nAdded special tokens {special_tokens} into tokenizer vocab.\n") encoder_max_length = 512 def process_infer_dataset_sample(examples): all_cs = [] all_selected_ids = [] all_gs = [] for id, (i, cs,gs) in enumerate(zip(examples["input"], examples["conclusions"],examples["is_gold"])): ins_num = min(len(cs),gen_per_device_examples_num)-1 #if not do_train else len(cs) gold_id = gs.index(1) all_ids = list(range(len(gs))) all_ids.remove(gold_id) selected_ids = list(np.random.choice(all_ids,ins_num,replace=False)) selected_ids.append(gold_id) all_selected_ids.append(selected_ids) tmp_cs = [cs[j] for j in selected_ids] all_cs.append(tmp_cs) all_gs.append([gs[j] for j in selected_ids]) # print(tmp_cs,[gs[j] for j in selected_ids],selected_ids) examples['conclusions'] = all_cs examples['is_gold']= all_gs examples['selected_ids'] = all_selected_ids return examples def process_data_to_model_inputs(examples): inputs = [] ids = [] all_selected_ids = [] for id, (i, cs,gs) in enumerate(zip(examples["input"], examples["conclusions"],examples["is_gold"])): for c in cs: inputs.append(i.replace("[MASK]", c)) ids.extend([id]*len(cs)) # inputs = [i.replace("[MASK]", c) for i,c in zip(examples["input"],examples["conclusion"])] tokenized_inputs = tokenizer( inputs, padding="max_length", truncation=True, max_length=encoder_max_length ) model_inputs = {} model_inputs['ids']=ids model_inputs["input_ids"] = tokenized_inputs.input_ids model_inputs["attention_mask"] = tokenized_inputs.attention_mask model_inputs["labels"] = [l for ls in examples["is_gold"] for l in ls]#[ls[index] for j,ls in enumerate(examples["is_gold"]) for index in all_selected_ids[j]] # since above lists are references, the following line changes the 0 index for all samples # print(model_inputs['labels']) return model_inputs training_args = TrainingArguments( # evaluation_strategy="steps", per_device_train_batch_size=ver_per_device_train_batch_size, per_device_eval_batch_size=ver_per_device_eval_batch_size, fp16=False, half_precision_backend="amp", output_dir=args.output_dir, logging_steps=100, save_strategy="no", gradient_accumulation_steps=ver_gradient_accumulation_steps, num_train_epochs=1, do_eval=False, learning_rate=ver_learning_rate, eval_accumulation_steps=1 ) ## map train data column_names = train_dataset.column_names train_dataset = train_dataset.map( process_data_to_model_inputs, # do_train=True, batched=True, remove_columns=column_names, num_proc=8, batch_size=16, load_from_cache_file=False, # necessary ) infer_examples = infer_examples.map( process_infer_dataset_sample, batched=True, num_proc=8, batch_size=16, load_from_cache_file=False ) column_names = infer_examples.column_names infer_dataset = infer_examples.map( process_data_to_model_inputs, # do_train=False, batched=True, num_proc=8, batch_size=16, remove_columns=column_names, load_from_cache_file=False, # necessary ) # set Python list to PyTorch tensor train_dataset.set_format(type="torch", columns=["input_ids", "attention_mask", "labels"]) infer_dataset.set_format(type="torch", columns=["input_ids", "attention_mask", "labels"]) # # enable fp16 apex training model = AutoModelForSequenceClassification.from_pretrained(VER_MODEL_PATH) model.resize_token_embeddings(len(tokenizer)) # instantiate trainer trainer = Trainer( model=model, tokenizer=tokenizer, args=training_args, compute_metrics=compute_metrics, train_dataset=train_dataset, eval_dataset=train_dataset ) if __name__ == "__main__": trainer.train() trainer.save_model() trainer.save_state() pred = trainer.predict(infer_dataset, ignore_keys=["encoder_last_hidden_state"]) create_ver_infer(infer_examples, pred)
ContextualSP/logigan/pre-training/verifier_multi_es.py/0
{ "file_path": "ContextualSP/logigan/pre-training/verifier_multi_es.py", "repo_id": "ContextualSP", "token_count": 3015 }
241
recursive-include matchzoo/datasets/toy *
ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/MANIFEST.in/0
{ "file_path": "ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/MANIFEST.in", "repo_id": "ContextualSP", "token_count": 16 }
242
import typing import matchzoo as mz from .preparer import Preparer from matchzoo.engine.base_task import BaseTask from matchzoo.engine.base_model import BaseModel from matchzoo.engine.base_callback import BaseCallback from matchzoo.engine.base_preprocessor import BasePreprocessor def prepare( task: BaseTask, model_class: typing.Type[BaseModel], data_pack: mz.DataPack, callback: typing.Optional[BaseCallback] = None, preprocessor: typing.Optional[BasePreprocessor] = None, embedding: typing.Optional['mz.Embedding'] = None, config: typing.Optional[dict] = None, ): """ A simple shorthand for using :class:`matchzoo.Preparer`. `config` is used to control specific behaviors. The default `config` will be updated accordingly if a `config` dictionary is passed. e.g. to override the default `bin_size`, pass `config={'bin_size': 15}`. :param task: Task. :param model_class: Model class. :param data_pack: DataPack used to fit the preprocessor. :param callback: Callback used to padding a batch. (default: the default callback of `model_class`) :param preprocessor: Preprocessor used to fit the `data_pack`. (default: the default preprocessor of `model_class`) :param embedding: Embedding to build a embedding matrix. If not set, then a correctly shaped randomized matrix will be built. :param config: Configuration of specific behaviors. (default: return value of `mz.Preparer.get_default_config()`) :return: A tuple of `(model, preprocessor, data_generator_builder, embedding_matrix)`. """ preparer = Preparer(task=task, config=config) return preparer.prepare( model_class=model_class, data_pack=data_pack, callback=callback, preprocessor=preprocessor, embedding=embedding )
ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/auto/preparer/prepare.py/0
{ "file_path": "ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/auto/preparer/prepare.py", "repo_id": "ContextualSP", "token_count": 636 }
243
"""A basic class representing a Dataset.""" import typing import math from collections import Iterable import numpy as np import pandas as pd from torch.utils import data import matchzoo as mz from matchzoo.engine.base_callback import BaseCallback class Dataset(data.IterableDataset): """ Dataset that is built from a data pack. :param data_pack: DataPack to build the dataset. :param mode: One of "point", "pair", and "list". (default: "point") :param num_dup: Number of duplications per instance, only effective when `mode` is "pair". (default: 1) :param num_neg: Number of negative samples per instance, only effective when `mode` is "pair". (default: 1) :param batch_size: Batch size. (default: 32) :param resample: Either to resample for each epoch, only effective when `mode` is "pair". (default: `True`) :param shuffle: Either to shuffle the samples/instances. (default: `True`) :param sort: Whether to sort data according to length_right. (default: `False`) :param callbacks: Callbacks. See `matchzoo.dataloader.callbacks` for more details. Examples: >>> import matchzoo as mz >>> data_pack = mz.datasets.toy.load_data(stage='train') >>> preprocessor = mz.preprocessors.BasicPreprocessor() >>> data_processed = preprocessor.fit_transform(data_pack) >>> dataset_point = mz.dataloader.Dataset( ... data_processed, mode='point', batch_size=32) >>> len(dataset_point) 4 >>> dataset_pair = mz.dataloader.Dataset( ... data_processed, mode='pair', num_dup=2, num_neg=2, batch_size=32) >>> len(dataset_pair) 1 """ def __init__( self, data_pack: mz.DataPack, mode='point', num_dup: int = 1, num_neg: int = 1, batch_size: int = 32, resample: bool = False, shuffle: bool = True, sort: bool = False, callbacks: typing.List[BaseCallback] = None ): """Init.""" if callbacks is None: callbacks = [] if mode not in ('point', 'pair', 'list'): raise ValueError(f"{mode} is not a valid mode type." f"Must be one of `point`, `pair` or `list`.") if shuffle and sort: raise ValueError(f"parameters `shuffle` and `sort` conflict, " f"should not both be `True`.") data_pack = data_pack.copy() self._mode = mode self._num_dup = num_dup self._num_neg = num_neg self._batch_size = batch_size self._resample = (resample if mode != 'point' else False) self._shuffle = shuffle self._sort = sort self._orig_relation = data_pack.relation self._callbacks = callbacks if mode == 'pair': data_pack.relation = self._reorganize_pair_wise( relation=self._orig_relation, num_dup=num_dup, num_neg=num_neg ) self._data_pack = data_pack self._batch_indices = None self.reset_index() def __getitem__(self, item) -> typing.Tuple[dict, np.ndarray]: """Get a batch from index idx. :param item: the index of the batch. """ if isinstance(item, slice): indices = sum(self._batch_indices[item], []) elif isinstance(item, Iterable): indices = [self._batch_indices[i] for i in item] else: indices = self._batch_indices[item] batch_data_pack = self._data_pack[indices] self._handle_callbacks_on_batch_data_pack(batch_data_pack) x, y = batch_data_pack.unpack() self._handle_callbacks_on_batch_unpacked(x, y) return x, y def __len__(self) -> int: """Get the total number of batches.""" return len(self._batch_indices) def __iter__(self): """Create a generator that iterate over the Batches.""" if self._resample or self._shuffle: self.on_epoch_end() for i in range(len(self)): yield self[i] def on_epoch_end(self): """Reorganize the index array if needed.""" if self._resample: self.resample_data() self.reset_index() def resample_data(self): """Reorganize data.""" if self.mode != 'point': self._data_pack.relation = self._reorganize_pair_wise( relation=self._orig_relation, num_dup=self._num_dup, num_neg=self._num_neg ) def reset_index(self): """ Set the :attr:`_batch_indices`. Here the :attr:`_batch_indices` records the index of all the instances. """ # index pool: index -> instance index if self._mode == 'point': num_instances = len(self._data_pack) index_pool = list(range(num_instances)) elif self._mode == 'pair': index_pool = [] step_size = self._num_neg + 1 num_instances = int(len(self._data_pack) / step_size) for i in range(num_instances): lower = i * step_size upper = (i + 1) * step_size indices = list(range(lower, upper)) if indices: index_pool.append(indices) elif self._mode == 'list': raise NotImplementedError( f'{self._mode} dataset not implemented.') else: raise ValueError(f"{self._mode} is not a valid mode type" f"Must be one of `point`, `pair` or `list`.") if self._shuffle: np.random.shuffle(index_pool) if self._sort: old_index_pool = index_pool max_instance_right_length = [] for row in range(len(old_index_pool)): instance = self._data_pack[old_index_pool[row]].unpack()[0] max_instance_right_length.append(max(instance['length_right'])) sort_index = np.argsort(max_instance_right_length) index_pool = [old_index_pool[index] for index in sort_index] # batch_indices: index -> batch of indices self._batch_indices = [] for i in range(math.ceil(num_instances / self._batch_size)): lower = self._batch_size * i upper = self._batch_size * (i + 1) candidates = index_pool[lower:upper] if self._mode == 'pair': candidates = sum(candidates, []) self._batch_indices.append(candidates) def _handle_callbacks_on_batch_data_pack(self, batch_data_pack): for callback in self._callbacks: callback.on_batch_data_pack(batch_data_pack) def _handle_callbacks_on_batch_unpacked(self, x, y): for callback in self._callbacks: callback.on_batch_unpacked(x, y) @property def callbacks(self): """`callbacks` getter.""" return self._callbacks @callbacks.setter def callbacks(self, value): """`callbacks` setter.""" self._callbacks = value @property def num_neg(self): """`num_neg` getter.""" return self._num_neg @num_neg.setter def num_neg(self, value): """`num_neg` setter.""" self._num_neg = value self.resample_data() self.reset_index() @property def num_dup(self): """`num_dup` getter.""" return self._num_dup @num_dup.setter def num_dup(self, value): """`num_dup` setter.""" self._num_dup = value self.resample_data() self.reset_index() @property def mode(self): """`mode` getter.""" return self._mode @property def batch_size(self): """`batch_size` getter.""" return self._batch_size @batch_size.setter def batch_size(self, value): """`batch_size` setter.""" self._batch_size = value self.reset_index() @property def shuffle(self): """`shuffle` getter.""" return self._shuffle @shuffle.setter def shuffle(self, value): """`shuffle` setter.""" self._shuffle = value self.reset_index() @property def sort(self): """`sort` getter.""" return self._sort @sort.setter def sort(self, value): """`sort` setter.""" self._sort = value self.reset_index() @property def resample(self): """`resample` getter.""" return self._resample @resample.setter def resample(self, value): """`resample` setter.""" self._resample = value self.reset_index() @property def batch_indices(self): """`batch_indices` getter.""" return self._batch_indices @classmethod def _reorganize_pair_wise( cls, relation: pd.DataFrame, num_dup: int = 1, num_neg: int = 1 ): """Re-organize the data pack as pair-wise format.""" pairs = [] groups = relation.sort_values( 'label', ascending=False).groupby('id_left') for _, group in groups: labels = group.label.unique() for label in labels[:-1]: pos_samples = group[group.label == label] pos_samples = pd.concat([pos_samples] * num_dup) neg_samples = group[group.label < label] for _, pos_sample in pos_samples.iterrows(): pos_sample = pd.DataFrame([pos_sample]) neg_sample = neg_samples.sample(num_neg, replace=True) pairs.extend((pos_sample, neg_sample)) new_relation = pd.concat(pairs, ignore_index=True) return new_relation
ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/dataloader/dataset.py/0
{ "file_path": "ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/dataloader/dataset.py", "repo_id": "ContextualSP", "token_count": 4624 }
244
"""SNLI data loader.""" import typing from pathlib import Path import pandas as pd import matchzoo from matchzoo.engine.base_task import BaseTask _url = "https://nlp.stanford.edu/projects/snli/snli_1.0.zip" def load_data( stage: str = 'train', task: typing.Union[str, BaseTask] = 'classification', target_label: str = 'entailment', return_classes: bool = False ) -> typing.Union[matchzoo.DataPack, tuple]: """ Load SNLI data. :param stage: One of `train`, `dev`, and `test`. (default: `train`) :param task: Could be one of `ranking`, `classification` or a :class:`matchzoo.engine.BaseTask` instance. (default: `classification`) :param target_label: If `ranking`, chose one of `entailment`, `contradiction` and `neutral` as the positive label. (default: `entailment`) :param return_classes: `True` to return classes for classification task, `False` otherwise. :return: A DataPack unless `task` is `classificiation` and `return_classes` is `True`: a tuple of `(DataPack, classes)` in that case. """ if stage not in ('train', 'dev', 'test'): raise ValueError(f"{stage} is not a valid stage." f"Must be one of `train`, `dev`, and `test`.") data_root = _download_data() file_path = data_root.joinpath(f'snli_1.0_{stage}.txt') data_pack = _read_data(file_path, task, target_label) if task == 'ranking' or isinstance(task, matchzoo.tasks.Ranking): return data_pack elif task == 'classification' or isinstance( task, matchzoo.tasks.Classification): classes = ['entailment', 'contradiction', 'neutral'] if return_classes: return data_pack, classes else: return data_pack else: raise ValueError(f"{task} is not a valid task." f"Must be one of `Ranking` and `Classification`.") def _download_data(): ref_path = matchzoo.utils.get_file( 'snli', _url, extract=True, cache_dir=matchzoo.USER_DATA_DIR, cache_subdir='snli' ) return Path(ref_path).parent.joinpath('snli_1.0') def _read_data(path, task, target_label): table = pd.read_csv(path, sep='\t') df = pd.DataFrame({ 'text_left': table['sentence1'], 'text_right': table['sentence2'], 'label': table['gold_label'] }) df = df.dropna(axis=0, how='any').reset_index(drop=True) filter_id = df[df['label'] == '-'].index.tolist() df.drop(filter_id, inplace=True) if task == 'ranking' or isinstance(task, matchzoo.tasks.Ranking): if target_label not in ['entailment', 'contradiction', 'neutral']: raise ValueError(f"{target_label} is not a valid target label." f"Must be one of `entailment`, `contradiction`" f" and `neutral`") df['label'] = (df['label'] == target_label) elif task == 'classification' or isinstance( task, matchzoo.tasks.Classification): classes = ['entailment', 'contradiction', 'neutral'] df['label'] = df['label'].apply(classes.index) else: raise ValueError(f"{task} is not a valid task." f"Must be one of `Ranking` and `Classification`.") return matchzoo.pack(df, task)
ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/datasets/snli/load_data.py/0
{ "file_path": "ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/datasets/snli/load_data.py", "repo_id": "ContextualSP", "token_count": 1427 }
245
"""Hyper parameter search spaces wrapping `hyperopt`.""" import typing import numbers import hyperopt import hyperopt.pyll.base class HyperoptProxy(object): """ Hyperopt proxy class. See `hyperopt`'s documentation for more details: https://github.com/hyperopt/hyperopt/wiki/FMin Reason of these wrappers: A hyper space in `hyperopt` requires a `label` to instantiate. This `label` is used later as a reference to original hyper space that is sampled. In `matchzoo`, hyper spaces are used in :class:`matchzoo.engine.Param`. Only if a hyper space's label matches its parent :class:`matchzoo.engine.Param`'s name, `matchzoo` can correctly back-refrenced the parameter got sampled. This can be done by asking the user always use the same name for a parameter and its hyper space, but typos can occur. As a result, these wrappers are created to hide hyper spaces' `label`, and always correctly bind them with its parameter's name. Examples:: >>> import matchzoo as mz >>> from hyperopt.pyll.stochastic import sample Basic Usage: >>> model = mz.models.DenseBaseline() >>> sample(model.params.hyper_space) # doctest: +SKIP {'mlp_num_layers': 1.0, 'mlp_num_units': 274.0} Arithmetic Operations: >>> new_space = 2 ** mz.hyper_spaces.quniform(2, 6) >>> model.params.get('mlp_num_layers').hyper_space = new_space >>> sample(model.params.hyper_space) # doctest: +SKIP {'mlp_num_layers': 8.0, 'mlp_num_units': 292.0} """ def __init__( self, hyperopt_func: typing.Callable[..., hyperopt.pyll.Apply], **kwargs ): """ :class:`HyperoptProxy` constructor. :param hyperopt_func: Target `hyperopt.hp` function to proxy. :param kwargs: Keyword arguments of the proxy function, must pass all parameters in `hyperopt_func`. """ self._func = hyperopt_func self._kwargs = kwargs def convert(self, name: str) -> hyperopt.pyll.Apply: """ Attach `name` as `hyperopt.hp`'s `label`. :param name: :return: a `hyperopt` ready search space """ return self._func(name, **self._kwargs) def __add__(self, other): """__add__.""" return _wrap_as_composite_func(self, other, lambda x, y: x + y) def __radd__(self, other): """__radd__.""" return _wrap_as_composite_func(self, other, lambda x, y: x + y) def __sub__(self, other): """__sub__.""" return _wrap_as_composite_func(self, other, lambda x, y: x - y) def __rsub__(self, other): """__rsub__.""" return _wrap_as_composite_func(self, other, lambda x, y: y - x) def __mul__(self, other): """__mul__.""" return _wrap_as_composite_func(self, other, lambda x, y: x * y) def __rmul__(self, other): """__rmul__.""" return _wrap_as_composite_func(self, other, lambda x, y: x * y) def __truediv__(self, other): """__truediv__.""" return _wrap_as_composite_func(self, other, lambda x, y: x / y) def __rtruediv__(self, other): """__rtruediv__.""" return _wrap_as_composite_func(self, other, lambda x, y: y / x) def __floordiv__(self, other): """__floordiv__.""" return _wrap_as_composite_func(self, other, lambda x, y: x // y) def __rfloordiv__(self, other): """__rfloordiv__.""" return _wrap_as_composite_func(self, other, lambda x, y: y // x) def __pow__(self, other): """__pow__.""" return _wrap_as_composite_func(self, other, lambda x, y: x ** y) def __rpow__(self, other): """__rpow__.""" return _wrap_as_composite_func(self, other, lambda x, y: y ** x) def __neg__(self): """__neg__.""" return _wrap_as_composite_func(self, None, lambda x, _: -x) def _wrap_as_composite_func(self, other, func): def _wrapper(name, **kwargs): return func(self._func(name, **kwargs), other) return HyperoptProxy(_wrapper, **self._kwargs) class choice(HyperoptProxy): """:func:`hyperopt.hp.choice` proxy.""" def __init__(self, options: list): """ :func:`hyperopt.hp.choice` proxy. :param options: options to search from """ super().__init__(hyperopt_func=hyperopt.hp.choice, options=options) self._options = options def __str__(self): """:return: `str` representation of the hyper space.""" return f'choice in {self._options}' class quniform(HyperoptProxy): """:func:`hyperopt.hp.quniform` proxy.""" def __init__( self, low: numbers.Number, high: numbers.Number, q: numbers.Number = 1 ): """ :func:`hyperopt.hp.quniform` proxy. If using with integer values, then `high` is exclusive. :param low: lower bound of the space :param high: upper bound of the space :param q: similar to the `step` in the python built-in `range` """ super().__init__(hyperopt_func=hyperopt.hp.quniform, low=low, high=high, q=q) self._low = low self._high = high self._q = q def __str__(self): """:return: `str` representation of the hyper space.""" return f'quantitative uniform distribution in ' \ f'[{self._low}, {self._high}), with a step size of {self._q}' class uniform(HyperoptProxy): """:func:`hyperopt.hp.uniform` proxy.""" def __init__( self, low: numbers.Number, high: numbers.Number ): """ :func:`hyperopt.hp.uniform` proxy. :param low: lower bound of the space :param high: upper bound of the space """ super().__init__(hyperopt_func=hyperopt.hp.uniform, low=low, high=high) self._low = low self._high = high def __str__(self): """:return: `str` representation of the hyper space.""" return f'uniform distribution in [{self._low}, {self._high})' def sample(space): """ Take a sample in the hyper space. This method is stateless, so the distribution of the samples is different from that of `tune` call. This function just gives a general idea of what a sample from the `space` looks like. Example: >>> import matchzoo as mz >>> space = mz.models.DenseBaseline.get_default_params().hyper_space >>> mz.hyper_spaces.sample(space) # doctest: +ELLIPSIS {'mlp_num_fan_out': ...} """ return hyperopt.pyll.stochastic.sample(space)
ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/engine/hyper_spaces.py/0
{ "file_path": "ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/engine/hyper_spaces.py", "repo_id": "ContextualSP", "token_count": 2925 }
246
from .dense_baseline import DenseBaseline from .dssm import DSSM from .cdssm import CDSSM from .drmm import DRMM from .drmmtks import DRMMTKS from .esim import ESIM from .knrm import KNRM from .conv_knrm import ConvKNRM from .bimpm import BiMPM from .matchlstm import MatchLSTM from .arci import ArcI from .arcii import ArcII from .bert import Bert from .mvlstm import MVLSTM from .match_pyramid import MatchPyramid from .anmm import aNMM from .hbmp import HBMP from .duet import DUET from .diin import DIIN from .match_srnn import MatchSRNN def list_available() -> list: from matchzoo.engine.base_model import BaseModel from matchzoo.utils import list_recursive_concrete_subclasses return list_recursive_concrete_subclasses(BaseModel)
ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/models/__init__.py/0
{ "file_path": "ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/models/__init__.py", "repo_id": "ContextualSP", "token_count": 261 }
247
"""An implementation of HBMP Model.""" import typing import copy import torch import torch.nn as nn from matchzoo.engine import hyper_spaces from matchzoo.engine.param_table import ParamTable from matchzoo.engine.param import Param from matchzoo.engine.base_model import BaseModel class HBMP(BaseModel): """ HBMP model. Examples: >>> model = HBMP() >>> model.params['embedding_input_dim'] = 200 >>> model.params['embedding_output_dim'] = 100 >>> model.params['mlp_num_layers'] = 1 >>> model.params['mlp_num_units'] = 10 >>> model.params['mlp_num_fan_out'] = 10 >>> model.params['mlp_activation_func'] = nn.LeakyReLU(0.1) >>> model.params['lstm_hidden_size'] = 5 >>> model.params['lstm_num'] = 3 >>> model.params['num_layers'] = 3 >>> model.params['dropout_rate'] = 0.1 >>> model.guess_and_fill_missing_params(verbose=0) >>> model.build() """ @classmethod def get_default_params(cls) -> ParamTable: """:return: model default parameters.""" params = super().get_default_params( with_embedding=True, with_multi_layer_perceptron=True) params.add(Param(name='lstm_hidden_size', value=5, desc="Integer, the hidden size of the " "bi-directional LSTM layer.")) params.add(Param(name='lstm_num', value=3, desc="Integer, number of LSTM units")) params.add(Param(name='num_layers', value=1, desc="Integer, number of LSTM layers.")) params.add(Param( name='dropout_rate', value=0.0, hyper_space=hyper_spaces.quniform( low=0.0, high=0.8, q=0.01), desc="The dropout rate." )) return params def build(self): """ Build model structure. HBMP use Siamese arthitecture. """ self.embedding = self._make_default_embedding_layer() encoder_layer = nn.LSTM( input_size=self._params['embedding_output_dim'], hidden_size=self._params['lstm_hidden_size'], num_layers=self._params['num_layers'], dropout=self._params['dropout_rate'], batch_first=True, bidirectional=True) self.encoder = nn.ModuleList( [copy.deepcopy(encoder_layer) for _ in range(self._params['lstm_num'])]) self.max_pool = nn.AdaptiveMaxPool1d(1) self.mlp = self._make_multi_layer_perceptron_layer( self._params['lstm_hidden_size'] * 24 ) self.out = self._make_output_layer( self._params['mlp_num_fan_out'] ) def forward(self, inputs): """Forward.""" # Scalar dimensions referenced here: # B = batch size (number of sequences) # D = embedding size # L = `input_left` sequence length # R = `input_right` sequence length # F = hidden size of LSTM layer # Left input and right input. # shape = [B, L] # shape = [B, R] input_left, input_right = inputs['text_left'], inputs['text_right'] batch_size = input_left.shape[0] state_shape = ( 2 * self._params['num_layers'], batch_size, self._params['lstm_hidden_size'] ) # shape = [B, L, D] # shape = [B, R, D] embed_left = self.embedding(input_left.long()) embed_right = self.embedding(input_right.long()) out_left = [] h_left = c_left = torch.zeros(*state_shape, device=input_left.device) for layer in self.encoder: out, (h_left, c_left) = layer(embed_left, (h_left, c_left)) out_left.append(self.max_pool(out.transpose(1, 2)).squeeze(2)) out_right = [] h_right = c_right = torch.zeros(*state_shape, device=input_left.device) for layer in self.encoder: out, (h_right, c_right) = layer(embed_right, (h_right, c_right)) out_right.append(self.max_pool(out.transpose(1, 2)).squeeze(2)) # shape = [B, 6 * F] encode_left = torch.cat(out_left, 1) encode_right = torch.cat(out_right, 1) embed_minus = torch.abs(encode_left - encode_right) embed_multiply = encode_left * encode_right encode_concat = torch.cat( [encode_left, encode_right, embed_minus, embed_multiply], 1) output = self.mlp(encode_concat) output = self.out(output) return output
ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/models/hbmp.py/0
{ "file_path": "ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/models/hbmp.py", "repo_id": "ContextualSP", "token_count": 2187 }
248
from .unit import Unit class Lowercase(Unit): """Process unit for text lower case.""" def transform(self, input_: list) -> list: """ Convert list of tokens to lower case. :param input_: list of tokens. :return tokens: lower-cased list of tokens. """ return [token.lower() for token in input_]
ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/preprocessors/units/lowercase.py/0
{ "file_path": "ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/preprocessors/units/lowercase.py", "repo_id": "ContextualSP", "token_count": 135 }
249
from .trainer import Trainer
ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/trainers/__init__.py/0
{ "file_path": "ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/trainers/__init__.py", "repo_id": "ContextualSP", "token_count": 7 }
250
import shutil import pandas as pd import pytest from matchzoo import DataPack, load_data_pack @pytest.fixture def data_pack(): relation = [['qid0', 'did0', 1], ['qid1', 'did1', 0]] left = [['qid0', [1, 2]], ['qid1', [2, 3]]] right = [['did0', [2, 3, 4]], ['did1', [3, 4, 5]]] relation = pd.DataFrame(relation, columns=['id_left', 'id_right', 'label']) left = pd.DataFrame(left, columns=['id_left', 'text_left']) left.set_index('id_left', inplace=True) right = pd.DataFrame(right, columns=['id_right', 'text_right']) right.set_index('id_right', inplace=True) return DataPack(relation=relation, left=left, right=right) def test_length(data_pack): num_examples = 2 assert len(data_pack) == num_examples def test_getter(data_pack): assert data_pack.relation.iloc[0].values.tolist() == ['qid0', 'did0', 1] assert data_pack.relation.iloc[1].values.tolist() == ['qid1', 'did1', 0] assert data_pack.left.loc['qid0', 'text_left'] == [1, 2] assert data_pack.right.loc['did1', 'text_right'] == [3, 4, 5] def test_save_load(data_pack): dirpath = '.tmpdir' data_pack.save(dirpath) dp = load_data_pack(dirpath) assert len(data_pack) == 2 assert len(dp) == 2 shutil.rmtree(dirpath)
ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/tests/data_pack/test_datapack.py/0
{ "file_path": "ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/tests/data_pack/test_datapack.py", "repo_id": "ContextualSP", "token_count": 581 }
251
import torch import pytest from pathlib import Path import shutil import matchzoo as mz @pytest.fixture(scope='module') def task(): return mz.tasks.Ranking(losses=mz.losses.RankCrossEntropyLoss()) @pytest.fixture(scope='module') def train_raw(task): return mz.datasets.toy.load_data('train', task)[:10] @pytest.fixture(scope='module') def model_class(): return mz.models.DenseBaseline @pytest.fixture(scope='module') def embedding(): return mz.datasets.toy.load_embedding() @pytest.fixture(scope='module') def setup(task, model_class, train_raw, embedding): return mz.auto.prepare( task=task, model_class=model_class, data_pack=train_raw, embedding=embedding ) @pytest.fixture(scope='module') def model(setup): return setup[0] @pytest.fixture(scope='module') def preprocessor(setup): return setup[1] @pytest.fixture(scope='module') def dataset_builder(setup): return setup[2] @pytest.fixture(scope='module') def dataloader_builder(setup): return setup[3] @pytest.fixture(scope='module') def dataloader(train_raw, preprocessor, dataset_builder, dataloader_builder): return dataloader_builder.build( dataset_builder.build(preprocessor.transform(train_raw))) @pytest.fixture(scope='module') def optimizer(model): return torch.optim.Adam(model.parameters()) @pytest.fixture(scope='module') def scheduler(optimizer): return torch.optim.lr_scheduler.StepLR(optimizer, step_size=10) @pytest.fixture(scope='module') def save_dir(): return Path('.matchzoo_test_save_load_tmpdir') @pytest.fixture(scope='module') def trainer( model, optimizer, dataloader, scheduler, save_dir ): return mz.trainers.Trainer( model=model, optimizer=optimizer, trainloader=dataloader, validloader=dataloader, epochs=4, validate_interval=2, patience=1, scheduler=scheduler, clip_norm=10, save_dir=save_dir, save_all=True, verbose=1, ) @pytest.mark.slow def test_trainer(trainer, dataloader, save_dir): trainer.run() assert trainer.evaluate(dataloader) assert trainer.predict(dataloader) is not None # Save model model_checkpoint = save_dir.joinpath('model.pt') trainer.save_model() trainer.restore_model(model_checkpoint) # Save model trainer_checkpoint = save_dir.joinpath('trainer.pt') trainer.save() trainer.restore(trainer_checkpoint) if save_dir.exists(): shutil.rmtree(save_dir)
ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/tests/trainer/test_trainer.py/0
{ "file_path": "ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/tests/trainer/test_trainer.py", "repo_id": "ContextualSP", "token_count": 1046 }
252
<jupyter_start><jupyter_code>import torch import numpy as np import pandas as pd import matchzoo as mz print('matchzoo version', mz.__version__) ranking_task = mz.tasks.Ranking(losses=mz.losses.RankHingeLoss()) ranking_task.metrics = [ mz.metrics.NormalizedDiscountedCumulativeGain(k=3), mz.metrics.NormalizedDiscountedCumulativeGain(k=5), mz.metrics.MeanAveragePrecision() ] print("`ranking_task` initialized with metrics", ranking_task.metrics) print('data loading ...') train_pack_raw = mz.datasets.wiki_qa.load_data('train', task=ranking_task) dev_pack_raw = mz.datasets.wiki_qa.load_data('dev', task=ranking_task, filtered=True) test_pack_raw = mz.datasets.wiki_qa.load_data('test', task=ranking_task, filtered=True) print('data loaded as `train_pack_raw` `dev_pack_raw` `test_pack_raw`')<jupyter_output>data loading ... data loaded as `train_pack_raw` `dev_pack_raw` `test_pack_raw`
ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/tutorials/ranking/init.ipynb/0
{ "file_path": "ContextualSP/poset_decoding/traversal_path_prediction/MatchZoo-py/tutorials/ranking/init.ipynb", "repo_id": "ContextualSP", "token_count": 347 }
253
#!/usr/bin/env bash export seed=1 export config_file=train_configs/concat.none.jsonnet export model_file=checkpoints_cosql/cosql_concat_none_model export tables_file=dataset_cosql/tables.json export database_path=dataset_cosql/database export dataset_path=dataset_cosql export train_data_path=dataset_cosql/train.json export validation_data_path=dataset_cosql/dev.json export pretrained_file=glove/glove.twitter.27B.100d.txt allennlp train -s ${model_file} ${config_file} \ --include-package dataset_reader.sparc_reader \ --include-package models.sparc_parser \ -o "{\"model.serialization_dir\":\"${model_file}\",\"random_seed\":\"${seed}\",\"numpy_seed\":\"${seed}\",\"pytorch_seed\":\"${seed}\",\"dataset_reader.tables_file\":\"${tables_file}\",\"dataset_reader.database_path\":\"${database_path}\",\"train_data_path\":\"${train_data_path}\",\"validation_data_path\":\"${validation_data_path}\",\"model.text_embedder.tokens.pretrained_file\":\"${pretrained_file}\",\"model.dataset_path\":\"${dataset_path}\"}"
ContextualSP/semantic_parsing_in_context/bash_files/linux/train_cosql.bash/0
{ "file_path": "ContextualSP/semantic_parsing_in_context/bash_files/linux/train_cosql.bash", "repo_id": "ContextualSP", "token_count": 367 }
254
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. """ Mainly borrowed from `allennlp.data.fields.knowledge_graph_filed.py` ############################################################ # NOTICE # # we maintain this file for not sorting the entities. # # which is important for our model! # ############################################################ Author: Qian Liu """ """ A ``KnowledgeGraph`` is a graphical representation of some structured knowledge source: say a table, figure or an explicit knowledge base. """ from typing import Dict, List, Set class KnowledgeGraph: """ A ``KnowledgeGraph`` represents a collection of entities and their relationships. The ``KnowledgeGraph`` currently stores (untyped) neighborhood information and text representations of each entity (if there is any). The knowledge base itself can be a table (like in WikitableQuestions), a figure (like in NLVR) or some other structured knowledge source. This abstract class needs to be inherited for implementing the functionality appropriate for a given KB. All of the parameters listed below are stored as public attributes. Parameters ---------- entities : ``Set[str]`` The string identifiers of the entities in this knowledge graph. We sort this set and store it as a list. The sorting is so that we get a guaranteed consistent ordering across separate runs of the code. neighbors : ``Dict[str, List[str]]`` A mapping from string identifiers to other string identifiers, denoting which entities are neighbors in the graph. entity_text : ``Dict[str, str]`` If you have additional text associated with each entity (other than its string identifier), you can store that here. This might be, e.g., the text in a table cell, or the description of a wikipedia entity. """ def __init__(self, entities: List[str], neighbors: Dict[str, List[str]], neighbors_with_table: Dict[str, List[str]], entity_text: Dict[str, str] = None) -> None: self.entities = entities self.neighbors = neighbors self.neighbors_with_table = neighbors_with_table self.entity_text = entity_text def __eq__(self, other): if isinstance(self, other.__class__): return self.__dict__ == other.__dict__ return NotImplemented
ContextualSP/semantic_parsing_in_context/context/knowledge_graph_filed.py/0
{ "file_path": "ContextualSP/semantic_parsing_in_context/context/knowledge_graph_filed.py", "repo_id": "ContextualSP", "token_count": 856 }
255
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from typing import Any, Dict, List, Sequence, Tuple import torch from context.copy_production_rule_field import CopyProductionRule from allennlp.state_machines.states.state import State from models.states_machine.grammar_state_let import GrammarStatelet from models.states_machine.condition_state_let import ConditionStatelet from models.states_machine.rnn_statelet import RnnStatelet # This syntax is pretty weird and ugly, but it's necessary to make mypy happy with the API that # we've defined. We're using generics to make the type of `combine_states` come out right. See # the note in `state_machines.state.py` for a little more detail. class GrammarBasedState(State['GrammarBasedState']): """ A generic State that's suitable for most models that do grammar-based decoding. We keep around a `group` of states, and each element in the group has a few things: a batch index, an action history, a score, an ``RnnStatelet``, and a ``GrammarStatelet``. We additionally have some information that's independent of any particular group element: a list of all possible actions for all batch instances passed to ``model.forward()``, and a ``extras`` field that you can use if you really need some extra information about each batch instance (like a string description, or other metadata). Finally, we also have a specially-treated, optional ``debug_info`` field. If this is given, it should be an empty list for each group instance when the initial state is created. In that case, we will keep around information about the actions considered at each timestep of decoding and other things that you might want to visualize in a demo. This probably isn't necessary for training, and to get it right we need to copy a bunch of data structures for each new state, so it's best used only at evaluation / demo time. Parameters ---------- batch_indices : ``List[int]`` Passed to super class; see docs there. action_history : ``List[List[int]]`` Passed to super class; see docs there. score : ``List[torch.Tensor]`` Passed to super class; see docs there. rnn_state : ``List[RnnStatelet]`` An ``RnnStatelet`` for every group element. This keeps track of the current decoder hidden state, the previous decoder output, the output from the encoder (for computing attentions), and other things that are typical seq2seq decoder state things. grammar_state : ``List[GrammarStatelet]`` This hold the current grammar state for each element of the group. The ``GrammarStatelet`` keeps track of which actions are currently valid. condition_state: ``List[ConditionStatelet]`` This object will further prune the decoding space, along with some prior knowledge (e.g. the same columns cannot appear in the same select clause) possible_actions : ``List[List[ProductionRule]]`` The list of all possible actions that was passed to ``model.forward()``. We need this so we can recover production strings, which we need to update grammar states. extras : ``List[Any]``, optional (default=None) If you need to keep around some extra data for each instance in the batch, you can put that in here, without adding another field. This should be used `very sparingly`, as there is no type checking or anything done on the contents of this field, and it will just be passed around between ``States`` as-is, without copying. debug_info : ``List[Any]``, optional (default=None). """ def __init__(self, batch_indices: List[int], action_history: List[List[int]], score: List[torch.Tensor], rnn_state: List[RnnStatelet], grammar_state: List[GrammarStatelet], condition_state: List[ConditionStatelet], possible_actions: List[List[CopyProductionRule]], extras: List[Any] = None, debug_info: List = None) -> None: super().__init__(batch_indices, action_history, score) self.rnn_state = rnn_state self.grammar_state = grammar_state self.condition_state = condition_state self.possible_actions = possible_actions self.extras = extras self.debug_info = debug_info def new_state_from_group_index(self, group_index: int, action: int, new_score: torch.Tensor, new_rnn_state: RnnStatelet, considered_actions: List[int] = None, action_probabilities: List[float] = None, attention_weights: torch.Tensor = None) -> 'GrammarBasedState': batch_index = self.batch_indices[group_index] new_action_history = self.action_history[group_index] + [action] production_rule = self.possible_actions[batch_index][action][0] new_grammar_state = self.grammar_state[group_index].take_action(production_rule) new_condition_state = self.condition_state[group_index].take_action(production_rule) if self.debug_info is not None: attention = attention_weights[group_index] if attention_weights is not None else None debug_info = { 'considered_actions': [self.possible_actions[batch_index][action_id].rule for action_id in considered_actions], 'question_attention': attention, 'probabilities': action_probabilities, } new_debug_info = [self.debug_info[group_index] + [debug_info]] else: new_debug_info = None return GrammarBasedState(batch_indices=[batch_index], action_history=[new_action_history], score=[new_score], rnn_state=[new_rnn_state], grammar_state=[new_grammar_state], condition_state=[new_condition_state], possible_actions=self.possible_actions, extras=self.extras, debug_info=new_debug_info) def print_action_history(self, group_index: int = None) -> None: scores = self.score if group_index is None else [self.score[group_index]] batch_indices = self.batch_indices if group_index is None else [self.batch_indices[group_index]] histories = self.action_history if group_index is None else [self.action_history[group_index]] for score, batch_index, action_history in zip(scores, batch_indices, histories): print(' ', score.detach().cpu().numpy()[0], [self.possible_actions[batch_index][action][0] for action in action_history]) def get_valid_actions(self) -> List[Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]]: """ Returns a list of valid actions for each element of the group. Note the validation is applied on two functions, one is grammar state's filter, another is condition state's filter. """ return [condition_state.get_valid_actions(grammar_state.get_valid_actions()) for condition_state, grammar_state in zip(self.condition_state, self.grammar_state)] def is_finished(self) -> bool: if len(self.batch_indices) != 1: raise RuntimeError("is_finished() is only defined with a group_size of 1") return self.grammar_state[0].is_finished() @classmethod def combine_states(cls, states: Sequence['GrammarBasedState']) -> 'GrammarBasedState': batch_indices = [batch_index for state in states for batch_index in state.batch_indices] action_histories = [action_history for state in states for action_history in state.action_history] scores = [score for state in states for score in state.score] rnn_states = [rnn_state for state in states for rnn_state in state.rnn_state] grammar_states = [grammar_state for state in states for grammar_state in state.grammar_state] condition_states = [condition_state for state in states for condition_state in state.condition_state] if states[0].debug_info is not None: debug_info = [debug_info for state in states for debug_info in state.debug_info] else: debug_info = None return GrammarBasedState(batch_indices=batch_indices, action_history=action_histories, score=scores, rnn_state=rnn_states, grammar_state=grammar_states, condition_state=condition_states, possible_actions=states[0].possible_actions, extras=states[0].extras, debug_info=debug_info)
ContextualSP/semantic_parsing_in_context/models/states_machine/grammar_based_state.py/0
{ "file_path": "ContextualSP/semantic_parsing_in_context/models/states_machine/grammar_based_state.py", "repo_id": "ContextualSP", "token_count": 3754 }
256
# Copyright (c) Facebook, Inc. and Microsoft Corporation. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from typing import Dict, List try: import marisa_trie except ModuleNotFoundError: pass class Trie(object): def __init__(self, sequences: List[List[int]] = []): self.trie_dict = {} self.len = 0 if sequences: for sequence in sequences: Trie._add_to_trie(sequence, self.trie_dict) self.len += 1 self.append_trie = None self.bos_token_id = None def append(self, trie, bos_token_id): self.append_trie = trie self.bos_token_id = bos_token_id def add(self, sequence: List[int]): Trie._add_to_trie(sequence, self.trie_dict) self.len += 1 def get(self, prefix_sequence: List[int]): return Trie._get_from_trie( prefix_sequence, self.trie_dict, self.append_trie, self.bos_token_id ) @staticmethod def load_from_dict(trie_dict): trie = Trie() trie.trie_dict = trie_dict trie.len = sum(1 for _ in trie) return trie @staticmethod def _add_to_trie(sequence: List[int], trie_dict: Dict): if sequence: if sequence[0] not in trie_dict: trie_dict[sequence[0]] = {} Trie._add_to_trie(sequence[1:], trie_dict[sequence[0]]) @staticmethod def _get_from_trie( prefix_sequence: List[int], trie_dict: Dict, append_trie=None, bos_token_id: int = None, ): if len(prefix_sequence) == 0: output = list(trie_dict.keys()) if append_trie and bos_token_id in output: output.remove(bos_token_id) output += list(append_trie.trie_dict.keys()) return output elif prefix_sequence[0] in trie_dict: return Trie._get_from_trie( prefix_sequence[1:], trie_dict[prefix_sequence[0]], append_trie, bos_token_id, ) else: if append_trie: return append_trie.get(prefix_sequence) else: return [] def __iter__(self): def _traverse(prefix_sequence, trie_dict): if trie_dict: for next_token in trie_dict: yield from _traverse( prefix_sequence + [next_token], trie_dict[next_token] ) else: yield prefix_sequence return _traverse([], self.trie_dict) def __len__(self): return self.len def __getitem__(self, value): return self.get(value) class MarisaTrie(object): def __init__( self, sequences: List[List[int]] = [], cache_fist_branch=True, max_token_id=256001, ): self.int2char = [chr(i) for i in range(min(max_token_id, 55000))] + ( [chr(i) for i in range(65000, max_token_id + 10000)] if max_token_id >= 55000 else [] ) self.char2int = {self.int2char[i]: i for i in range(max_token_id)} self.cache_fist_branch = cache_fist_branch if self.cache_fist_branch: self.zero_iter = list({sequence[0] for sequence in sequences}) assert len(self.zero_iter) == 1 self.first_iter = list({sequence[1] for sequence in sequences}) self.trie = marisa_trie.Trie( "".join([self.int2char[i] for i in sequence]) for sequence in sequences ) def get(self, prefix_sequence: List[int]): if self.cache_fist_branch and len(prefix_sequence) == 0: return self.zero_iter elif ( self.cache_fist_branch and len(prefix_sequence) == 1 and self.zero_iter == prefix_sequence ): return self.first_iter else: key = "".join([self.int2char[i] for i in prefix_sequence]) return list( { self.char2int[e[len(key)]] for e in self.trie.keys(key) if len(e) > len(key) } ) def __iter__(self): for sequence in self.trie.iterkeys(): yield [self.char2int[e] for e in sequence] def __len__(self): return len(self.trie) def __getitem__(self, value): return self.get(value) class DummyTrieMention(object): def __init__(self, return_values): self._return_values = return_values def get(self, indices=None): return self._return_values class DummyTrieEntity(object): def __init__(self, return_values, codes): self._return_values = list( set(return_values).difference( set( codes[e] for e in ( "start_mention_token", "end_mention_token", "start_entity_token", ) ) ) ) self._codes = codes def get(self, indices, depth=0): if len(indices) == 0 and depth == 0: return self._codes["end_mention_token"] elif len(indices) == 0 and depth == 1: return self._codes["start_entity_token"] elif len(indices) == 0: return self._return_values elif len(indices) == 1 and indices[0] == self._codes["end_entity_token"]: return self._codes["EOS"] else: return self.get(indices[1:], depth=depth + 1)
ContextualSP/unified_parser_text_to_sql/genre/trie.py/0
{ "file_path": "ContextualSP/unified_parser_text_to_sql/genre/trie.py", "repo_id": "ContextualSP", "token_count": 2933 }
257
import os import json import argparse import subprocess from tqdm import tqdm from step1_schema_linking import read_database_schema from train import run_command def running_process(generate_path): # cmd = f"python -m multiprocessing_bpe_encoder \ # --encoder-json ./models/spider_sl/encoder.json \ # --vocab-bpe ./models/spider_sl/vocab.bpe \ # --inputs {generate_path}/train.src \ # --outputs {generate_path}/train.bpe.src \ # --workers 1 \ # --keep-empty" # run_command(cmd) # # cmd = f"python -m multiprocessing_bpe_encoder \ # --encoder-json ./models/spider_sl/encoder.json \ # --vocab-bpe ./models/spider_sl/vocab.bpe \ # --inputs {generate_path}/train.tgt \ # --outputs {generate_path}/train.bpe.tgt \ # --workers 1 \ # --keep-empty" # run_command(cmd) cmd = f"python -m multiprocessing_bpe_encoder \ --encoder-json ./models/spider_sl/encoder.json \ --vocab-bpe ./models/spider_sl/vocab.bpe \ --inputs {generate_path}/dev.src \ --outputs {generate_path}/dev.bpe.src \ --workers 1 \ --keep-empty" run_command(cmd) cmd = f"python -m multiprocessing_bpe_encoder \ --encoder-json ./models/spider_sl/encoder.json \ --vocab-bpe ./models/spider_sl/vocab.bpe \ --inputs {generate_path}/dev.tgt \ --outputs {generate_path}/dev.bpe.tgt \ --workers 1 \ --keep-empty" run_command(cmd) # cmd = f'fairseq-preprocess --source-lang "src" --target-lang "tgt" \ # --trainpref {generate_path}/train.bpe \ # --validpref {generate_path}/dev.bpe \ # --destdir {generate_path}/bin \ # --workers 2 \ # --srcdict ./models/spider_sl/dict.src.txt \ # --tgtdict ./models/spider_sl/dict.tgt.txt ' cmd = f'fairseq-preprocess --source-lang "src" --target-lang "tgt" \ --validpref {generate_path}/dev.bpe \ --destdir {generate_path}/bin \ --workers 2 \ --srcdict ./models/spider_sl/dict.src.txt \ --tgtdict ./models/spider_sl/dict.tgt.txt ' subprocess.Popen( cmd, universal_newlines=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() def build_schema_linking_data(schema, question, item, turn_id, linking_type): source_sequence_list, target_sequence_list = [], [] # column description column_names = [] for i, (t, c) in enumerate(zip(schema['column_types'], schema['column_names_original'])): if c[0] == -1: column_names.append("{0} {1}".format(t, c[1].lower())) else: column_with_alias = "{0}@{1}".format(schema['table_names_original'][c[0]].lower(), c[1].lower()) tag_list = [] if column_with_alias in item['interaction'][turn_id]['exact_match']: tag_list.append('EM') elif column_with_alias in item['interaction'][turn_id]['partial_match']: tag_list.append('PA') if column_with_alias in item['interaction'][turn_id]['value_match']: tag_list.append('VC') # primary-foreign key if i in schema['primary_keys']: tag_list.append('RK') elif i in schema['foreign_keys_col']: tag_list.append('FO') if tag_list != []: column_names.append("{0} {1} {2}".format(' '.join(tag_list), t, column_with_alias)) else: column_names.append("{0} {1}".format(t, column_with_alias)) # table description table_names = [] for t in schema['table_names_original']: tag_list = [] if t in item['interaction'][turn_id]['exact_match']: tag_list.append('EM') elif t in item['interaction'][turn_id]['partial_match']: tag_list.append('PA') if '_nosl' in linking_type or 'not' in linking_type: tag_list = [] if tag_list != []: table_names.append("{0} {1}".format(' '.join(tag_list), t.lower())) else: table_names.append("{0}".format(t.lower())) table_names = ' | '.join(table_names) column_names = ' | '.join(column_names) for structure_schema_list in schema['permutations'][:10]: structure_schema_str = ' | '.join(structure_schema_list) source_sequence = f"<C> {column_names} | <T> {table_names} | <S> {structure_schema_str} | <Q> {question.lower()}" target_sequence = item['interaction'][turn_id]['sql'].lower() source_sequence_list.append(source_sequence) target_sequence_list.append(target_sequence) return source_sequence_list, target_sequence_list def extract_input_and_output(example_lines, linking_type): inputs = [] outputs = [] database_schema_filename = './data/spider/tables.json' schema_tokens, column_names, database_schemas = read_database_schema(database_schema_filename) for item in tqdm(example_lines): question = item['interaction'][0]['utterance'] schema = database_schemas[item['database_id']] source_sequence, target_sequence = build_schema_linking_data(schema=schema, question=question, item=item, turn_id=0, linking_type=linking_type) outputs.extend(target_sequence) inputs.extend(source_sequence) assert len(inputs) == len(outputs) return inputs, outputs def read_dataflow_dataset(file_path, out_folder, session, linking_type): train_out_path = os.path.join(out_folder, session) train_src_writer = open(train_out_path + ".src", "w", encoding="utf8") train_tgt_writer = open(train_out_path + ".tgt", "w", encoding="utf8") with open(file_path, "r", encoding='utf-8') as data_file: lines = json.load(data_file) data_input, data_output = extract_input_and_output(lines, linking_type) train_src_writer.write("\n".join(data_input)) train_tgt_writer.write("\n".join(data_output)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--sl_dataset_path", default='./data/spider_schema_linking_tag') parser.add_argument("--output_path", default='./dataset_post/spider_sl') parser.add_argument("--linking_type", default='default') args = parser.parse_args() # for session in ["train", "dev"]: for session in ["dev"]: file_path = os.path.join(args.sl_dataset_path, "{}.json".format(session)) out_folder = args.output_path if not os.path.exists(out_folder): os.makedirs(out_folder) read_dataflow_dataset(file_path, out_folder, session, args.linking_type) running_process(args.output_path)
ContextualSP/unified_parser_text_to_sql/step2_serialization.py/0
{ "file_path": "ContextualSP/unified_parser_text_to_sql/step2_serialization.py", "repo_id": "ContextualSP", "token_count": 3372 }
258
SUPERNET: MLP_RATIO: 4.0 NUM_HEADS: 10 EMBED_DIM: 640 DEPTH: 16 SEARCH_SPACE: MLP_RATIO: - 3.0 - 3.5 - 4.0 NUM_HEADS: - 8 - 9 - 10 DEPTH: - 14 - 15 - 16 EMBED_DIM: - 528 - 576 - 624 RETRAIN: MLP_RATIO: - 3.5 - 3.5 - 4.0 - 3.5 - 4.0 - 3.5 - 3.5 - 3.0 - 4.0 - 4.0 - 3.0 - 4.0 - 3.0 - 3.5 NUM_HEADS: - 9 - 9 - 9 - 9 - 9 - 10 - 9 - 9 - 10 - 9 - 10 - 9 - 9 - 10 DEPTH: 14 EMBED_DIM: 576
Cream/AutoFormer/experiments/subnet/AutoFormer-B.yaml/0
{ "file_path": "Cream/AutoFormer/experiments/subnet/AutoFormer-B.yaml", "repo_id": "Cream", "token_count": 398 }
259
import torch from torch import nn from torch.nn import Parameter import torch.nn.functional as F from .Linear_super import LinearSuper from .qkv_super import qkv_super from ..utils import trunc_normal_ def softmax(x, dim, onnx_trace=False): if onnx_trace: return F.softmax(x.float(), dim=dim) else: return F.softmax(x, dim=dim, dtype=torch.float32) class RelativePosition2D_super(nn.Module): def __init__(self, num_units, max_relative_position): super().__init__() self.num_units = num_units self.max_relative_position = max_relative_position # The first element in embeddings_table_v is the vertical embedding for the class self.embeddings_table_v = nn.Parameter(torch.randn(max_relative_position * 2 + 2, num_units)) self.embeddings_table_h = nn.Parameter(torch.randn(max_relative_position * 2 + 2, num_units)) trunc_normal_(self.embeddings_table_v, std=.02) trunc_normal_(self.embeddings_table_h, std=.02) self.sample_head_dim = None self.sample_embeddings_table_h = None self.sample_embeddings_table_v = None def set_sample_config(self, sample_head_dim): self.sample_head_dim = sample_head_dim self.sample_embeddings_table_h = self.embeddings_table_h[:,:sample_head_dim] self.sample_embeddings_table_v = self.embeddings_table_v[:,:sample_head_dim] def calc_sampled_param_num(self): return self.sample_embeddings_table_h.numel() + self.sample_embeddings_table_v.numel() def forward(self, length_q, length_k): # remove the first cls token distance computation length_q = length_q - 1 length_k = length_k - 1 device = self.embeddings_table_v.device range_vec_q = torch.arange(length_q, device=device) range_vec_k = torch.arange(length_k, device=device) # compute the row and column distance distance_mat_v = (range_vec_k[None, :] // int(length_q ** 0.5 ) - range_vec_q[:, None] // int(length_q ** 0.5 )) distance_mat_h = (range_vec_k[None, :] % int(length_q ** 0.5 ) - range_vec_q[:, None] % int(length_q ** 0.5 )) # clip the distance to the range of [-max_relative_position, max_relative_position] distance_mat_clipped_v = torch.clamp(distance_mat_v, -self.max_relative_position, self.max_relative_position) distance_mat_clipped_h = torch.clamp(distance_mat_h, -self.max_relative_position, self.max_relative_position) # translate the distance from [1, 2 * max_relative_position + 1], 0 is for the cls token final_mat_v = distance_mat_clipped_v + self.max_relative_position + 1 final_mat_h = distance_mat_clipped_h + self.max_relative_position + 1 # pad the 0 which represent the cls token final_mat_v = torch.nn.functional.pad(final_mat_v, (1,0,1,0), "constant", 0) final_mat_h = torch.nn.functional.pad(final_mat_h, (1,0,1,0), "constant", 0) final_mat_v = final_mat_v.long() final_mat_h = final_mat_h.long() # get the embeddings with the corresponding distance embeddings = self.sample_embeddings_table_v[final_mat_v] + self.sample_embeddings_table_h[final_mat_h] return embeddings class AttentionSuper(nn.Module): def __init__(self, super_embed_dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., normalization = False, relative_position = False, num_patches = None, max_relative_position=14, scale=False, change_qkv = False): super().__init__() self.num_heads = num_heads head_dim = super_embed_dim // num_heads self.scale = qk_scale or head_dim ** -0.5 self.super_embed_dim = super_embed_dim self.fc_scale = scale self.change_qkv = change_qkv if change_qkv: self.qkv = qkv_super(super_embed_dim, 3 * super_embed_dim, bias=qkv_bias) else: self.qkv = LinearSuper(super_embed_dim, 3 * super_embed_dim, bias=qkv_bias) self.relative_position = relative_position if self.relative_position: self.rel_pos_embed_k = RelativePosition2D_super(super_embed_dim //num_heads, max_relative_position) self.rel_pos_embed_v = RelativePosition2D_super(super_embed_dim //num_heads, max_relative_position) self.max_relative_position = max_relative_position self.sample_qk_embed_dim = None self.sample_v_embed_dim = None self.sample_num_heads = None self.sample_scale = None self.sample_in_embed_dim = None self.proj = LinearSuper(super_embed_dim, super_embed_dim) self.attn_drop = nn.Dropout(attn_drop) self.proj_drop = nn.Dropout(proj_drop) def set_sample_config(self, sample_q_embed_dim=None, sample_num_heads=None, sample_in_embed_dim=None): self.sample_in_embed_dim = sample_in_embed_dim self.sample_num_heads = sample_num_heads if not self.change_qkv: self.sample_qk_embed_dim = self.super_embed_dim self.sample_scale = (sample_in_embed_dim // self.sample_num_heads) ** -0.5 else: self.sample_qk_embed_dim = sample_q_embed_dim self.sample_scale = (self.sample_qk_embed_dim // self.sample_num_heads) ** -0.5 self.qkv.set_sample_config(sample_in_dim=sample_in_embed_dim, sample_out_dim=3*self.sample_qk_embed_dim) self.proj.set_sample_config(sample_in_dim=self.sample_qk_embed_dim, sample_out_dim=sample_in_embed_dim) if self.relative_position: self.rel_pos_embed_k.set_sample_config(self.sample_qk_embed_dim // sample_num_heads) self.rel_pos_embed_v.set_sample_config(self.sample_qk_embed_dim // sample_num_heads) def calc_sampled_param_num(self): return 0 def get_complexity(self, sequence_length): total_flops = 0 total_flops += self.qkv.get_complexity(sequence_length) # attn total_flops += sequence_length * sequence_length * self.sample_qk_embed_dim # x total_flops += sequence_length * sequence_length * self.sample_qk_embed_dim total_flops += self.proj.get_complexity(sequence_length) if self.relative_position: total_flops += self.max_relative_position * sequence_length * sequence_length + sequence_length * sequence_length / 2.0 total_flops += self.max_relative_position * sequence_length * sequence_length + sequence_length * self.sample_qk_embed_dim / 2.0 return total_flops def forward(self, x): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.sample_num_heads, -1).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) attn = (q @ k.transpose(-2, -1)) * self.sample_scale if self.relative_position: r_p_k = self.rel_pos_embed_k(N, N) attn = attn + (q.permute(2, 0, 1, 3).reshape(N, self.sample_num_heads * B, -1) @ r_p_k.transpose(2, 1)) \ .transpose(1, 0).reshape(B, self.sample_num_heads, N, N) * self.sample_scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (attn @ v).transpose(1,2).reshape(B, N, -1) if self.relative_position: r_p_v = self.rel_pos_embed_v(N, N) attn_1 = attn.permute(2, 0, 1, 3).reshape(N, B * self.sample_num_heads, -1) # The size of attention is (B, num_heads, N, N), reshape it to (N, B*num_heads, N) and do batch matmul with # the relative position embedding of V (N, N, head_dim) get shape like (N, B*num_heads, head_dim). We reshape it to the # same size as x (B, num_heads, N, hidden_dim) x = x + (attn_1 @ r_p_v).transpose(1, 0).reshape(B, self.sample_num_heads, N, -1).transpose(2,1).reshape(B, N, -1) if self.fc_scale: x = x * (self.super_embed_dim / self.sample_qk_embed_dim) x = self.proj(x) x = self.proj_drop(x) return x
Cream/AutoFormer/model/module/multihead_super.py/0
{ "file_path": "Cream/AutoFormer/model/module/multihead_super.py", "repo_id": "Cream", "token_count": 3598 }
260
# CyDAS Detection Code Base ### Environments - Python 3.7 - Pytorch>=1.8.2 - Torchvision == 0.9.2 You can directly run the code ```sh env.sh``` and ```sh compile.sh``` to setup the running environment. We use 8 GPUs (24GB RTX 3090) to train our detector, you can adjust the batch size in configs by yourselves. ### Data Preparatoin Your directory tree should be look like this: ````bash $HitDet.pytorch/data ├── coco │   ├── annotations │   ├── train2017 │   └── val2017 │ ├── VOCdevkit │   ├── VOC2007 │   │   ├── Annotations │   │ ├── ImageSets │   │ ├── JPEGImages │   │ ├── SegmentationClass │   │   └── SegmentationObject │   └── VOC2012 │      ├── Annotations │   ├── ImageSets │   ├── JPEGImages │   ├── SegmentationClass │      └── SegmentationObject ```` ### Getting Start Our pretrained backbone params can be found in [GoogleDrive](https://drive.google.com/drive/folders/1CkFp24bEDq0wUp504BQ68jn5Vs069qox) Installation * Clone this repo: ```bash cd CDARTS_detection ``` * Install dependencies: ```bash bash env.sh bash compile.sh ``` Train: ``` sh train.sh ``` ## Acknowledgement Our code is based on the open source project [MMDetection](https://github.com/open-mmlab/mmdetection).
Cream/CDARTS/CDARTS_detection/README.md/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/README.md", "repo_id": "Cream", "token_count": 458 }
261
import yaml try: from yaml import CLoader as Loader, CDumper as Dumper except ImportError: from yaml import Loader, Dumper from .base import BaseFileHandler # isort:skip class YamlHandler(BaseFileHandler): def load_from_fileobj(self, file, **kwargs): kwargs.setdefault('Loader', Loader) return yaml.load(file, **kwargs) def dump_to_fileobj(self, obj, file, **kwargs): kwargs.setdefault('Dumper', Dumper) yaml.dump(obj, file, **kwargs) def dump_to_str(self, obj, **kwargs): kwargs.setdefault('Dumper', Dumper) return yaml.dump(obj, **kwargs)
Cream/CDARTS/CDARTS_detection/mmcv/fileio/handlers/yaml_handler.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmcv/fileio/handlers/yaml_handler.py", "repo_id": "Cream", "token_count": 256 }
262
import torch import torch.distributed as dist import torch.nn as nn from torch._utils import (_flatten_dense_tensors, _take_tensors, _unflatten_dense_tensors) from .scatter_gather import scatter_kwargs class MMDistributedDataParallel(nn.Module): def __init__(self, module, dim=0, broadcast_buffers=True, bucket_cap_mb=25): super(MMDistributedDataParallel, self).__init__() self.module = module self.dim = dim self.broadcast_buffers = broadcast_buffers self.broadcast_bucket_size = bucket_cap_mb * 1024 * 1024 self._sync_params() def _dist_broadcast_coalesced(self, tensors, buffer_size): for tensors in _take_tensors(tensors, buffer_size): flat_tensors = _flatten_dense_tensors(tensors) dist.broadcast(flat_tensors, 0) for tensor, synced in zip( tensors, _unflatten_dense_tensors(flat_tensors, tensors)): tensor.copy_(synced) def _sync_params(self): module_states = list(self.module.state_dict().values()) if len(module_states) > 0: self._dist_broadcast_coalesced(module_states, self.broadcast_bucket_size) if self.broadcast_buffers: if torch.__version__ < '1.0': buffers = [b.data for b in self.module._all_buffers()] else: buffers = [b.data for b in self.module.buffers()] if len(buffers) > 0: self._dist_broadcast_coalesced(buffers, self.broadcast_bucket_size) def scatter(self, inputs, kwargs, device_ids): return scatter_kwargs(inputs, kwargs, device_ids, dim=self.dim) def forward(self, *inputs, **kwargs): inputs, kwargs = self.scatter(inputs, kwargs, [torch.cuda.current_device()]) return self.module(*inputs[0], **kwargs[0])
Cream/CDARTS/CDARTS_detection/mmcv/parallel/distributed.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmcv/parallel/distributed.py", "repo_id": "Cream", "token_count": 1000 }
263
import torch from .hook import Hook class EmptyCacheHook(Hook): def __init__(self, before_epoch=False, after_epoch=True, after_iter=False): self._before_epoch = before_epoch self._after_epoch = after_epoch self._after_iter = after_iter def after_iter(self, runner): if self._after_iter: torch.cuda.empty_cache() def before_epoch(self, runner): if self._before_epoch: torch.cuda.empty_cache() def after_epoch(self, runner): if self._after_epoch: torch.cuda.empty_cache()
Cream/CDARTS/CDARTS_detection/mmcv/runner/hooks/memory.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmcv/runner/hooks/memory.py", "repo_id": "Cream", "token_count": 258 }
264
import os.path as osp from collections import OrderedDict import cv2 from mmcv.opencv_info import USE_OPENCV2 from mmcv.utils import (check_file_exist, mkdir_or_exist, scandir, track_progress) if not USE_OPENCV2: from cv2 import (CAP_PROP_FRAME_WIDTH, CAP_PROP_FRAME_HEIGHT, CAP_PROP_FPS, CAP_PROP_FRAME_COUNT, CAP_PROP_FOURCC, CAP_PROP_POS_FRAMES, VideoWriter_fourcc) else: from cv2.cv import CV_CAP_PROP_FRAME_WIDTH as CAP_PROP_FRAME_WIDTH from cv2.cv import CV_CAP_PROP_FRAME_HEIGHT as CAP_PROP_FRAME_HEIGHT from cv2.cv import CV_CAP_PROP_FPS as CAP_PROP_FPS from cv2.cv import CV_CAP_PROP_FRAME_COUNT as CAP_PROP_FRAME_COUNT from cv2.cv import CV_CAP_PROP_FOURCC as CAP_PROP_FOURCC from cv2.cv import CV_CAP_PROP_POS_FRAMES as CAP_PROP_POS_FRAMES from cv2.cv import CV_FOURCC as VideoWriter_fourcc class Cache(object): def __init__(self, capacity): self._cache = OrderedDict() self._capacity = int(capacity) if capacity <= 0: raise ValueError('capacity must be a positive integer') @property def capacity(self): return self._capacity @property def size(self): return len(self._cache) def put(self, key, val): if key in self._cache: return if len(self._cache) >= self.capacity: self._cache.popitem(last=False) self._cache[key] = val def get(self, key, default=None): val = self._cache[key] if key in self._cache else default return val class VideoReader(object): """Video class with similar usage to a list object. This video warpper class provides convenient apis to access frames. There exists an issue of OpenCV's VideoCapture class that jumping to a certain frame may be inaccurate. It is fixed in this class by checking the position after jumping each time. Cache is used when decoding videos. So if the same frame is visited for the second time, there is no need to decode again if it is stored in the cache. :Example: >>> import mmcv >>> v = mmcv.VideoReader('sample.mp4') >>> len(v) # get the total frame number with `len()` 120 >>> for img in v: # v is iterable >>> mmcv.imshow(img) >>> v[5] # get the 6th frame """ def __init__(self, filename, cache_capacity=10): check_file_exist(filename, 'Video file not found: ' + filename) self._vcap = cv2.VideoCapture(filename) assert cache_capacity > 0 self._cache = Cache(cache_capacity) self._position = 0 # get basic info self._width = int(self._vcap.get(CAP_PROP_FRAME_WIDTH)) self._height = int(self._vcap.get(CAP_PROP_FRAME_HEIGHT)) self._fps = self._vcap.get(CAP_PROP_FPS) self._frame_cnt = int(self._vcap.get(CAP_PROP_FRAME_COUNT)) self._fourcc = self._vcap.get(CAP_PROP_FOURCC) @property def vcap(self): """:obj:`cv2.VideoCapture`: The raw VideoCapture object.""" return self._vcap @property def opened(self): """bool: Indicate whether the video is opened.""" return self._vcap.isOpened() @property def width(self): """int: Width of video frames.""" return self._width @property def height(self): """int: Height of video frames.""" return self._height @property def resolution(self): """tuple: Video resolution (width, height).""" return (self._width, self._height) @property def fps(self): """float: FPS of the video.""" return self._fps @property def frame_cnt(self): """int: Total frames of the video.""" return self._frame_cnt @property def fourcc(self): """str: "Four character code" of the video.""" return self._fourcc @property def position(self): """int: Current cursor position, indicating frame decoded.""" return self._position def _get_real_position(self): return int(round(self._vcap.get(CAP_PROP_POS_FRAMES))) def _set_real_position(self, frame_id): self._vcap.set(CAP_PROP_POS_FRAMES, frame_id) pos = self._get_real_position() for _ in range(frame_id - pos): self._vcap.read() self._position = frame_id def read(self): """Read the next frame. If the next frame have been decoded before and in the cache, then return it directly, otherwise decode, cache and return it. Returns: ndarray or None: Return the frame if successful, otherwise None. """ # pos = self._position if self._cache: img = self._cache.get(self._position) if img is not None: ret = True else: if self._position != self._get_real_position(): self._set_real_position(self._position) ret, img = self._vcap.read() if ret: self._cache.put(self._position, img) else: ret, img = self._vcap.read() if ret: self._position += 1 return img def get_frame(self, frame_id): """Get frame by index. Args: frame_id (int): Index of the expected frame, 0-based. Returns: ndarray or None: Return the frame if successful, otherwise None. """ if frame_id < 0 or frame_id >= self._frame_cnt: raise IndexError( '"frame_id" must be between 0 and {}'.format(self._frame_cnt - 1)) if frame_id == self._position: return self.read() if self._cache: img = self._cache.get(frame_id) if img is not None: self._position = frame_id + 1 return img self._set_real_position(frame_id) ret, img = self._vcap.read() if ret: if self._cache: self._cache.put(self._position, img) self._position += 1 return img def current_frame(self): """Get the current frame (frame that is just visited). Returns: ndarray or None: If the video is fresh, return None, otherwise return the frame. """ if self._position == 0: return None return self._cache.get(self._position - 1) def cvt2frames(self, frame_dir, file_start=0, filename_tmpl='{:06d}.jpg', start=0, max_num=0, show_progress=True): """Convert a video to frame images Args: frame_dir (str): Output directory to store all the frame images. file_start (int): Filenames will start from the specified number. filename_tmpl (str): Filename template with the index as the placeholder. start (int): The starting frame index. max_num (int): Maximum number of frames to be written. show_progress (bool): Whether to show a progress bar. """ mkdir_or_exist(frame_dir) if max_num == 0: task_num = self.frame_cnt - start else: task_num = min(self.frame_cnt - start, max_num) if task_num <= 0: raise ValueError('start must be less than total frame number') if start > 0: self._set_real_position(start) def write_frame(file_idx): img = self.read() filename = osp.join(frame_dir, filename_tmpl.format(file_idx)) cv2.imwrite(filename, img) if show_progress: track_progress(write_frame, range(file_start, file_start + task_num)) else: for i in range(task_num): img = self.read() if img is None: break filename = osp.join(frame_dir, filename_tmpl.format(i + file_start)) cv2.imwrite(filename, img) def __len__(self): return self.frame_cnt def __getitem__(self, index): if isinstance(index, slice): return [ self.get_frame(i) for i in range(*index.indices(self.frame_cnt)) ] # support negative indexing if index < 0: index += self.frame_cnt if index < 0: raise IndexError('index out of range') return self.get_frame(index) def __iter__(self): self._set_real_position(0) return self def __next__(self): img = self.read() if img is not None: return img else: raise StopIteration next = __next__ def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self._vcap.release() def frames2video(frame_dir, video_file, fps=30, fourcc='XVID', filename_tmpl='{:06d}.jpg', start=0, end=0, show_progress=True): """Read the frame images from a directory and join them as a video Args: frame_dir (str): The directory containing video frames. video_file (str): Output filename. fps (float): FPS of the output video. fourcc (str): Fourcc of the output video, this should be compatible with the output file type. filename_tmpl (str): Filename template with the index as the variable. start (int): Starting frame index. end (int): Ending frame index. show_progress (bool): Whether to show a progress bar. """ if end == 0: ext = filename_tmpl.split('.')[-1] end = len([name for name in scandir(frame_dir, ext)]) first_file = osp.join(frame_dir, filename_tmpl.format(start)) check_file_exist(first_file, 'The start frame not found: ' + first_file) img = cv2.imread(first_file) height, width = img.shape[:2] resolution = (width, height) vwriter = cv2.VideoWriter(video_file, VideoWriter_fourcc(*fourcc), fps, resolution) def write_frame(file_idx): filename = osp.join(frame_dir, filename_tmpl.format(file_idx)) img = cv2.imread(filename) vwriter.write(img) if show_progress: track_progress(write_frame, range(start, end)) else: for i in range(start, end): filename = osp.join(frame_dir, filename_tmpl.format(i)) img = cv2.imread(filename) vwriter.write(img) vwriter.release()
Cream/CDARTS/CDARTS_detection/mmcv/video/io.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmcv/video/io.py", "repo_id": "Cream", "token_count": 5118 }
265
import torch class AssignResult(object): def __init__(self, num_gts, gt_inds, max_overlaps, labels=None): self.num_gts = num_gts self.gt_inds = gt_inds self.max_overlaps = max_overlaps self.labels = labels def add_gt_(self, gt_labels): self_inds = torch.arange( 1, len(gt_labels) + 1, dtype=torch.long, device=gt_labels.device) self.gt_inds = torch.cat([self_inds, self.gt_inds]) self.max_overlaps = torch.cat( [self.max_overlaps.new_ones(self.num_gts), self.max_overlaps]) if self.labels is not None: self.labels = torch.cat([gt_labels, self.labels])
Cream/CDARTS/CDARTS_detection/mmdet/core/bbox/assigners/assign_result.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmdet/core/bbox/assigners/assign_result.py", "repo_id": "Cream", "token_count": 333 }
266
import numpy as np def bbox_overlaps(bboxes1, bboxes2, mode='iou'): """Calculate the ious between each bbox of bboxes1 and bboxes2. Args: bboxes1(ndarray): shape (n, 4) bboxes2(ndarray): shape (k, 4) mode(str): iou (intersection over union) or iof (intersection over foreground) Returns: ious(ndarray): shape (n, k) """ assert mode in ['iou', 'iof'] bboxes1 = bboxes1.astype(np.float32) bboxes2 = bboxes2.astype(np.float32) rows = bboxes1.shape[0] cols = bboxes2.shape[0] ious = np.zeros((rows, cols), dtype=np.float32) if rows * cols == 0: return ious exchange = False if bboxes1.shape[0] > bboxes2.shape[0]: bboxes1, bboxes2 = bboxes2, bboxes1 ious = np.zeros((cols, rows), dtype=np.float32) exchange = True area1 = (bboxes1[:, 2] - bboxes1[:, 0] + 1) * ( bboxes1[:, 3] - bboxes1[:, 1] + 1) area2 = (bboxes2[:, 2] - bboxes2[:, 0] + 1) * ( bboxes2[:, 3] - bboxes2[:, 1] + 1) for i in range(bboxes1.shape[0]): x_start = np.maximum(bboxes1[i, 0], bboxes2[:, 0]) y_start = np.maximum(bboxes1[i, 1], bboxes2[:, 1]) x_end = np.minimum(bboxes1[i, 2], bboxes2[:, 2]) y_end = np.minimum(bboxes1[i, 3], bboxes2[:, 3]) overlap = np.maximum(x_end - x_start + 1, 0) * np.maximum( y_end - y_start + 1, 0) if mode == 'iou': union = area1[i] + area2 - overlap else: union = area1[i] if not exchange else area2 ious[i, :] = overlap / union if exchange: ious = ious.T return ious
Cream/CDARTS/CDARTS_detection/mmdet/core/evaluation/bbox_overlaps.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmdet/core/evaluation/bbox_overlaps.py", "repo_id": "Cream", "token_count": 826 }
267
from .dist_utils import allreduce_grads, DistOptimizerHook, DistOptimizerArchHook from .misc import tensor2imgs, unmap, multi_apply __all__ = [ 'allreduce_grads', 'DistOptimizerHook', 'tensor2imgs', 'unmap', 'multi_apply', 'DistOptimizerArchHook' ]
Cream/CDARTS/CDARTS_detection/mmdet/core/utils/__init__.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmdet/core/utils/__init__.py", "repo_id": "Cream", "token_count": 103 }
268
import mmcv from ..registry import PIPELINES from .compose import Compose @PIPELINES.register_module class MultiScaleFlipAug(object): def __init__(self, transforms, img_scale, flip=False): self.transforms = Compose(transforms) self.img_scale = img_scale if isinstance(img_scale, list) else [img_scale] assert mmcv.is_list_of(self.img_scale, tuple) self.flip = flip def __call__(self, results): aug_data = [] flip_aug = [False, True] if self.flip else [False] for scale in self.img_scale: for flip in flip_aug: _results = results.copy() _results['scale'] = scale _results['flip'] = flip data = self.transforms(_results) aug_data.append(data) # list of dict to dict of list aug_data_dict = {key: [] for key in aug_data[0]} for data in aug_data: for key, val in data.items(): aug_data_dict[key].append(val) return aug_data_dict def __repr__(self): repr_str = self.__class__.__name__ repr_str += '(transforms={}, img_scale={}, flip={})'.format( self.transforms, self.img_scale, self.flip) return repr_str
Cream/CDARTS/CDARTS_detection/mmdet/datasets/pipelines/test_aug.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmdet/datasets/pipelines/test_aug.py", "repo_id": "Cream", "token_count": 588 }
269
import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import normal_init from mmdet.core import delta2bbox from mmdet.ops import nms from .anchor_head import AnchorHead from ..registry import HEADS @HEADS.register_module class RPNHead(AnchorHead): def __init__(self, in_channels, **kwargs): super(RPNHead, self).__init__(2, in_channels, **kwargs) def _init_layers(self): self.rpn_conv = nn.Conv2d( self.in_channels, self.feat_channels, 3, padding=1) self.rpn_cls = nn.Conv2d(self.feat_channels, self.num_anchors * self.cls_out_channels, 1) self.rpn_reg = nn.Conv2d(self.feat_channels, self.num_anchors * 4, 1) def init_weights(self): normal_init(self.rpn_conv, std=0.01) normal_init(self.rpn_cls, std=0.01) normal_init(self.rpn_reg, std=0.01) def forward_single(self, x): x = self.rpn_conv(x) x = F.relu(x, inplace=True) rpn_cls_score = self.rpn_cls(x) rpn_bbox_pred = self.rpn_reg(x) return rpn_cls_score, rpn_bbox_pred def loss(self, cls_scores, bbox_preds, gt_bboxes, img_metas, cfg, gt_bboxes_ignore=None): losses = super(RPNHead, self).loss( cls_scores, bbox_preds, gt_bboxes, None, img_metas, cfg, gt_bboxes_ignore=gt_bboxes_ignore) return dict( loss_rpn_cls=losses['loss_cls'], loss_rpn_bbox=losses['loss_bbox']) def get_bboxes_single(self, cls_scores, bbox_preds, mlvl_anchors, img_shape, scale_factor, cfg, rescale=False): mlvl_proposals = [] for idx in range(len(cls_scores)): rpn_cls_score = cls_scores[idx] rpn_bbox_pred = bbox_preds[idx] assert rpn_cls_score.size()[-2:] == rpn_bbox_pred.size()[-2:] anchors = mlvl_anchors[idx] rpn_cls_score = rpn_cls_score.permute(1, 2, 0) if self.use_sigmoid_cls: rpn_cls_score = rpn_cls_score.reshape(-1) scores = rpn_cls_score.sigmoid() else: rpn_cls_score = rpn_cls_score.reshape(-1, 2) scores = rpn_cls_score.softmax(dim=1)[:, 1] rpn_bbox_pred = rpn_bbox_pred.permute(1, 2, 0).reshape(-1, 4) if cfg.nms_pre > 0 and scores.shape[0] > cfg.nms_pre: _, topk_inds = scores.topk(cfg.nms_pre) rpn_bbox_pred = rpn_bbox_pred[topk_inds, :] anchors = anchors[topk_inds, :] scores = scores[topk_inds] proposals = delta2bbox(anchors, rpn_bbox_pred, self.target_means, self.target_stds, img_shape) if cfg.min_bbox_size > 0: w = proposals[:, 2] - proposals[:, 0] + 1 h = proposals[:, 3] - proposals[:, 1] + 1 valid_inds = torch.nonzero((w >= cfg.min_bbox_size) & (h >= cfg.min_bbox_size)).squeeze() proposals = proposals[valid_inds, :] scores = scores[valid_inds] proposals = torch.cat([proposals, scores.unsqueeze(-1)], dim=-1) proposals, _ = nms(proposals, cfg.nms_thr) proposals = proposals[:cfg.nms_post, :] mlvl_proposals.append(proposals) proposals = torch.cat(mlvl_proposals, 0) if cfg.nms_across_levels: proposals, _ = nms(proposals, cfg.nms_thr) proposals = proposals[:cfg.max_num, :] else: scores = proposals[:, 4] num = min(cfg.max_num, proposals.shape[0]) _, topk_inds = scores.topk(num) proposals = proposals[topk_inds, :] return proposals
Cream/CDARTS/CDARTS_detection/mmdet/models/anchor_heads/rpn_head.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmdet/models/anchor_heads/rpn_head.py", "repo_id": "Cream", "token_count": 2356 }
270
import logging import torch import torch.nn as nn import torch.utils.checkpoint as cp from torch.nn.modules.batchnorm import _BatchNorm from mmcv.cnn import constant_init, kaiming_init # from mmcv.runner import load_checkpoint from mmdet.ops import DeformConv, ModulatedDeformConv, ContextBlock from mmdet.models.plugins import GeneralizedAttention from ..registry import BACKBONES from ..utils import build_conv_layer, build_norm_layer class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, kernel_size=3, dilation=1, downsample=None, style='pytorch', with_cp=False, conv2_split=False, conv_cfg=None, norm_cfg=dict(type='BN'), dcn=None, gcb=None, gen_attention=None): super(BasicBlock, self).__init__() assert dcn is None, "Not implemented yet." assert gen_attention is None, "Not implemented yet." assert gcb is None, "Not implemented yet." self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1) self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2) self.conv1 = build_conv_layer( conv_cfg, inplanes, planes, 3, stride=stride, padding=dilation, dilation=dilation, bias=False) self.add_module(self.norm1_name, norm1) self.conv2 = build_conv_layer( conv_cfg, planes, planes, 3, padding=1, bias=False) self.add_module(self.norm2_name, norm2) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.dilation = dilation assert not with_cp @property def norm1(self): return getattr(self, self.norm1_name) @property def norm2(self): return getattr(self, self.norm2_name) def forward(self, x): identity = x out = self.conv1(x) out = self.norm1(out) out = self.relu(out) out = self.conv2(out) out = self.norm2(out) if self.downsample is not None: identity = self.downsample(x) out += identity out = self.relu(out) return out class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, kernel_size=3, dilation=1, downsample=None, style='pytorch', with_cp=False, conv2_split=False, conv_cfg=None, norm_cfg=dict(type='BN'), dcn=None, gcb=None, gen_attention=None): """Bottleneck block for ResNet. If style is "pytorch", the stride-two layer is the 3x3 conv layer, if it is "caffe", the stride-two layer is the first 1x1 conv layer. """ super(Bottleneck, self).__init__() assert style in ['pytorch', 'caffe'] assert dcn is None or isinstance(dcn, dict) assert gcb is None or isinstance(gcb, dict) assert gen_attention is None or isinstance(gen_attention, dict) self.inplanes = inplanes self.planes = planes self.stride = stride self.dilation = dilation self.style = style self.with_cp = with_cp self.conv2_split = conv2_split self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.dcn = dcn self.with_dcn = dcn is not None self.gcb = gcb self.with_gcb = gcb is not None self.gen_attention = gen_attention self.with_gen_attention = gen_attention is not None if self.style == 'pytorch': self.conv1_stride = 1 self.conv2_stride = stride else: self.conv1_stride = stride self.conv2_stride = 1 self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1) self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2) self.norm3_name, norm3 = build_norm_layer( norm_cfg, planes * self.expansion, postfix=3) self.conv1 = build_conv_layer( conv_cfg, inplanes, planes, kernel_size=1, stride=self.conv1_stride, bias=False) self.add_module(self.norm1_name, norm1) fallback_on_stride = False self.with_modulated_dcn = False if self.with_dcn: fallback_on_stride = dcn.get('fallback_on_stride', False) self.with_modulated_dcn = dcn.get('modulated', False) if not self.with_dcn or fallback_on_stride: if not self.conv2_split: self.conv2 = build_conv_layer( conv_cfg, planes, planes, kernel_size=kernel_size, stride=self.conv2_stride, padding=int((kernel_size-1)*dilation/2), dilation=dilation, bias=False) else: self.conv2_d1 = build_conv_layer( conv_cfg, planes, planes-2*int(planes/3), kernel_size=3, stride=self.conv2_stride, padding=dilation, dilation=dilation, bias=False) self.conv2_d2 = build_conv_layer( conv_cfg, planes, int(planes/3), kernel_size=3, stride=self.conv2_stride, padding=dilation+1, dilation=dilation+1, bias=False) self.conv2_d3 = build_conv_layer( conv_cfg, planes, int(planes/3), kernel_size=3, stride=self.conv2_stride, padding=dilation+2, dilation=dilation+2, bias=False) else: assert conv_cfg is None, 'conv_cfg must be None for DCN' deformable_groups = dcn.get('deformable_groups', 1) if not self.with_modulated_dcn: conv_op = DeformConv offset_channels = 18 else: conv_op = ModulatedDeformConv offset_channels = 27 """ original code self.conv2_offset = nn.Conv2d( planes, deformable_groups * offset_channels, kernel_size=3, stride=self.conv2_stride, padding=dilation, dilation=dilation) """ # for huang lang test self.conv2_offset = StructualDeformBlock( planes, deformable_groups * offset_channels, kernel_size=3, stride=self.conv2_stride, padding=dilation, dilation=dilation) self.conv2 = conv_op( planes, planes, kernel_size=3, stride=self.conv2_stride, padding=dilation, dilation=dilation, deformable_groups=deformable_groups, bias=False) self.add_module(self.norm2_name, norm2) self.conv3 = build_conv_layer( conv_cfg, planes, planes * self.expansion, kernel_size=1, bias=False) self.add_module(self.norm3_name, norm3) self.relu = nn.ReLU(inplace=True) self.downsample = downsample if self.with_gcb: gcb_inplanes = planes * self.expansion self.context_block = ContextBlock(inplanes=gcb_inplanes, **gcb) # gen_attention if self.with_gen_attention: self.gen_attention_block = GeneralizedAttention( planes, **gen_attention) @property def norm1(self): return getattr(self, self.norm1_name) @property def norm2(self): return getattr(self, self.norm2_name) @property def norm3(self): return getattr(self, self.norm3_name) def forward(self, x): def _inner_forward(x): identity = x out = self.conv1(x) out = self.norm1(out) out = self.relu(out) if not self.with_dcn: if not self.conv2_split: out = self.conv2(out) else: out_d1 = self.conv2_d1(out) out_d2 = self.conv2_d2(out) out_d3 = self.conv2_d3(out) out = torch.cat((out_d1, out_d2, out_d3), 1) elif self.with_modulated_dcn: offset_mask = self.conv2_offset(out) offset = offset_mask[:, :18, :, :] mask = offset_mask[:, -9:, :, :].sigmoid() out = self.conv2(out, offset, mask) else: offset = self.conv2_offset(out) out = self.conv2(out, offset) out = self.norm2(out) out = self.relu(out) if self.with_gen_attention: out = self.gen_attention_block(out) out = self.conv3(out) out = self.norm3(out) if self.with_gcb: out = self.context_block(out) if self.downsample is not None: identity = self.downsample(x) out += identity return out if self.with_cp and x.requires_grad: out = cp.checkpoint(_inner_forward, x) else: out = _inner_forward(x) out = self.relu(out) return out # for huang lang test from torch.nn import functional as F class StructualDeformBlock(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, dilation=1): super(StructualDeformBlock, self).__init__() assert out_channels == 2 * kernel_size**2 self.out_channels = out_channels + 6 self.in_channels = in_channels self.kernel_size = kernel_size self.stride = stride self.padding = padding self.dilation = dilation # conv weights self.weight = nn.Parameter(torch.Tensor(self.out_channels, in_channels, kernel_size, kernel_size)) self.bias = nn.Parameter(torch.Tensor(self.out_channels)) # homogeneous coordinate map coord = (torch.arange(kernel_size, dtype=torch.float) - kernel_size // 2) * dilation coord = list(torch.meshgrid([coord, coord])) coord.append(torch.ones(kernel_size, kernel_size)) self.coord_map = torch.autograd.Variable(torch.stack(coord, dim=0).view(3, -1), requires_grad=False) # (3, K**2) def extra_repr(self): s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}' ', stride={stride}, padding={padding}, dilation={dilation}') return s.format(**self.__dict__) def forward(self, x_): offset_affine = F.conv2d(x_, self.weight, self.bias, self.stride, self.padding, self.dilation) n, c, h, w = offset_affine.shape # apply affine transformation on conv grids deform_params = offset_affine[:, -6:].view(n, 2, 3, h, w) structural_offset = torch.einsum('nijhw,jk->nikhw', (deform_params, self.coord_map.to(deform_params.device))) offset = structural_offset.reshape(n, -1, h, w) + offset_affine[:, :-6] return offset class MBBlock(nn.Module): def __init__(self, in_channels, out_channels, expansion, stride, kernel_size, dilation=1, groups=1): super(MBBlock, self).__init__() self.in_channels = in_channels self.out_channels =out_channels self.stride = stride self.groups = groups mid_channels = in_channels * expansion padding = (kernel_size - 1) * dilation // 2 self.conv1 = nn.Sequential( nn.Conv2d(in_channels, mid_channels, 1, stride=1, padding=0, dilation=1, bias=False, groups=groups), nn.BatchNorm2d(mid_channels), nn.ReLU(inplace=True) ) self.conv2 = nn.Sequential( nn.Conv2d(mid_channels, mid_channels, kernel_size, stride=stride, padding=padding, dilation=dilation, bias=False, groups=mid_channels), nn.BatchNorm2d(mid_channels), nn.ReLU(inplace=True) ) self.conv3 = nn.Sequential( nn.Conv2d(mid_channels, out_channels, 1, stride=1, padding=0, dilation=1, bias=False, groups=groups), nn.BatchNorm2d(out_channels) ) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.normal_(m.weight, 0, 1.0 / m.weight.shape[1]) if m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) if m.bias is not None: nn.init.constant_(m.bias, 0.0001) nn.init.constant_(m.running_mean, 0) def forward(self, x): out = self.conv1(x) out = self.conv2(out) out = self.conv3(out) if self.in_channels == self.out_channels and self.stride == 1: out = out + x return out def make_res_layer(block, inplanes, planes, blocks, stride=1, kernel_size=3, dilation=1, style='pytorch', with_cp=False, conv2_split=False, toy_replace=None, conv_cfg=None, norm_cfg=dict(type='BN'), dcn=None, gcb=None, gen_attention=None, gen_attention_blocks=[]): downsample = None if stride != 1 or inplanes != planes * block.expansion: downsample = nn.Sequential( build_conv_layer( conv_cfg, inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), build_norm_layer(norm_cfg, planes * block.expansion)[1], ) layers = [] layers.append( block( inplanes=inplanes, planes=planes, stride=stride, kernel_size=kernel_size, dilation=dilation, downsample=downsample, style=style, with_cp=with_cp, conv2_split=conv2_split, conv_cfg=conv_cfg, norm_cfg=norm_cfg, dcn=dcn, gcb=gcb, gen_attention=gen_attention if (0 in gen_attention_blocks) else None)) inplanes = planes * block.expansion for i in range(1, blocks): if blocks > 30 and i % 2 == 1: layers.append( block( inplanes=inplanes, planes=planes, stride=1, kernel_size=3, dilation=2, style=style, with_cp=with_cp, conv2_split=conv2_split, conv_cfg=conv_cfg, norm_cfg=norm_cfg, dcn=dcn, gcb=gcb, gen_attention=gen_attention if (i in gen_attention_blocks) else None)) elif toy_replace is not None and i == toy_replace.get('layer', 30): if toy_replace.get('block', 'res') == 'ir': layers.append( MBBlock(inplanes, inplanes, 1, 1, toy_replace.get('conv_kernel'), dilation=toy_replace.get('dilation'), groups=1) ) else: layers.append( block( inplanes=inplanes, planes=planes, stride=1, kernel_size=toy_replace.get('conv_kernel'), dilation=toy_replace.get('dilation'), style=style, with_cp=with_cp, conv2_split=conv2_split, conv_cfg=conv_cfg, norm_cfg=norm_cfg, dcn=dcn, gcb=gcb, gen_attention=gen_attention if (i in gen_attention_blocks) else None)) else: layers.append( block( inplanes=inplanes, planes=planes, stride=1, kernel_size=kernel_size, dilation=dilation, style=style, with_cp=with_cp, conv2_split=conv2_split, conv_cfg=conv_cfg, norm_cfg=norm_cfg, dcn=dcn, gcb=gcb, gen_attention=gen_attention if (i in gen_attention_blocks) else None)) # for [1,2,3,1] ''' layers.append( block( inplanes=inplanes, planes=planes, stride=1, kernel_size=3, dilation=2, style=style, with_cp=with_cp, conv2_split=conv2_split, conv_cfg=conv_cfg, norm_cfg=norm_cfg, dcn=dcn, gcb=gcb, gen_attention=gen_attention if (i in gen_attention_blocks) else None)) ''' return nn.Sequential(*layers) @BACKBONES.register_module class ResNet(nn.Module): """ResNet backbone. Args: depth (int): Depth of resnet, from {18, 34, 50, 101, 152}. num_stages (int): Resnet stages, normally 4. strides (Sequence[int]): Strides of the first block of each stage. dilations (Sequence[int]): Dilation of each stage. out_indices (Sequence[int]): Output from which stages. style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two layer is the 3x3 conv layer, otherwise the stride-two layer is the first 1x1 conv layer. frozen_stages (int): Stages to be frozen (stop grad and set eval mode). -1 means not freezing any parameters. norm_cfg (dict): dictionary to construct and config norm layer. norm_eval (bool): Whether to set norm layers to eval mode, namely, freeze running stats (mean and var). Note: Effect on Batch Norm and its variants only. with_cp (bool): Use checkpoint or not. Using checkpoint will save some memory while slowing down the training speed. zero_init_residual (bool): whether to use zero init for last norm layer in resblocks to let them behave as identity. """ arch_settings = { 10: (BasicBlock, (1, 1, 1, 1)), 18: (BasicBlock, (2, 2, 2, 2)), 34: (BasicBlock, (3, 4, 6, 3)), 50: (Bottleneck, (3, 4, 6, 3)), 101: (Bottleneck, (3, 4, 23, 3)), 152: (Bottleneck, (3, 8, 36, 3)) } def __init__(self, depth, num_stages=4, strides=(1, 2, 2, 2), kernel_size=3, dilations=(1, 1, 1, 1), out_indices=(0, 1, 2, 3), style='pytorch', frozen_stages=-1, conv_cfg=None, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, dcn=None, stage_with_dcn=(False, False, False, False), gcb=None, stage_with_gcb=(False, False, False, False), gen_attention=None, stage_with_gen_attention=((), (), (), ()), with_cp=False, conv2_split=False, toy_replace=None, # for toy experiments replace zero_init_residual=True): super(ResNet, self).__init__() if depth not in self.arch_settings: raise KeyError('invalid depth {} for resnet'.format(depth)) self.depth = depth self.num_stages = num_stages assert num_stages >= 1 and num_stages <= 4 self.strides = strides self.kernel_size=kernel_size self.dilations = dilations assert len(strides) == len(dilations) == num_stages self.out_indices = out_indices assert max(out_indices) < num_stages self.style = style self.frozen_stages = frozen_stages self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.with_cp = with_cp self.conv2_split = conv2_split self.toy_replace = toy_replace self.norm_eval = norm_eval self.dcn = dcn self.stage_with_dcn = stage_with_dcn if dcn is not None: assert len(stage_with_dcn) == num_stages self.gen_attention = gen_attention self.gcb = gcb self.stage_with_gcb = stage_with_gcb if gcb is not None: assert len(stage_with_gcb) == num_stages self.zero_init_residual = zero_init_residual self.block, stage_blocks = self.arch_settings[depth] self.stage_blocks = stage_blocks[:num_stages] self.inplanes = 64 self._make_stem_layer() self.res_layers = [] _toy_replace = None for i, num_blocks in enumerate(self.stage_blocks): if self.toy_replace is not None: if i != self.toy_replace.get('stage'): _toy_replace = None else: _toy_replace = self.toy_replace stride = strides[i] dilation = dilations[i] dcn = self.dcn if self.stage_with_dcn[i] else None gcb = self.gcb if self.stage_with_gcb[i] else None planes = 64 * 2**i res_layer = make_res_layer( self.block, self.inplanes, planes, num_blocks, stride=stride, kernel_size=kernel_size, dilation=dilation, style=self.style, with_cp=with_cp, conv2_split=conv2_split, toy_replace=_toy_replace, conv_cfg=conv_cfg, norm_cfg=norm_cfg, dcn=dcn, gcb=gcb, gen_attention=gen_attention, gen_attention_blocks=stage_with_gen_attention[i]) self.inplanes = planes * self.block.expansion layer_name = 'layer{}'.format(i + 1) self.add_module(layer_name, res_layer) self.res_layers.append(layer_name) self._freeze_stages() self.feat_dim = self.block.expansion * 64 * 2**( len(self.stage_blocks) - 1) @property def norm1(self): return getattr(self, self.norm1_name) def _make_stem_layer(self): self.conv1 = build_conv_layer( self.conv_cfg, 3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.norm1_name, norm1 = build_norm_layer(self.norm_cfg, 64, postfix=1) self.add_module(self.norm1_name, norm1) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) def _freeze_stages(self): if self.frozen_stages >= 0: self.norm1.eval() for m in [self.conv1, self.norm1]: for param in m.parameters(): param.requires_grad = False for i in range(1, self.frozen_stages + 1): m = getattr(self, 'layer{}'.format(i)) m.eval() for param in m.parameters(): param.requires_grad = False def init_weights(self, pretrained=None): if isinstance(pretrained, str): logger = logging.getLogger() load_checkpoint(self, pretrained, strict=False, logger=logger) elif pretrained is None: for m in self.modules(): if isinstance(m, nn.Conv2d): kaiming_init(m) elif isinstance(m, (_BatchNorm, nn.GroupNorm)): constant_init(m, 1) if self.dcn is not None: for m in self.modules(): if isinstance(m, Bottleneck) and hasattr( m, 'conv2_offset'): constant_init(m.conv2_offset, 0) if self.zero_init_residual: for m in self.modules(): if isinstance(m, Bottleneck): constant_init(m.norm3, 0) elif isinstance(m, BasicBlock): constant_init(m.norm2, 0) else: raise TypeError('pretrained must be a str or None') def forward(self, x): x = self.conv1(x) x = self.norm1(x) x = self.relu(x) x = self.maxpool(x) outs = [] for i, layer_name in enumerate(self.res_layers): res_layer = getattr(self, layer_name) x = res_layer(x) if i in self.out_indices: outs.append(x) return tuple(outs) def train(self, mode=True): super(ResNet, self).train(mode) self._freeze_stages() if mode and self.norm_eval: for m in self.modules(): # trick: eval have effect on BatchNorm only if isinstance(m, _BatchNorm): m.eval() from collections import OrderedDict def load_checkpoint(model, filename, strict=False, logger=None): checkpoint = torch.load(filename) # get state_dict from checkpoint if isinstance(checkpoint, OrderedDict): state_dict = checkpoint elif isinstance(checkpoint, dict) and 'state_dict' in checkpoint: state_dict = checkpoint['state_dict'] else: raise RuntimeError( 'No state_dict found in checkpoint file {}'.format(filename)) # strip prefix of state_dict if list(state_dict.keys())[0].startswith('module.'): state_dict = {k[7:]: v for k, v in state_dict.items()} # load state_dict if hasattr(model, 'module'): load_state_dict(model.module, state_dict, strict, logger) else: omit_name = None if model.toy_replace is not None: # layer3.1.conv2.weight omit_name = 'layer' + str(model.toy_replace.get('stage')+1) + '.' + str(model.toy_replace.get('layer')) + '.conv2.weight' load_state_dict(model, state_dict, strict, logger, omit_name=omit_name) return checkpoint def load_state_dict(module, state_dict, strict=False, logger=None, omit_name=None): """Load state_dict to a module. Args: logger (:obj:`logging.Logger`, optional): Logger to log the error message. If not specified, print function will be used. """ unexpected_keys = [] own_state = module.state_dict() state_dict_modify = state_dict.copy() for name, param in state_dict.items(): if isinstance(param, torch.nn.Parameter): # backwards compatibility for serialized parameters param = param.data if 'conv2' in name and 'layer4.0.conv2_d2.weight' in own_state.keys(): d1 = name.replace('conv2', 'conv2_d1') d1_c = own_state[d1].size(0) own_state[d1].copy_(param[:d1_c,:,:,:]) state_dict_modify[d1] = param[:d1_c,:,:,:] d2 = name.replace('conv2', 'conv2_d2') d2_c = own_state[d2].size(0) own_state[d2].copy_(param[d1_c:d1_c+d2_c,:,:,:]) state_dict_modify[d2] = param[d1_c:d1_c+d2_c,:,:,:] d3 = name.replace('conv2', 'conv2_d3') own_state[d3].copy_(param[d1_c+d2_c:,:,:,:]) state_dict_modify[d3] = param[d1_c+d2_c:,:,:,:] else: if name not in own_state: unexpected_keys.append(name) continue try: if name == omit_name: print('{} is omitted.'.format(omit_name)) else: own_state[name].copy_(param) except Exception: raise RuntimeError( 'While copying the parameter named {}, ' 'whose dimensions in the model are {} and ' 'whose dimensions in the checkpoint are {}.'.format( name, own_state[name].size(), param.size())) missing_keys = set(own_state.keys()) - set(state_dict_modify.keys()) err_msg = [] if unexpected_keys: err_msg.append('unexpected key in source state_dict: {}\n'.format( ', '.join(unexpected_keys))) if missing_keys: err_msg.append('missing keys in source state_dict: {}\n'.format( ', '.join(missing_keys))) err_msg = '\n'.join(err_msg) if err_msg: if strict: raise RuntimeError(err_msg) elif logger is not None: logger.warn(err_msg) else: print(err_msg)
Cream/CDARTS/CDARTS_detection/mmdet/models/backbones/resnet.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmdet/models/backbones/resnet.py", "repo_id": "Cream", "token_count": 15964 }
271
import torch from mmdet.core import bbox2roi, build_assigner, build_sampler from ..registry import DETECTORS from .two_stage import TwoStageDetector @DETECTORS.register_module class DoubleHeadRCNN(TwoStageDetector): def __init__(self, reg_roi_scale_factor, cls_roi_scale_factor=None, **kwargs): super().__init__(**kwargs) self.reg_roi_scale_factor = reg_roi_scale_factor self.cls_roi_scale_factor = cls_roi_scale_factor def forward_dummy(self, img): outs = () # backbone x = self.extract_feat(img) # rpn if self.with_rpn: rpn_outs = self.rpn_head(x) outs = outs + (rpn_outs, ) proposals = torch.randn(1000, 4).cuda() # bbox head rois = bbox2roi([proposals]) bbox_cls_feats = self.bbox_roi_extractor( x[:self.bbox_roi_extractor.num_inputs], rois, roi_scale_factor=self.cls_roi_scale_factor) bbox_reg_feats = self.bbox_roi_extractor( x[:self.bbox_roi_extractor.num_inputs], rois, roi_scale_factor=self.reg_roi_scale_factor) if self.with_shared_head: bbox_cls_feats = self.shared_head(bbox_cls_feats) bbox_reg_feats = self.shared_head(bbox_reg_feats) cls_score, bbox_pred = self.bbox_head(bbox_cls_feats, bbox_reg_feats) outs += (cls_score, bbox_pred) return outs def forward_train(self, img, img_meta, gt_bboxes, gt_labels, gt_bboxes_ignore=None, gt_masks=None, proposals=None): out = self.extract_feat(img) if len(out) >= 4: x = out loss_latency = None else: x = out[0] loss_latency = out[1] losses = dict() # RPN forward and loss if self.with_rpn: rpn_outs = self.rpn_head(x) rpn_loss_inputs = rpn_outs + (gt_bboxes, img_meta, self.train_cfg.rpn) rpn_losses = self.rpn_head.loss( *rpn_loss_inputs, gt_bboxes_ignore=gt_bboxes_ignore) losses.update(rpn_losses) proposal_cfg = self.train_cfg.get('rpn_proposal', self.test_cfg.rpn) proposal_inputs = rpn_outs + (img_meta, proposal_cfg) proposal_list = self.rpn_head.get_bboxes(*proposal_inputs) else: proposal_list = proposals # assign gts and sample proposals if self.with_bbox or self.with_mask: bbox_assigner = build_assigner(self.train_cfg.rcnn.assigner) bbox_sampler = build_sampler( self.train_cfg.rcnn.sampler, context=self) num_imgs = img.size(0) if gt_bboxes_ignore is None: gt_bboxes_ignore = [None for _ in range(num_imgs)] sampling_results = [] for i in range(num_imgs): assign_result = bbox_assigner.assign(proposal_list[i], gt_bboxes[i], gt_bboxes_ignore[i], gt_labels[i]) sampling_result = bbox_sampler.sample( assign_result, proposal_list[i], gt_bboxes[i], gt_labels[i], feats=[lvl_feat[i][None] for lvl_feat in x]) sampling_results.append(sampling_result) # bbox head forward and loss if self.with_bbox: rois = bbox2roi([res.bboxes for res in sampling_results]) # TODO: a more flexible way to decide which feature maps to use bbox_cls_feats = self.bbox_roi_extractor( x[:self.bbox_roi_extractor.num_inputs], rois, roi_scale_factor=self.cls_roi_scale_factor) bbox_reg_feats = self.bbox_roi_extractor( x[:self.bbox_roi_extractor.num_inputs], rois, roi_scale_factor=self.reg_roi_scale_factor) if self.with_shared_head: bbox_cls_feats = self.shared_head(bbox_cls_feats) bbox_reg_feats = self.shared_head(bbox_reg_feats) cls_score, bbox_pred = self.bbox_head(bbox_cls_feats, bbox_reg_feats) bbox_targets = self.bbox_head.get_target(sampling_results, gt_bboxes, gt_labels, self.train_cfg.rcnn) loss_bbox = self.bbox_head.loss(cls_score, bbox_pred, *bbox_targets) losses.update(loss_bbox) # mask head forward and loss if self.with_mask: if not self.share_roi_extractor: pos_rois = bbox2roi( [res.pos_bboxes for res in sampling_results]) mask_feats = self.mask_roi_extractor( x[:self.mask_roi_extractor.num_inputs], pos_rois) if self.with_shared_head: mask_feats = self.shared_head(mask_feats) else: pos_inds = [] device = bbox_cls_feats.device for res in sampling_results: pos_inds.append( torch.ones( res.pos_bboxes.shape[0], device=device, dtype=torch.uint8)) pos_inds.append( torch.zeros( res.neg_bboxes.shape[0], device=device, dtype=torch.uint8)) pos_inds = torch.cat(pos_inds) mask_feats = bbox_cls_feats[pos_inds] mask_pred = self.mask_head(mask_feats) mask_targets = self.mask_head.get_target(sampling_results, gt_masks, self.train_cfg.rcnn) pos_labels = torch.cat( [res.pos_gt_labels for res in sampling_results]) loss_mask = self.mask_head.loss(mask_pred, mask_targets, pos_labels) losses.update(loss_mask) return losses, loss_latency def simple_test_bboxes(self, x, img_meta, proposals, rcnn_test_cfg, rescale=False): """Test only det bboxes without augmentation.""" rois = bbox2roi(proposals) bbox_cls_feats = self.bbox_roi_extractor( x[:self.bbox_roi_extractor.num_inputs], rois, roi_scale_factor=self.cls_roi_scale_factor) bbox_reg_feats = self.bbox_roi_extractor( x[:self.bbox_roi_extractor.num_inputs], rois, roi_scale_factor=self.reg_roi_scale_factor) if self.with_shared_head: bbox_cls_feats = self.shared_head(bbox_cls_feats) bbox_reg_feats = self.shared_head(bbox_reg_feats) cls_score, bbox_pred = self.bbox_head(bbox_cls_feats, bbox_reg_feats) img_shape = img_meta[0]['img_shape'] scale_factor = img_meta[0]['scale_factor'] det_bboxes, det_labels = self.bbox_head.get_det_bboxes( rois, cls_score, bbox_pred, img_shape, scale_factor, rescale=rescale, cfg=rcnn_test_cfg) return det_bboxes, det_labels
Cream/CDARTS/CDARTS_detection/mmdet/models/detectors/double_head_rcnn.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmdet/models/detectors/double_head_rcnn.py", "repo_id": "Cream", "token_count": 4788 }
272
import torch import torch.nn as nn import torch.nn.functional as F from .utils import weight_reduce_loss from ..registry import LOSSES def cross_entropy(pred, label, weight=None, reduction='mean', avg_factor=None): # element-wise losses loss = F.cross_entropy(pred, label, reduction='none') # apply weights and do the reduction if weight is not None: weight = weight.float() loss = weight_reduce_loss( loss, weight=weight, reduction=reduction, avg_factor=avg_factor) return loss def _expand_binary_labels(labels, label_weights, label_channels): bin_labels = labels.new_full((labels.size(0), label_channels), 0) inds = torch.nonzero(labels >= 1).squeeze() if inds.numel() > 0: bin_labels[inds, labels[inds] - 1] = 1 if label_weights is None: bin_label_weights = None else: bin_label_weights = label_weights.view(-1, 1).expand( label_weights.size(0), label_channels) return bin_labels, bin_label_weights def binary_cross_entropy(pred, label, weight=None, reduction='mean', avg_factor=None): if pred.dim() != label.dim(): label, weight = _expand_binary_labels(label, weight, pred.size(-1)) # weighted element-wise losses if weight is not None: weight = weight.float() loss = F.binary_cross_entropy_with_logits( pred, label.float(), weight, reduction='none') # do the reduction for the weighted loss loss = weight_reduce_loss(loss, reduction=reduction, avg_factor=avg_factor) return loss def mask_cross_entropy(pred, target, label, reduction='mean', avg_factor=None): # TODO: handle these two reserved arguments assert reduction == 'mean' and avg_factor is None num_rois = pred.size()[0] inds = torch.arange(0, num_rois, dtype=torch.long, device=pred.device) pred_slice = pred[inds, label].squeeze(1) return F.binary_cross_entropy_with_logits( pred_slice, target, reduction='mean')[None] @LOSSES.register_module class CrossEntropyLoss(nn.Module): def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', loss_weight=1.0): super(CrossEntropyLoss, self).__init__() assert (use_sigmoid is False) or (use_mask is False) self.use_sigmoid = use_sigmoid self.use_mask = use_mask self.reduction = reduction self.loss_weight = loss_weight if self.use_sigmoid: self.cls_criterion = binary_cross_entropy elif self.use_mask: self.cls_criterion = mask_cross_entropy else: self.cls_criterion = cross_entropy def forward(self, cls_score, label, weight=None, avg_factor=None, reduction_override=None, **kwargs): assert reduction_override in (None, 'none', 'mean', 'sum') reduction = ( reduction_override if reduction_override else self.reduction) loss_cls = self.loss_weight * self.cls_criterion( cls_score, label, weight, reduction=reduction, avg_factor=avg_factor, **kwargs) return loss_cls
Cream/CDARTS/CDARTS_detection/mmdet/models/losses/cross_entropy_loss.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmdet/models/losses/cross_entropy_loss.py", "repo_id": "Cream", "token_count": 1550 }
273
# -------------------------------------------------------- # Copyright (c) 2019 Jianyuan Guo ([email protected]) # -------------------------------------------------------- import torch import torch.nn as nn import torch.nn.functional as F from .hit_ops import OPS PRIMITIVES = [ 'conv_1x1', 'ir_k3_e6_d3', 'ir_k5_e6', 'ir_k5_e6_d3', 'sd_k3_d1', 'sd_k3_d3', 'sd_k5_d2', 'sd_k5_d3', ] class HitNeck(nn.Module): def __init__(self, num_fm=4, in_channel=[256], out_channel=256, latency=None, gamma=0.02, genotype=None, **kwargs): super(HitNeck, self).__init__() self.num_fm = num_fm self.in_channel = in_channel self.out_channel = out_channel self.genotype = genotype bn_type = kwargs.get('bn_type', 'BN') self.cells = nn.ModuleList() input_size = [160, 80, 40, 20] # 1/4, 1/8, 1/16, 1/32 for i, ops in enumerate(genotype): if i < self.num_fm: cell = OPS[PRIMITIVES[ops]](input_size[i%self.num_fm], in_channel[i%self.num_fm], out_channel, 1, bn=bn_type) else: cell = OPS[PRIMITIVES[ops]](input_size[i%self.num_fm], out_channel, out_channel, 1, bn=bn_type) self.cells.append(cell) for m in self.modules(): if isinstance(m, nn.SyncBatchNorm): m._specify_ddp_gpu_num(1) def forward(self, x, step): assert(step in [1, 2]) _step = step - 1 out = [] for i in range(_step*self.num_fm, step*self.num_fm): out.append(self.cells[i](x[i%self.num_fm])) return out
Cream/CDARTS/CDARTS_detection/mmdet/models/necks/auto_neck/hit_neck_search.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmdet/models/necks/auto_neck/hit_neck_search.py", "repo_id": "Cream", "token_count": 882 }
274
from .conv_ws import conv_ws_2d, ConvWS2d from .conv_module import build_conv_layer, ConvModule from .norm import build_norm_layer from .scale import Scale from .weight_init import (xavier_init, normal_init, uniform_init, kaiming_init, bias_init_with_prob) __all__ = [ 'conv_ws_2d', 'ConvWS2d', 'build_conv_layer', 'ConvModule', 'build_norm_layer', 'xavier_init', 'normal_init', 'uniform_init', 'kaiming_init', 'bias_init_with_prob', 'Scale' ]
Cream/CDARTS/CDARTS_detection/mmdet/models/utils/__init__.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmdet/models/utils/__init__.py", "repo_id": "Cream", "token_count": 204 }
275
// modify from // https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/blob/mmdetection/mmdet/ops/dcn/src/deform_conv_cuda.c #include <torch/extension.h> #include <cmath> #include <vector> void deformable_im2col(const at::Tensor data_im, const at::Tensor data_offset, const int channels, const int height, const int width, const int ksize_h, const int ksize_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, const int parallel_imgs, const int deformable_group, at::Tensor data_col); void deformable_col2im(const at::Tensor data_col, const at::Tensor data_offset, const int channels, const int height, const int width, const int ksize_h, const int ksize_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, const int parallel_imgs, const int deformable_group, at::Tensor grad_im); void deformable_col2im_coord( const at::Tensor data_col, const at::Tensor data_im, const at::Tensor data_offset, const int channels, const int height, const int width, const int ksize_h, const int ksize_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, const int parallel_imgs, const int deformable_group, at::Tensor grad_offset); void modulated_deformable_im2col_cuda( const at::Tensor data_im, const at::Tensor data_offset, const at::Tensor data_mask, const int batch_size, const int channels, const int height_im, const int width_im, const int height_col, const int width_col, const int kernel_h, const int kenerl_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, const int deformable_group, at::Tensor data_col); void modulated_deformable_col2im_cuda( const at::Tensor data_col, const at::Tensor data_offset, const at::Tensor data_mask, const int batch_size, const int channels, const int height_im, const int width_im, const int height_col, const int width_col, const int kernel_h, const int kenerl_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, const int deformable_group, at::Tensor grad_im); void modulated_deformable_col2im_coord_cuda( const at::Tensor data_col, const at::Tensor data_im, const at::Tensor data_offset, const at::Tensor data_mask, const int batch_size, const int channels, const int height_im, const int width_im, const int height_col, const int width_col, const int kernel_h, const int kenerl_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, const int deformable_group, at::Tensor grad_offset, at::Tensor grad_mask); void shape_check(at::Tensor input, at::Tensor offset, at::Tensor *gradOutput, at::Tensor weight, int kH, int kW, int dH, int dW, int padH, int padW, int dilationH, int dilationW, int group, int deformable_group) { TORCH_CHECK(weight.ndimension() == 4, "4D weight tensor (nOutputPlane,nInputPlane,kH,kW) expected, " "but got: %s", weight.ndimension()); TORCH_CHECK(weight.is_contiguous(), "weight tensor has to be contiguous"); TORCH_CHECK(kW > 0 && kH > 0, "kernel size should be greater than zero, but got kH: %d kW: %d", kH, kW); TORCH_CHECK((weight.size(2) == kH && weight.size(3) == kW), "kernel size should be consistent with weight, ", "but got kH: %d kW: %d weight.size(2): %d, weight.size(3): %d", kH, kW, weight.size(2), weight.size(3)); TORCH_CHECK(dW > 0 && dH > 0, "stride should be greater than zero, but got dH: %d dW: %d", dH, dW); TORCH_CHECK( dilationW > 0 && dilationH > 0, "dilation should be greater than 0, but got dilationH: %d dilationW: %d", dilationH, dilationW); int ndim = input.ndimension(); int dimf = 0; int dimh = 1; int dimw = 2; if (ndim == 4) { dimf++; dimh++; dimw++; } TORCH_CHECK(ndim == 3 || ndim == 4, "3D or 4D input tensor expected but got: %s", ndim); long nInputPlane = weight.size(1) * group; long inputHeight = input.size(dimh); long inputWidth = input.size(dimw); long nOutputPlane = weight.size(0); long outputHeight = (inputHeight + 2 * padH - (dilationH * (kH - 1) + 1)) / dH + 1; long outputWidth = (inputWidth + 2 * padW - (dilationW * (kW - 1) + 1)) / dW + 1; TORCH_CHECK(nInputPlane % deformable_group == 0, "input channels must divide deformable group size"); if (outputWidth < 1 || outputHeight < 1) AT_ERROR( "Given input size: (%ld x %ld x %ld). " "Calculated output size: (%ld x %ld x %ld). Output size is too small", nInputPlane, inputHeight, inputWidth, nOutputPlane, outputHeight, outputWidth); TORCH_CHECK(input.size(1) == nInputPlane, "invalid number of input planes, expected: %d, but got: %d", nInputPlane, input.size(1)); TORCH_CHECK((inputHeight >= kH && inputWidth >= kW), "input image is smaller than kernel"); TORCH_CHECK((offset.size(2) == outputHeight && offset.size(3) == outputWidth), "invalid spatial size of offset, expected height: %d width: %d, but " "got height: %d width: %d", outputHeight, outputWidth, offset.size(2), offset.size(3)); TORCH_CHECK((offset.size(1) == deformable_group * 2 * kH * kW), "invalid number of channels of offset"); if (gradOutput != NULL) { TORCH_CHECK(gradOutput->size(dimf) == nOutputPlane, "invalid number of gradOutput planes, expected: %d, but got: %d", nOutputPlane, gradOutput->size(dimf)); TORCH_CHECK((gradOutput->size(dimh) == outputHeight && gradOutput->size(dimw) == outputWidth), "invalid size of gradOutput, expected height: %d width: %d , but " "got height: %d width: %d", outputHeight, outputWidth, gradOutput->size(dimh), gradOutput->size(dimw)); } } int deform_conv_forward_cuda(at::Tensor input, at::Tensor weight, at::Tensor offset, at::Tensor output, at::Tensor columns, at::Tensor ones, int kW, int kH, int dW, int dH, int padW, int padH, int dilationW, int dilationH, int group, int deformable_group, int im2col_step) { // todo: resize columns to include im2col: done // todo: add im2col_step as input // todo: add new output buffer and transpose it to output (or directly // transpose output) todo: possibly change data indexing because of // parallel_imgs shape_check(input, offset, NULL, weight, kH, kW, dH, dW, padH, padW, dilationH, dilationW, group, deformable_group); input = input.contiguous(); offset = offset.contiguous(); weight = weight.contiguous(); int batch = 1; if (input.ndimension() == 3) { // Force batch batch = 0; input.unsqueeze_(0); offset.unsqueeze_(0); } // todo: assert batchsize dividable by im2col_step long batchSize = input.size(0); long nInputPlane = input.size(1); long inputHeight = input.size(2); long inputWidth = input.size(3); long nOutputPlane = weight.size(0); long outputWidth = (inputWidth + 2 * padW - (dilationW * (kW - 1) + 1)) / dW + 1; long outputHeight = (inputHeight + 2 * padH - (dilationH * (kH - 1) + 1)) / dH + 1; TORCH_CHECK((offset.size(0) == batchSize), "invalid batch size of offset"); output = output.view({batchSize / im2col_step, im2col_step, nOutputPlane, outputHeight, outputWidth}); columns = at::zeros( {nInputPlane * kW * kH, im2col_step * outputHeight * outputWidth}, input.options()); if (ones.ndimension() != 2 || ones.size(0) * ones.size(1) < outputHeight * outputWidth) { ones = at::ones({outputHeight, outputWidth}, input.options()); } input = input.view({batchSize / im2col_step, im2col_step, nInputPlane, inputHeight, inputWidth}); offset = offset.view({batchSize / im2col_step, im2col_step, deformable_group * 2 * kH * kW, outputHeight, outputWidth}); at::Tensor output_buffer = at::zeros({batchSize / im2col_step, nOutputPlane, im2col_step * outputHeight, outputWidth}, output.options()); output_buffer = output_buffer.view( {output_buffer.size(0), group, output_buffer.size(1) / group, output_buffer.size(2), output_buffer.size(3)}); for (int elt = 0; elt < batchSize / im2col_step; elt++) { deformable_im2col(input[elt], offset[elt], nInputPlane, inputHeight, inputWidth, kH, kW, padH, padW, dH, dW, dilationH, dilationW, im2col_step, deformable_group, columns); columns = columns.view({group, columns.size(0) / group, columns.size(1)}); weight = weight.view({group, weight.size(0) / group, weight.size(1), weight.size(2), weight.size(3)}); for (int g = 0; g < group; g++) { output_buffer[elt][g] = output_buffer[elt][g] .flatten(1) .addmm_(weight[g].flatten(1), columns[g]) .view_as(output_buffer[elt][g]); } } output_buffer = output_buffer.view( {output_buffer.size(0), output_buffer.size(1) * output_buffer.size(2), output_buffer.size(3), output_buffer.size(4)}); output_buffer = output_buffer.view({batchSize / im2col_step, nOutputPlane, im2col_step, outputHeight, outputWidth}); output_buffer.transpose_(1, 2); output.copy_(output_buffer); output = output.view({batchSize, nOutputPlane, outputHeight, outputWidth}); input = input.view({batchSize, nInputPlane, inputHeight, inputWidth}); offset = offset.view( {batchSize, deformable_group * 2 * kH * kW, outputHeight, outputWidth}); if (batch == 0) { output = output.view({nOutputPlane, outputHeight, outputWidth}); input = input.view({nInputPlane, inputHeight, inputWidth}); offset = offset.view({offset.size(1), offset.size(2), offset.size(3)}); } return 1; } int deform_conv_backward_input_cuda(at::Tensor input, at::Tensor offset, at::Tensor gradOutput, at::Tensor gradInput, at::Tensor gradOffset, at::Tensor weight, at::Tensor columns, int kW, int kH, int dW, int dH, int padW, int padH, int dilationW, int dilationH, int group, int deformable_group, int im2col_step) { shape_check(input, offset, &gradOutput, weight, kH, kW, dH, dW, padH, padW, dilationH, dilationW, group, deformable_group); input = input.contiguous(); offset = offset.contiguous(); gradOutput = gradOutput.contiguous(); weight = weight.contiguous(); int batch = 1; if (input.ndimension() == 3) { // Force batch batch = 0; input = input.view({1, input.size(0), input.size(1), input.size(2)}); offset = offset.view({1, offset.size(0), offset.size(1), offset.size(2)}); gradOutput = gradOutput.view( {1, gradOutput.size(0), gradOutput.size(1), gradOutput.size(2)}); } long batchSize = input.size(0); long nInputPlane = input.size(1); long inputHeight = input.size(2); long inputWidth = input.size(3); long nOutputPlane = weight.size(0); long outputWidth = (inputWidth + 2 * padW - (dilationW * (kW - 1) + 1)) / dW + 1; long outputHeight = (inputHeight + 2 * padH - (dilationH * (kH - 1) + 1)) / dH + 1; TORCH_CHECK((offset.size(0) == batchSize), 3, "invalid batch size of offset"); gradInput = gradInput.view({batchSize, nInputPlane, inputHeight, inputWidth}); columns = at::zeros( {nInputPlane * kW * kH, im2col_step * outputHeight * outputWidth}, input.options()); // change order of grad output gradOutput = gradOutput.view({batchSize / im2col_step, im2col_step, nOutputPlane, outputHeight, outputWidth}); gradOutput.transpose_(1, 2); gradInput = gradInput.view({batchSize / im2col_step, im2col_step, nInputPlane, inputHeight, inputWidth}); input = input.view({batchSize / im2col_step, im2col_step, nInputPlane, inputHeight, inputWidth}); gradOffset = gradOffset.view({batchSize / im2col_step, im2col_step, deformable_group * 2 * kH * kW, outputHeight, outputWidth}); offset = offset.view({batchSize / im2col_step, im2col_step, deformable_group * 2 * kH * kW, outputHeight, outputWidth}); for (int elt = 0; elt < batchSize / im2col_step; elt++) { // divide into groups columns = columns.view({group, columns.size(0) / group, columns.size(1)}); weight = weight.view({group, weight.size(0) / group, weight.size(1), weight.size(2), weight.size(3)}); gradOutput = gradOutput.view( {gradOutput.size(0), group, gradOutput.size(1) / group, gradOutput.size(2), gradOutput.size(3), gradOutput.size(4)}); for (int g = 0; g < group; g++) { columns[g] = columns[g].addmm_(weight[g].flatten(1).transpose(0, 1), gradOutput[elt][g].flatten(1), 0.0f, 1.0f); } columns = columns.view({columns.size(0) * columns.size(1), columns.size(2)}); gradOutput = gradOutput.view( {gradOutput.size(0), gradOutput.size(1) * gradOutput.size(2), gradOutput.size(3), gradOutput.size(4), gradOutput.size(5)}); deformable_col2im_coord(columns, input[elt], offset[elt], nInputPlane, inputHeight, inputWidth, kH, kW, padH, padW, dH, dW, dilationH, dilationW, im2col_step, deformable_group, gradOffset[elt]); deformable_col2im(columns, offset[elt], nInputPlane, inputHeight, inputWidth, kH, kW, padH, padW, dH, dW, dilationH, dilationW, im2col_step, deformable_group, gradInput[elt]); } gradOutput.transpose_(1, 2); gradOutput = gradOutput.view({batchSize, nOutputPlane, outputHeight, outputWidth}); gradInput = gradInput.view({batchSize, nInputPlane, inputHeight, inputWidth}); input = input.view({batchSize, nInputPlane, inputHeight, inputWidth}); gradOffset = gradOffset.view( {batchSize, deformable_group * 2 * kH * kW, outputHeight, outputWidth}); offset = offset.view( {batchSize, deformable_group * 2 * kH * kW, outputHeight, outputWidth}); if (batch == 0) { gradOutput = gradOutput.view({nOutputPlane, outputHeight, outputWidth}); input = input.view({nInputPlane, inputHeight, inputWidth}); gradInput = gradInput.view({nInputPlane, inputHeight, inputWidth}); offset = offset.view({offset.size(1), offset.size(2), offset.size(3)}); gradOffset = gradOffset.view({offset.size(1), offset.size(2), offset.size(3)}); } return 1; } int deform_conv_backward_parameters_cuda( at::Tensor input, at::Tensor offset, at::Tensor gradOutput, at::Tensor gradWeight, // at::Tensor gradBias, at::Tensor columns, at::Tensor ones, int kW, int kH, int dW, int dH, int padW, int padH, int dilationW, int dilationH, int group, int deformable_group, float scale, int im2col_step) { // todo: transpose and reshape outGrad // todo: reshape columns // todo: add im2col_step as input shape_check(input, offset, &gradOutput, gradWeight, kH, kW, dH, dW, padH, padW, dilationH, dilationW, group, deformable_group); input = input.contiguous(); offset = offset.contiguous(); gradOutput = gradOutput.contiguous(); int batch = 1; if (input.ndimension() == 3) { // Force batch batch = 0; input = input.view( at::IntList({1, input.size(0), input.size(1), input.size(2)})); gradOutput = gradOutput.view( {1, gradOutput.size(0), gradOutput.size(1), gradOutput.size(2)}); } long batchSize = input.size(0); long nInputPlane = input.size(1); long inputHeight = input.size(2); long inputWidth = input.size(3); long nOutputPlane = gradWeight.size(0); long outputWidth = (inputWidth + 2 * padW - (dilationW * (kW - 1) + 1)) / dW + 1; long outputHeight = (inputHeight + 2 * padH - (dilationH * (kH - 1) + 1)) / dH + 1; TORCH_CHECK((offset.size(0) == batchSize), "invalid batch size of offset"); columns = at::zeros( {nInputPlane * kW * kH, im2col_step * outputHeight * outputWidth}, input.options()); gradOutput = gradOutput.view({batchSize / im2col_step, im2col_step, nOutputPlane, outputHeight, outputWidth}); gradOutput.transpose_(1, 2); at::Tensor gradOutputBuffer = at::zeros_like(gradOutput); gradOutputBuffer = gradOutputBuffer.view({batchSize / im2col_step, nOutputPlane, im2col_step, outputHeight, outputWidth}); gradOutputBuffer.copy_(gradOutput); gradOutputBuffer = gradOutputBuffer.view({batchSize / im2col_step, nOutputPlane, im2col_step * outputHeight, outputWidth}); gradOutput.transpose_(1, 2); gradOutput = gradOutput.view({batchSize, nOutputPlane, outputHeight, outputWidth}); input = input.view({batchSize / im2col_step, im2col_step, nInputPlane, inputHeight, inputWidth}); offset = offset.view({batchSize / im2col_step, im2col_step, deformable_group * 2 * kH * kW, outputHeight, outputWidth}); for (int elt = 0; elt < batchSize / im2col_step; elt++) { deformable_im2col(input[elt], offset[elt], nInputPlane, inputHeight, inputWidth, kH, kW, padH, padW, dH, dW, dilationH, dilationW, im2col_step, deformable_group, columns); // divide into group gradOutputBuffer = gradOutputBuffer.view( {gradOutputBuffer.size(0), group, gradOutputBuffer.size(1) / group, gradOutputBuffer.size(2), gradOutputBuffer.size(3)}); columns = columns.view({group, columns.size(0) / group, columns.size(1)}); gradWeight = gradWeight.view({group, gradWeight.size(0) / group, gradWeight.size(1), gradWeight.size(2), gradWeight.size(3)}); for (int g = 0; g < group; g++) { gradWeight[g] = gradWeight[g] .flatten(1) .addmm_(gradOutputBuffer[elt][g].flatten(1), columns[g].transpose(1, 0), 1.0, scale) .view_as(gradWeight[g]); } gradOutputBuffer = gradOutputBuffer.view( {gradOutputBuffer.size(0), gradOutputBuffer.size(1) * gradOutputBuffer.size(2), gradOutputBuffer.size(3), gradOutputBuffer.size(4)}); columns = columns.view({columns.size(0) * columns.size(1), columns.size(2)}); gradWeight = gradWeight.view({gradWeight.size(0) * gradWeight.size(1), gradWeight.size(2), gradWeight.size(3), gradWeight.size(4)}); } input = input.view({batchSize, nInputPlane, inputHeight, inputWidth}); offset = offset.view( {batchSize, deformable_group * 2 * kH * kW, outputHeight, outputWidth}); if (batch == 0) { gradOutput = gradOutput.view({nOutputPlane, outputHeight, outputWidth}); input = input.view({nInputPlane, inputHeight, inputWidth}); } return 1; } void modulated_deform_conv_cuda_forward( at::Tensor input, at::Tensor weight, at::Tensor bias, at::Tensor ones, at::Tensor offset, at::Tensor mask, at::Tensor output, at::Tensor columns, int kernel_h, int kernel_w, const int stride_h, const int stride_w, const int pad_h, const int pad_w, const int dilation_h, const int dilation_w, const int group, const int deformable_group, const bool with_bias) { TORCH_CHECK(input.is_contiguous(), "input tensor has to be contiguous"); TORCH_CHECK(weight.is_contiguous(), "weight tensor has to be contiguous"); const int batch = input.size(0); const int channels = input.size(1); const int height = input.size(2); const int width = input.size(3); const int channels_out = weight.size(0); const int channels_kernel = weight.size(1); const int kernel_h_ = weight.size(2); const int kernel_w_ = weight.size(3); if (kernel_h_ != kernel_h || kernel_w_ != kernel_w) AT_ERROR("Input shape and kernel shape wont match: (%d x %d vs %d x %d).", kernel_h_, kernel_w, kernel_h_, kernel_w_); if (channels != channels_kernel * group) AT_ERROR("Input shape and kernel channels wont match: (%d vs %d).", channels, channels_kernel * group); const int height_out = (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1; const int width_out = (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1; if (ones.ndimension() != 2 || ones.size(0) * ones.size(1) < height_out * width_out) { // Resize plane and fill with ones... ones = at::ones({height_out, width_out}, input.options()); } // resize output output = output.view({batch, channels_out, height_out, width_out}).zero_(); // resize temporary columns columns = at::zeros({channels * kernel_h * kernel_w, 1 * height_out * width_out}, input.options()); output = output.view({output.size(0), group, output.size(1) / group, output.size(2), output.size(3)}); for (int b = 0; b < batch; b++) { modulated_deformable_im2col_cuda( input[b], offset[b], mask[b], 1, channels, height, width, height_out, width_out, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w, dilation_h, dilation_w, deformable_group, columns); // divide into group weight = weight.view({group, weight.size(0) / group, weight.size(1), weight.size(2), weight.size(3)}); columns = columns.view({group, columns.size(0) / group, columns.size(1)}); for (int g = 0; g < group; g++) { output[b][g] = output[b][g] .flatten(1) .addmm_(weight[g].flatten(1), columns[g]) .view_as(output[b][g]); } weight = weight.view({weight.size(0) * weight.size(1), weight.size(2), weight.size(3), weight.size(4)}); columns = columns.view({columns.size(0) * columns.size(1), columns.size(2)}); } output = output.view({output.size(0), output.size(1) * output.size(2), output.size(3), output.size(4)}); if (with_bias) { output += bias.view({1, bias.size(0), 1, 1}); } } void modulated_deform_conv_cuda_backward( at::Tensor input, at::Tensor weight, at::Tensor bias, at::Tensor ones, at::Tensor offset, at::Tensor mask, at::Tensor columns, at::Tensor grad_input, at::Tensor grad_weight, at::Tensor grad_bias, at::Tensor grad_offset, at::Tensor grad_mask, at::Tensor grad_output, int kernel_h, int kernel_w, int stride_h, int stride_w, int pad_h, int pad_w, int dilation_h, int dilation_w, int group, int deformable_group, const bool with_bias) { TORCH_CHECK(input.is_contiguous(), "input tensor has to be contiguous"); TORCH_CHECK(weight.is_contiguous(), "weight tensor has to be contiguous"); const int batch = input.size(0); const int channels = input.size(1); const int height = input.size(2); const int width = input.size(3); const int channels_kernel = weight.size(1); const int kernel_h_ = weight.size(2); const int kernel_w_ = weight.size(3); if (kernel_h_ != kernel_h || kernel_w_ != kernel_w) AT_ERROR("Input shape and kernel shape wont match: (%d x %d vs %d x %d).", kernel_h_, kernel_w, kernel_h_, kernel_w_); if (channels != channels_kernel * group) AT_ERROR("Input shape and kernel channels wont match: (%d vs %d).", channels, channels_kernel * group); const int height_out = (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1; const int width_out = (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1; if (ones.ndimension() != 2 || ones.size(0) * ones.size(1) < height_out * width_out) { // Resize plane and fill with ones... ones = at::ones({height_out, width_out}, input.options()); } grad_input = grad_input.view({batch, channels, height, width}); columns = at::zeros({channels * kernel_h * kernel_w, height_out * width_out}, input.options()); grad_output = grad_output.view({grad_output.size(0), group, grad_output.size(1) / group, grad_output.size(2), grad_output.size(3)}); for (int b = 0; b < batch; b++) { // divide int group columns = columns.view({group, columns.size(0) / group, columns.size(1)}); weight = weight.view({group, weight.size(0) / group, weight.size(1), weight.size(2), weight.size(3)}); for (int g = 0; g < group; g++) { columns[g].addmm_(weight[g].flatten(1).transpose(0, 1), grad_output[b][g].flatten(1), 0.0f, 1.0f); } columns = columns.view({columns.size(0) * columns.size(1), columns.size(2)}); weight = weight.view({weight.size(0) * weight.size(1), weight.size(2), weight.size(3), weight.size(4)}); // gradient w.r.t. input coordinate data modulated_deformable_col2im_coord_cuda( columns, input[b], offset[b], mask[b], 1, channels, height, width, height_out, width_out, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w, dilation_h, dilation_w, deformable_group, grad_offset[b], grad_mask[b]); // gradient w.r.t. input data modulated_deformable_col2im_cuda( columns, offset[b], mask[b], 1, channels, height, width, height_out, width_out, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w, dilation_h, dilation_w, deformable_group, grad_input[b]); // gradient w.r.t. weight, dWeight should accumulate across the batch and // group modulated_deformable_im2col_cuda( input[b], offset[b], mask[b], 1, channels, height, width, height_out, width_out, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w, dilation_h, dilation_w, deformable_group, columns); columns = columns.view({group, columns.size(0) / group, columns.size(1)}); grad_weight = grad_weight.view({group, grad_weight.size(0) / group, grad_weight.size(1), grad_weight.size(2), grad_weight.size(3)}); if (with_bias) grad_bias = grad_bias.view({group, grad_bias.size(0) / group}); for (int g = 0; g < group; g++) { grad_weight[g] = grad_weight[g] .flatten(1) .addmm_(grad_output[b][g].flatten(1), columns[g].transpose(0, 1)) .view_as(grad_weight[g]); if (with_bias) { grad_bias[g] = grad_bias[g] .view({-1, 1}) .addmm_(grad_output[b][g].flatten(1), ones.view({-1, 1})) .view(-1); } } columns = columns.view({columns.size(0) * columns.size(1), columns.size(2)}); grad_weight = grad_weight.view({grad_weight.size(0) * grad_weight.size(1), grad_weight.size(2), grad_weight.size(3), grad_weight.size(4)}); if (with_bias) grad_bias = grad_bias.view({grad_bias.size(0) * grad_bias.size(1)}); } grad_output = grad_output.view({grad_output.size(0) * grad_output.size(1), grad_output.size(2), grad_output.size(3), grad_output.size(4)}); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("deform_conv_forward_cuda", &deform_conv_forward_cuda, "deform forward (CUDA)"); m.def("deform_conv_backward_input_cuda", &deform_conv_backward_input_cuda, "deform_conv_backward_input (CUDA)"); m.def("deform_conv_backward_parameters_cuda", &deform_conv_backward_parameters_cuda, "deform_conv_backward_parameters (CUDA)"); m.def("modulated_deform_conv_cuda_forward", &modulated_deform_conv_cuda_forward, "modulated deform conv forward (CUDA)"); m.def("modulated_deform_conv_cuda_backward", &modulated_deform_conv_cuda_backward, "modulated deform conv backward (CUDA)"); }
Cream/CDARTS/CDARTS_detection/mmdet/ops/dcn/src/deform_conv_cuda.cpp/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmdet/ops/dcn/src/deform_conv_cuda.cpp", "repo_id": "Cream", "token_count": 12775 }
276
import os.path as osp from setuptools import setup, Extension import numpy as np from Cython.Build import cythonize from Cython.Distutils import build_ext from torch.utils.cpp_extension import BuildExtension, CUDAExtension ext_args = dict( include_dirs=[np.get_include()], language='c++', extra_compile_args={ 'cc': ['-Wno-unused-function', '-Wno-write-strings'], 'nvcc': ['-c', '--compiler-options', '-fPIC'], }, ) extensions = [ Extension('soft_nms_cpu', ['src/soft_nms_cpu.pyx'], **ext_args), ] def customize_compiler_for_nvcc(self): """inject deep into distutils to customize how the dispatch to cc/nvcc works. If you subclass UnixCCompiler, it's not trivial to get your subclass injected in, and still have the right customizations (i.e. distutils.sysconfig.customize_compiler) run on it. So instead of going the OO route, I have this. Note, it's kindof like a wierd functional subclassing going on.""" # tell the compiler it can processes .cu self.src_extensions.append('.cu') # save references to the default compiler_so and _comple methods default_compiler_so = self.compiler_so super = self._compile # now redefine the _compile method. This gets executed for each # object but distutils doesn't have the ability to change compilers # based on source extension: we add it. def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts): if osp.splitext(src)[1] == '.cu': # use the cuda for .cu files self.set_executable('compiler_so', 'nvcc') # use only a subset of the extra_postargs, which are 1-1 translated # from the extra_compile_args in the Extension class postargs = extra_postargs['nvcc'] else: postargs = extra_postargs['cc'] super(obj, src, ext, cc_args, postargs, pp_opts) # reset the default compiler_so, which we might have changed for cuda self.compiler_so = default_compiler_so # inject our redefined _compile method into the class self._compile = _compile class custom_build_ext(build_ext): def build_extensions(self): customize_compiler_for_nvcc(self.compiler) build_ext.build_extensions(self) setup( name='soft_nms', cmdclass={'build_ext': custom_build_ext}, ext_modules=cythonize(extensions), ) setup( name='nms_cuda', ext_modules=[ CUDAExtension('nms_cuda', [ 'src/nms_cuda.cpp', 'src/nms_kernel.cu', ]), CUDAExtension('nms_cpu', [ 'src/nms_cpu.cpp', ]), ], cmdclass={'build_ext': BuildExtension})
Cream/CDARTS/CDARTS_detection/mmdet/ops/nms/setup.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmdet/ops/nms/setup.py", "repo_id": "Cream", "token_count": 1084 }
277
from .functions.roi_pool import roi_pool from .modules.roi_pool import RoIPool __all__ = ['roi_pool', 'RoIPool']
Cream/CDARTS/CDARTS_detection/mmdet/ops/roi_pool/__init__.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmdet/ops/roi_pool/__init__.py", "repo_id": "Cream", "token_count": 45 }
278
// modify from // https://github.com/facebookresearch/maskrcnn-benchmark/blob/master/maskrcnn_benchmark/csrc/cuda/SigmoidFocalLoss_cuda.cu // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. // This file is modified from // https://github.com/pytorch/pytorch/blob/master/modules/detectron/sigmoid_focal_loss_op.cu // Cheng-Yang Fu // [email protected] #include <ATen/ATen.h> #include <ATen/cuda/CUDAContext.h> #include <THC/THC.h> #include <THC/THCAtomics.cuh> #include <THC/THCDeviceUtils.cuh> #include <cfloat> // TODO make it in a common file #define CUDA_1D_KERNEL_LOOP(i, n) \ for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; \ i += blockDim.x * gridDim.x) template <typename scalar_t> __global__ void SigmoidFocalLossForward(const int nthreads, const scalar_t *logits, const long *targets, const int num_classes, const float gamma, const float alpha, const int num, scalar_t *losses) { CUDA_1D_KERNEL_LOOP(i, nthreads) { int n = i / num_classes; int d = i % num_classes; // current class[0~79]; int t = targets[n]; // target class [1~80]; // Decide it is positive or negative case. scalar_t c1 = (t == (d + 1)); scalar_t c2 = (t >= 0 & t != (d + 1)); scalar_t zn = (1.0 - alpha); scalar_t zp = (alpha); // p = 1. / 1. + expf(-x); p = sigmoid(x) scalar_t p = 1. / (1. + expf(-logits[i])); // (1-p)**gamma * log(p) where scalar_t term1 = powf((1. - p), gamma) * logf(max(p, FLT_MIN)); // p**gamma * log(1-p) scalar_t term2 = powf(p, gamma) * (-1. * logits[i] * (logits[i] >= 0) - logf(1. + expf(logits[i] - 2. * logits[i] * (logits[i] >= 0)))); losses[i] = 0.0; losses[i] += -c1 * term1 * zp; losses[i] += -c2 * term2 * zn; } // CUDA_1D_KERNEL_LOOP } // SigmoidFocalLossForward template <typename scalar_t> __global__ void SigmoidFocalLossBackward( const int nthreads, const scalar_t *logits, const long *targets, const scalar_t *d_losses, const int num_classes, const float gamma, const float alpha, const int num, scalar_t *d_logits) { CUDA_1D_KERNEL_LOOP(i, nthreads) { int n = i / num_classes; int d = i % num_classes; // current class[0~79]; int t = targets[n]; // target class [1~80], 0 is background; // Decide it is positive or negative case. scalar_t c1 = (t == (d + 1)); scalar_t c2 = (t >= 0 & t != (d + 1)); scalar_t zn = (1.0 - alpha); scalar_t zp = (alpha); // p = 1. / 1. + expf(-x); p = sigmoid(x) scalar_t p = 1. / (1. + expf(-logits[i])); // (1-p)**g * (1 - p - g*p*log(p) scalar_t term1 = powf((1. - p), gamma) * (1. - p - (p * gamma * logf(max(p, FLT_MIN)))); // (p**g) * (g*(1-p)*log(1-p) - p) scalar_t term2 = powf(p, gamma) * ((-1. * logits[i] * (logits[i] >= 0) - logf(1. + expf(logits[i] - 2. * logits[i] * (logits[i] >= 0)))) * (1. - p) * gamma - p); d_logits[i] = 0.0; d_logits[i] += -c1 * term1 * zp; d_logits[i] += -c2 * term2 * zn; d_logits[i] = d_logits[i] * d_losses[i]; } // CUDA_1D_KERNEL_LOOP } // SigmoidFocalLossBackward at::Tensor SigmoidFocalLoss_forward_cuda(const at::Tensor &logits, const at::Tensor &targets, const int num_classes, const float gamma, const float alpha) { AT_ASSERTM(logits.type().is_cuda(), "logits must be a CUDA tensor"); AT_ASSERTM(targets.type().is_cuda(), "targets must be a CUDA tensor"); AT_ASSERTM(logits.dim() == 2, "logits should be NxClass"); const int num_samples = logits.size(0); auto losses = at::empty({num_samples, logits.size(1)}, logits.options()); auto losses_size = num_samples * logits.size(1); dim3 grid(std::min(THCCeilDiv(losses_size, 512L), 4096L)); dim3 block(512); if (losses.numel() == 0) { THCudaCheck(cudaGetLastError()); return losses; } AT_DISPATCH_FLOATING_TYPES_AND_HALF( logits.type(), "SigmoidFocalLoss_forward", [&] { SigmoidFocalLossForward<scalar_t><<<grid, block>>>( losses_size, logits.contiguous().data<scalar_t>(), targets.contiguous().data<long>(), num_classes, gamma, alpha, num_samples, losses.data<scalar_t>()); }); THCudaCheck(cudaGetLastError()); return losses; } at::Tensor SigmoidFocalLoss_backward_cuda(const at::Tensor &logits, const at::Tensor &targets, const at::Tensor &d_losses, const int num_classes, const float gamma, const float alpha) { AT_ASSERTM(logits.type().is_cuda(), "logits must be a CUDA tensor"); AT_ASSERTM(targets.type().is_cuda(), "targets must be a CUDA tensor"); AT_ASSERTM(d_losses.type().is_cuda(), "d_losses must be a CUDA tensor"); AT_ASSERTM(logits.dim() == 2, "logits should be NxClass"); const int num_samples = logits.size(0); AT_ASSERTM(logits.size(1) == num_classes, "logits.size(1) should be num_classes"); auto d_logits = at::zeros({num_samples, num_classes}, logits.options()); auto d_logits_size = num_samples * logits.size(1); dim3 grid(std::min(THCCeilDiv(d_logits_size, 512L), 4096L)); dim3 block(512); if (d_logits.numel() == 0) { THCudaCheck(cudaGetLastError()); return d_logits; } AT_DISPATCH_FLOATING_TYPES_AND_HALF( logits.type(), "SigmoidFocalLoss_backward", [&] { SigmoidFocalLossBackward<scalar_t><<<grid, block>>>( d_logits_size, logits.contiguous().data<scalar_t>(), targets.contiguous().data<long>(), d_losses.contiguous().data<scalar_t>(), num_classes, gamma, alpha, num_samples, d_logits.data<scalar_t>()); }); THCudaCheck(cudaGetLastError()); return d_logits; }
Cream/CDARTS/CDARTS_detection/mmdet/ops/sigmoid_focal_loss/src/sigmoid_focal_loss_cuda.cu/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/mmdet/ops/sigmoid_focal_loss/src/sigmoid_focal_loss_cuda.cu", "repo_id": "Cream", "token_count": 3155 }
279
import argparse from mmcv import Config from mmdet.models import build_detector from mmdet.utils import get_model_complexity_info def parse_args(): parser = argparse.ArgumentParser(description='Train a detector') parser.add_argument('config', help='train config file path') parser.add_argument( '--shape', type=int, nargs='+', default=[1280, 800], help='input image size') args = parser.parse_args() return args def main(): args = parse_args() if len(args.shape) == 1: input_shape = (3, args.shape[0], args.shape[0]) elif len(args.shape) == 2: input_shape = (3, ) + tuple(args.shape) else: raise ValueError('invalid input shape') cfg = Config.fromfile(args.config) model = build_detector( cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg).cuda() model.eval() if hasattr(model, 'forward_dummy'): model.forward = model.forward_dummy else: raise NotImplementedError( 'FLOPs counter is currently not currently supported with {}'. format(model.__class__.__name__)) flops, params = get_model_complexity_info(model, input_shape) split_line = '=' * 30 print('{0}\nInput shape: {1}\nFlops: {2}\nParams: {3}\n{0}'.format( split_line, input_shape, flops, params)) if __name__ == '__main__': main()
Cream/CDARTS/CDARTS_detection/tools/get_flops.py/0
{ "file_path": "Cream/CDARTS/CDARTS_detection/tools/get_flops.py", "repo_id": "Cream", "token_count": 582 }
280
import torch.utils.data as data class CombineDBs(data.Dataset): NUM_CLASSES = 21 def __init__(self, dataloaders, excluded=None): self.dataloaders = dataloaders self.excluded = excluded self.im_ids = [] # Combine object lists for dl in dataloaders: for elem in dl.im_ids: if elem not in self.im_ids: self.im_ids.append(elem) # Exclude if excluded: for dl in excluded: for elem in dl.im_ids: if elem in self.im_ids: self.im_ids.remove(elem) # Get object pointers self.cat_list = [] self.im_list = [] new_im_ids = [] num_images = 0 for ii, dl in enumerate(dataloaders): for jj, curr_im_id in enumerate(dl.im_ids): if (curr_im_id in self.im_ids) and (curr_im_id not in new_im_ids): num_images += 1 new_im_ids.append(curr_im_id) self.cat_list.append({'db_ii': ii, 'cat_ii': jj}) self.im_ids = new_im_ids print('Combined number of images: {:d}'.format(num_images)) def __getitem__(self, index): _db_ii = self.cat_list[index]["db_ii"] _cat_ii = self.cat_list[index]['cat_ii'] sample = self.dataloaders[_db_ii].__getitem__(_cat_ii) if 'meta' in sample.keys(): sample['meta']['db'] = str(self.dataloaders[_db_ii]) return sample def __len__(self): return len(self.cat_list) def __str__(self): include_db = [str(db) for db in self.dataloaders] exclude_db = [str(db) for db in self.excluded] return 'Included datasets:'+str(include_db)+'\n'+'Excluded datasets:'+str(exclude_db) if __name__ == "__main__": import matplotlib.pyplot as plt from dataloaders.datasets import pascal, sbd from dataloaders import sbd import torch import numpy as np from dataloaders.dataloader_utils import decode_segmap import argparse parser = argparse.ArgumentParser() args = parser.parse_args() args.base_size = 513 args.crop_size = 513 pascal_voc_val = pascal.VOCSegmentation(args, split='val') sbd = sbd.SBDSegmentation(args, split=['train', 'val']) pascal_voc_train = pascal.VOCSegmentation(args, split='train') dataset = CombineDBs([pascal_voc_train, sbd], excluded=[pascal_voc_val]) dataloader = torch.utils.data.DataLoader(dataset, batch_size=2, shuffle=True, num_workers=0) for ii, sample in enumerate(dataloader): for jj in range(sample["image"].size()[0]): img = sample['image'].numpy() gt = sample['label'].numpy() tmp = np.array(gt[jj]).astype(np.uint8) segmap = decode_segmap(tmp, dataset='pascal') img_tmp = np.transpose(img[jj], axes=[1, 2, 0]) img_tmp *= (0.229, 0.224, 0.225) img_tmp += (0.485, 0.456, 0.406) img_tmp *= 255.0 img_tmp = img_tmp.astype(np.uint8) plt.figure() plt.title('display') plt.subplot(211) plt.imshow(img_tmp) plt.subplot(212) plt.imshow(segmap) if ii == 1: break plt.show(block=True)
Cream/CDARTS/CDARTS_segmentation/dataloaders/datasets/combine_dbs.py/0
{ "file_path": "Cream/CDARTS/CDARTS_segmentation/dataloaders/datasets/combine_dbs.py", "repo_id": "Cream", "token_count": 1685 }
281
from .default import _C as config from .default import update_config seg_config = config update_seg_config = update_config
Cream/CDARTS/CDARTS_segmentation/segmentation/config/__init__.py/0
{ "file_path": "Cream/CDARTS/CDARTS_segmentation/segmentation/config/__init__.py", "repo_id": "Cream", "token_count": 34 }
282
from .aspp import ASPP from .deeplabv3 import DeepLabV3Decoder from .deeplabv3plus import DeepLabV3PlusDecoder from .panoptic_deeplab import PanopticDeepLabDecoder
Cream/CDARTS/CDARTS_segmentation/segmentation/model/decoder/__init__.py/0
{ "file_path": "Cream/CDARTS/CDARTS_segmentation/segmentation/model/decoder/__init__.py", "repo_id": "Cream", "token_count": 61 }
283
# ------------------------------------------------------------------------------ # Post-processing to get semantic segmentation results. # Written by Bowen Cheng ([email protected]) # ------------------------------------------------------------------------------ import torch __all__ = ['get_semantic_segmentation'] def get_semantic_segmentation(sem): """ Post-processing for semantic segmentation branch. Arguments: sem: A Tensor of shape [N, C, H, W], where N is the batch size, for consistent, we only support N=1. Returns: A Tensor of shape [1, H, W] (to be gathered by distributed data parallel). Raises: ValueError, if batch size is not 1. """ if sem.size(0) != 1: raise ValueError('Only supports inference for batch size = 1') sem = sem.squeeze(0) return torch.argmax(sem, dim=0, keepdim=True)
Cream/CDARTS/CDARTS_segmentation/segmentation/model/post_processing/semantic_post_processing.py/0
{ "file_path": "Cream/CDARTS/CDARTS_segmentation/segmentation/model/post_processing/semantic_post_processing.py", "repo_id": "Cream", "token_count": 284 }
284
from .cityscapes import Cityscapes from .bdd import BDD from .coco import COCO from .camvid import CamVid __all__ = ['Cityscapes', 'BDD', 'CamVid', 'COCO']
Cream/CDARTS/CDARTS_segmentation/tools/datasets/__init__.py/0
{ "file_path": "Cream/CDARTS/CDARTS_segmentation/tools/datasets/__init__.py", "repo_id": "Cream", "token_count": 61 }
285
from collections import namedtuple Genotype = namedtuple('Genotype', 'normal normal_concat reduce reduce_concat') PRIMITIVES = [ 'skip', 'conv', 'conv_downup', 'conv_2x_downup', 'sa', ] # 'conv_2x',
Cream/CDARTS/CDARTS_segmentation/train/genotypes.py/0
{ "file_path": "Cream/CDARTS/CDARTS_segmentation/train/genotypes.py", "repo_id": "Cream", "token_count": 94 }
286
## Environment Setup Tesla V100, CUDA10.0, linux 16.04, pytorch>=1.2, python3, [apex](https://github.com/NVIDIA/apex) ### Data Preparation * [Cifar-10](https://www.cs.toronto.edu/~kriz/cifar.html) * [Cifar-100](https://www.cs.toronto.edu/~kriz/cifar.html) * [ImageNet-2012](http://www.image-net.org/) Create soft link in main dir. ``` ln -s $DataLocation experiments/data ``` In ${ROOT}/experiments/data, it should be like this. ``` experiments/data/imagenet/train experiments/data/imagenet/val ... ``` ### Installation * First, you should install graphviz. ``` apt-get install graphviz ``` * Install python requirements. ```buildoutcfg pip install -r requirements ``` * Then you should install apex. ```buildoutcfg git clone https://github.com/NVIDIA/apex cd apex python setup.py install --cpp_ext --cuda_ext ``` ### Search, Retrain and Evaluation We have provided all the shell scripts and the corresponding default parameters, which are stored in the scripts folder. * For example: ```buildoutcfg cd ${CODE_ROOT} bash CyDAS/scripts/run_search_cifar_1gpu.sh bash CyDAS/scripts/run_retrain_cifar_1gpu.sh ... ``` #### Search * Main python file is ```buildoutcfg ${ROOT}/CyDAS/search.py ``` * Followings are options during training. ```buildoutcfg --regular # whether to use regular --regular_ratio # if use regular, the ragular ratio --regular_coeff # if use regular, the regular coefficient --ensemble_param # Ensemble different layer features --loss_alpha # the loss coefficient --w_lr # the learning rate of the search network --alpha_lr # the learning rate of the architecture parameters --nasnet_lr # the learning rate of the evaluation network --w_weight_decay # the weight decay the search and the evaluation network --alpha_weight_decay # the weight decay the the architecture parameters --fix_head # wheter to fix the parameters of auxiliary heads --interactive_type # The KD function, 0 kl, 1 cosine, 2 mse, 3 sl1 --pretrain_epochs # the pretrain epochs of the search network --search_iter # the search iterations --search_iter_epochs # the epochs in each search iteration --nasnet_warmup # the epochs used to train a new evaluation network ``` * Here we present our search scripts on CIFAR and ImageNet. ```buildoutcfg bash CyDAS/scripts/run_search_cifar_1gpu.sh bash CyDAS/scripts/run_search_cifar_4gpus.sh bash CyDAS/scripts/run_search_imagenet.sh ``` * Modify the following settings in `run_search_cifar_1gpu.sh` and `run_search_cifar_4gpus.sh` to search on CIFAR100. ``` --dataset cifar100 --n_classes 100 ``` #### Retrain * Main python file is ```buildoutcfg ${ROOT}/CyDAS/retrain.py ``` * We have provided all cell genotypes of Cifar and ImageNet in ```buildoutcfg ${ROOT}/CyDAS/cells/cifar_genotypes.json ... ``` * Followings are options during training. ```buildoutcfg --cell_file # path of cell genotype --weight_decay # decay of W in the Retrain-Phase --lr # learning rate of W in the Retrain-Phase --warmup_epochs # warmup epochs --epochs # total retrain epochs --cutout_length # cutout length for cifar --aux_weight # weight of auxiliary loss, 0.4 is the best option --drop_path_prob # used for dropping path in NAS --label_smooth # label smooth ratio ``` * Here we present our train scripts on CIFAR and ImageNet. ```buildoutcfg bash CyDAS/scripts/run_retrain_cifar_1gpu.sh bash CyDAS/scripts/run_retrain_cifar_4gpus.sh bash CyDAS/scripts/run_retrain_imagenet.sh ``` * Modify the following settings in `run_retrain_cifar.sh` to train CIFAR100. ``` --dataset cifar100 --n_classes 100 ``` #### Evaluation * Main python file is ```buildoutcfg ${ROOT}/CyDAS/test.py ``` * Followings are options during testing. ```buildoutcfg --resume # whether to load checkpint --resume_name # checkpint name ``` * Here we present our test scripts on CIFAR and ImageNet. ```buildoutcfg bash CyDAS/scripts/run_test_cifar.sh bash CyDAS/scripts/run_test_imagenet.sh ``` * Modify the following settings in `run_test_cifar.sh` to test CIFAR100. ``` --dataset cifar100 --n_classes 100 ```
Cream/CDARTS/SETUP.md/0
{ "file_path": "Cream/CDARTS/SETUP.md", "repo_id": "Cream", "token_count": 2025 }
287
""" CNN cell for architecture search """ import torch import torch.nn as nn from copy import deepcopy from models.ops import ResNetBasicblock, OPS, NAS_BENCH_201 from utils.genotypes import Structure # This module is used for NAS-Bench-201, represents a small search space with a complete DAG class SearchCell(nn.Module): def __init__(self, C_in, C_out, stride, max_nodes, op_names, affine=False, track_running_stats=True): super(SearchCell, self).__init__() self.op_names = deepcopy(op_names) self.edges = nn.ModuleDict() self.max_nodes = max_nodes self.in_dim = C_in self.out_dim = C_out for i in range(1, max_nodes): for j in range(i): node_str = '{:}<-{:}'.format(i, j) if j == 0: xlists = [OPS[op_name](C_in , C_out, stride, affine, track_running_stats) for op_name in op_names] else: xlists = [OPS[op_name](C_in , C_out, 1, affine, track_running_stats) for op_name in op_names] self.edges[ node_str ] = nn.ModuleList( xlists ) self.edge_keys = sorted(list(self.edges.keys())) self.edge2index = {key:i for i, key in enumerate(self.edge_keys)} self.num_edges = len(self.edges) def extra_repr(self): string = 'info :: {max_nodes} nodes, inC={in_dim}, outC={out_dim}'.format(**self.__dict__) return string def forward(self, inputs, weightss): nodes = [inputs] for i in range(1, self.max_nodes): inter_nodes = [] for j in range(i): node_str = '{:}<-{:}'.format(i, j) weights = weightss[ self.edge2index[node_str] ] inter_nodes.append( sum( layer(nodes[j]) * w for layer, w in zip(self.edges[node_str], weights) ) ) nodes.append( sum(inter_nodes) ) return nodes[-1] # GDAS def forward_gdas(self, inputs, hardwts, index): nodes = [inputs] for i in range(1, self.max_nodes): inter_nodes = [] for j in range(i): node_str = '{:}<-{:}'.format(i, j) weights = hardwts[ self.edge2index[node_str] ] argmaxs = index[ self.edge2index[node_str] ].item() weigsum = sum( weights[_ie] * edge(nodes[j]) if _ie == argmaxs else weights[_ie] for _ie, edge in enumerate(self.edges[node_str]) ) inter_nodes.append( weigsum ) nodes.append( sum(inter_nodes) ) return nodes[-1] # joint def forward_joint(self, inputs, weightss): nodes = [inputs] for i in range(1, self.max_nodes): inter_nodes = [] for j in range(i): node_str = '{:}<-{:}'.format(i, j) weights = weightss[ self.edge2index[node_str] ] #aggregation = sum( layer(nodes[j]) * w for layer, w in zip(self.edges[node_str], weights) ) / weights.numel() aggregation = sum( layer(nodes[j]) * w for layer, w in zip(self.edges[node_str], weights) ) inter_nodes.append( aggregation ) nodes.append( sum(inter_nodes) ) return nodes[-1] # uniform random sampling per iteration, SETN def forward_urs(self, inputs): nodes = [inputs] for i in range(1, self.max_nodes): while True: # to avoid select zero for all ops sops, has_non_zero = [], False for j in range(i): node_str = '{:}<-{:}'.format(i, j) candidates = self.edges[node_str] select_op = random.choice(candidates) sops.append( select_op ) if not hasattr(select_op, 'is_zero') or select_op.is_zero is False: has_non_zero=True if has_non_zero: break inter_nodes = [] for j, select_op in enumerate(sops): inter_nodes.append( select_op(nodes[j]) ) nodes.append( sum(inter_nodes) ) return nodes[-1] # select the argmax def forward_select(self, inputs, weightss): nodes = [inputs] for i in range(1, self.max_nodes): inter_nodes = [] for j in range(i): node_str = '{:}<-{:}'.format(i, j) weights = weightss[ self.edge2index[node_str] ] inter_nodes.append( self.edges[node_str][ weights.argmax().item() ]( nodes[j] ) ) #inter_nodes.append( sum( layer(nodes[j]) * w for layer, w in zip(self.edges[node_str], weights) ) ) nodes.append( sum(inter_nodes) ) return nodes[-1] # forward with a specific structure def forward_dynamic(self, inputs, structure): nodes = [inputs] for i in range(1, self.max_nodes): cur_op_node = structure.nodes[i-1] inter_nodes = [] for op_name, j in cur_op_node: node_str = '{:}<-{:}'.format(i, j) op_index = self.op_names.index( op_name ) inter_nodes.append( self.edges[node_str][op_index]( nodes[j] ) ) nodes.append( sum(inter_nodes) ) return nodes[-1]
Cream/CDARTS/benchmark201/models/search_cells.py/0
{ "file_path": "Cream/CDARTS/benchmark201/models/search_cells.py", "repo_id": "Cream", "token_count": 2072 }
288
import torch import torch.nn as nn from lib.utils import utils from lib.models.loss import Loss_interactive def search(train_loader, valid_loader, model, optimizer, w_optim, alpha_optim, layer_idx, epoch, writer, logger, config): # interactive retrain and kl device = torch.device("cuda") criterion = nn.CrossEntropyLoss().to(device) top1 = utils.AverageMeter() top5 = utils.AverageMeter() losses = utils.AverageMeter() losses_interactive = utils.AverageMeter() losses_cls = utils.AverageMeter() losses_reg = utils.AverageMeter() step_num = len(train_loader) step_num = int(step_num * config.sample_ratio) cur_step = epoch*step_num cur_lr_search = w_optim.param_groups[0]['lr'] cur_lr_main = optimizer.param_groups[0]['lr'] if config.local_rank == 0: logger.info("Train Epoch {} Search LR {}".format(epoch, cur_lr_search)) logger.info("Train Epoch {} Main LR {}".format(epoch, cur_lr_main)) writer.add_scalar('retrain/lr', cur_lr_search, cur_step) model.train() for step, ((trn_X, trn_y), (val_X, val_y)) in enumerate(zip(train_loader, valid_loader)): if step > step_num: break trn_X, trn_y = trn_X.to(device, non_blocking=True), trn_y.to(device, non_blocking=True) val_X, val_y = val_X.to(device, non_blocking=True), val_y.to(device, non_blocking=True) N = trn_X.size(0) #use valid data alpha_optim.zero_grad() optimizer.zero_grad() logits_search, emsemble_logits_search = model(val_X, layer_idx, super_flag=True) logits_main, emsemble_logits_main= model(val_X, layer_idx, super_flag=False) loss_cls = (criterion(logits_search, val_y) + criterion(logits_main, val_y)) / config.loss_alpha loss_interactive = Loss_interactive(emsemble_logits_search, emsemble_logits_main, config.loss_T, config.interactive_type) * config.loss_alpha loss_regular = 0 * loss_cls if config.regular: reg_decay = max(config.regular_coeff * (1 - float(epoch-config.pretrain_epochs)/((config.search_iter-config.pretrain_epochs)*config.search_iter_epochs*config.regular_ratio)), 0) # normal cell op_opt = ['max_pool_3x3', 'avg_pool_3x3', 'skip_connect'] op_groups = [] for idx in range(layer_idx, 3): for op_dx in op_opt: op_groups.append((idx - layer_idx, op_dx)) loss_regular = loss_regular + model.module.add_alpha_regularization(op_groups, weight_decay=reg_decay, method='L1', reduce=False) # reduction cell # op_opt = [] op_opt = ['max_pool_3x3', 'avg_pool_3x3', 'skip_connect'] op_groups = [] for i in range(layer_idx, 3): for op_dx in op_opt: op_groups.append((i - layer_idx, op_dx)) loss_regular = loss_regular + model.module.add_alpha_regularization(op_groups, weight_decay=reg_decay, method='L1', normal=False) loss = loss_cls + loss_interactive + loss_regular loss.backward() nn.utils.clip_grad_norm_(model.module.parameters(), config.w_grad_clip) optimizer.step() alpha_optim.step() prec1, prec5 = utils.accuracy(logits_main, val_y, topk=(1, 5)) if config.distributed: reduced_loss = utils.reduce_tensor(loss.data, config.world_size) reduced_loss_interactive = utils.reduce_tensor(loss_interactive.data, config.world_size) reduced_loss_cls = utils.reduce_tensor(loss_cls.data, config.world_size) reduced_loss_reg = utils.reduce_tensor(loss_regular.data, config.world_size) prec1 = utils.reduce_tensor(prec1, config.world_size) prec5 = utils.reduce_tensor(prec5, config.world_size) else: reduced_loss = loss.data reduced_loss_interactive = loss_interactive.data reduced_loss_cls = loss_cls.data reduced_loss_reg = loss_regular.data losses.update(reduced_loss.item(), N) losses_interactive.update(reduced_loss_interactive.item(), N) losses_cls.update(reduced_loss_cls.item(), N) losses_reg.update(reduced_loss_reg.item(), N) top1.update(prec1.item(), N) top5.update(prec5.item(), N) torch.cuda.synchronize() if config.local_rank == 0 and (step % config.print_freq == 0 or step == step_num): logger.info( "Train_2: Layer {}/{} Epoch {:2d}/{} Step {:03d}/{:03d} Loss {losses.avg:.3f} " "Loss_interactive {losses_interactive.avg:.3f} Losses_cls {losses_cls.avg:.3f} Losses_reg {losses_reg.avg:.3f} " "Prec@(1,5) ({top1.avg:.1%}, {top5.avg:.1%})".format( layer_idx+1, config.layer_num, epoch+1, config.search_iter*config.search_iter_epochs, step, step_num, losses=losses, losses_interactive=losses_interactive, losses_cls=losses_cls, losses_reg=losses_reg, top1=top1, top5=top5)) if config.local_rank == 0: writer.add_scalar('retrain/loss', reduced_loss.item(), cur_step) writer.add_scalar('retrain/top1', prec1.item(), cur_step) writer.add_scalar('retrain/top5', prec5.item(), cur_step) cur_step += 1 w_optim.zero_grad() logits_search_train, _ = model(trn_X, layer_idx, super_flag=True) loss_cls_train = criterion(logits_search_train, trn_y) loss_train = loss_cls_train loss_train.backward() # gradient clipping nn.utils.clip_grad_norm_(model.module.parameters(), config.w_grad_clip) # only update w w_optim.step() # alpha_optim.step() if config.distributed: reduced_loss_cls_train = utils.reduce_tensor(loss_cls_train.data, config.world_size) reduced_loss_train = utils.reduce_tensor(loss_train.data, config.world_size) else: reduced_loss_cls_train = reduced_loss_cls_train.data reduced_loss_train = reduced_loss_train.data if config.local_rank == 0 and (step % config.print_freq == 0 or step == step_num-1): logger.info( "Train_1: Loss_cls: {:.3f} Loss: {:.3f}".format( reduced_loss_cls_train.item(), reduced_loss_train.item()) ) if config.local_rank == 0: logger.info("Train_2: Layer {}/{} Epoch {:2d}/{} Final Prec@1 {:.4%}".format( layer_idx+1, config.layer_num, epoch+1, config.search_iter*config.search_iter_epochs, top1.avg)) def retrain_warmup(valid_loader, model, optimizer, layer_idx, epoch, writer, logger, super_flag, retrain_epochs, config): device = torch.device("cuda") criterion = nn.CrossEntropyLoss().to(device) top1 = utils.AverageMeter() top5 = utils.AverageMeter() losses = utils.AverageMeter() step_num = len(valid_loader) step_num = int(step_num * config.sample_ratio) cur_step = epoch*step_num cur_lr = optimizer.param_groups[0]['lr'] if config.local_rank == 0: logger.info("Warmup Epoch {} LR {:.3f}".format(epoch+1, cur_lr)) writer.add_scalar('warmup/lr', cur_lr, cur_step) model.train() for step, (val_X, val_y) in enumerate(valid_loader): if step > step_num: break val_X, val_y = val_X.to(device, non_blocking=True), val_y.to(device, non_blocking=True) N = val_X.size(0) optimizer.zero_grad() logits_main, _ = model(val_X, layer_idx, super_flag=super_flag) loss = criterion(logits_main, val_y) loss.backward() nn.utils.clip_grad_norm_(model.module.parameters(), config.w_grad_clip) optimizer.step() prec1, prec5 = utils.accuracy(logits_main, val_y, topk=(1, 5)) if config.distributed: reduced_loss = utils.reduce_tensor(loss.data, config.world_size) prec1 = utils.reduce_tensor(prec1, config.world_size) prec5 = utils.reduce_tensor(prec5, config.world_size) else: reduced_loss = loss.data losses.update(reduced_loss.item(), N) top1.update(prec1.item(), N) top5.update(prec5.item(), N) torch.cuda.synchronize() if config.local_rank == 0 and (step % config.print_freq == 0 or step == step_num): logger.info( "Warmup: Layer {}/{} Epoch {:2d}/{} Step {:03d}/{:03d} Loss {losses.avg:.3f} " "Prec@(1,5) ({top1.avg:.1%}, {top5.avg:.1%})".format( layer_idx+1, config.layer_num, epoch+1, retrain_epochs, step, step_num, losses=losses, top1=top1, top5=top5)) if config.local_rank == 0: writer.add_scalar('retrain/loss', reduced_loss.item(), cur_step) writer.add_scalar('retrain/top1', prec1.item(), cur_step) writer.add_scalar('retrain/top5', prec5.item(), cur_step) cur_step += 1 if config.local_rank == 0: logger.info("Warmup: Layer {}/{} Epoch {:2d}/{} Final Prec@1 {:.4%}".format( layer_idx+1, config.layer_num, epoch+1, retrain_epochs, top1.avg)) def validate(valid_loader, model, layer_idx, epoch, cur_step, writer, logger, super_flag, config): top1 = utils.AverageMeter() top5 = utils.AverageMeter() losses = utils.AverageMeter() model.eval() device = torch.device("cuda") criterion = nn.CrossEntropyLoss().to(device) with torch.no_grad(): for step, (X, y) in enumerate(valid_loader): X, y = X.to(device, non_blocking=True), y.to(device, non_blocking=True) N = X.size(0) logits, _ = model(X, layer_idx, super_flag=False) loss = criterion(logits, y) prec1, prec5 = utils.accuracy(logits, y, topk=(1, 5)) reduced_loss = loss.data losses.update(reduced_loss.item(), N) top1.update(prec1.item(), N) top5.update(prec5.item(), N) torch.cuda.synchronize() step_num = len(valid_loader) if (step % config.print_freq == 0 or step == step_num-1) and config.local_rank == 0: logger.info( "Valid: Layer {}/{} Epoch {:2d}/{} Step {:03d}/{:03d} Loss {losses.avg:.3f} " "Prec@(1,5) ({top1.avg:.1%}, {top5.avg:.1%})".format( layer_idx+1, config.layer_num, epoch+1, config.search_iter*config.search_iter_epochs, step, step_num, losses=losses, top1=top1, top5=top5)) if config.local_rank == 0: writer.add_scalar('val/loss', losses.avg, cur_step) writer.add_scalar('val/top1', top1.avg, cur_step) writer.add_scalar('val/top5', top5.avg, cur_step) logger.info("Valid: Layer {}/{} Epoch {:2d}/{} Final Prec@1 {:.4%}".format( layer_idx+1, config.layer_num, epoch+1, config.search_iter*config.search_iter_epochs, top1.avg)) return top1.avg
Cream/CDARTS/lib/core/search_function.py/0
{ "file_path": "Cream/CDARTS/lib/core/search_function.py", "repo_id": "Cream", "token_count": 5370 }
289
graphviz torch==1.2 torchvision==0.2 tensorboard tensorboardX
Cream/CDARTS/requirements/0
{ "file_path": "Cream/CDARTS/requirements", "repo_id": "Cream", "token_count": 27 }
290
AUTO_RESUME: False DATA_DIR: './data/imagenet' MODEL: '600m_retrain' RESUME_PATH: './experiments/workspace/retrain/resume.pth.tar' SAVE_PATH: './experiments/workspace/retrain' SEED: 42 LOG_INTERVAL: 50 RECOVERY_INTERVAL: 0 WORKERS: 4 NUM_GPU: 2 SAVE_IMAGES: False AMP: False OUTPUT: 'None' EVAL_METRICS: 'prec1' TTA: 0 LOCAL_RANK: 0 DATASET: NUM_CLASSES: 1000 IMAGE_SIZE: 224 # image patch size INTERPOLATION: 'random' # Image resize interpolation type BATCH_SIZE: 128 # batch size NO_PREFECHTER: False NET: GP: 'avg' DROPOUT_RATE: 0.0 SELECTION: 42 EMA: USE: True FORCE_CPU: False # force model ema to be tracked on CPU DECAY: 0.9998 OPT: 'rmsproptf' OPT_EPS: 1e-2 MOMENTUM: 0.9 DECAY_RATE: 0.1 SCHED: 'sgd' LR_NOISE_PCT: 0.67 LR_NOISE_STD: 1.0 WARMUP_LR: 1e-4 MIN_LR: 1e-5 EPOCHS: 200 START_EPOCH: None DECAY_EPOCHS: 30.0 WARMUP_EPOCHS: 3 COOLDOWN_EPOCHS: 10 PATIENCE_EPOCHS: 10 LR: 1e-2
Cream/Cream/experiments/configs/retrain/retrain.yaml/0
{ "file_path": "Cream/Cream/experiments/configs/retrain/retrain.yaml", "repo_id": "Cream", "token_count": 452 }
291
from copy import deepcopy from lib.utils.builder_util import modify_block_args from lib.models.blocks import get_Bottleneck, InvertedResidual from timm.models.efficientnet_blocks import * # SuperNet Builder definition. class SuperNetBuilder: """ Build Trunk Blocks """ def __init__( self, choices, channel_multiplier=1.0, channel_divisor=8, channel_min=None, output_stride=32, pad_type='', act_layer=None, se_kwargs=None, norm_layer=nn.BatchNorm2d, norm_kwargs=None, drop_path_rate=0., feature_location='', verbose=False, resunit=False, dil_conv=False, logger=None): # dict # choices = {'kernel_size': [3, 5, 7], 'exp_ratio': [4, 6]} self.choices = [[x, y] for x in choices['kernel_size'] for y in choices['exp_ratio']] self.choices_num = len(self.choices) - 1 self.channel_multiplier = channel_multiplier self.channel_divisor = channel_divisor self.channel_min = channel_min self.output_stride = output_stride self.pad_type = pad_type self.act_layer = act_layer self.se_kwargs = se_kwargs self.norm_layer = norm_layer self.norm_kwargs = norm_kwargs self.drop_path_rate = drop_path_rate self.feature_location = feature_location assert feature_location in ('pre_pwl', 'post_exp', '') self.verbose = verbose self.resunit = resunit self.dil_conv = dil_conv self.logger = logger # state updated during build, consumed by model self.in_chs = None def _round_channels(self, chs): return round_channels( chs, self.channel_multiplier, self.channel_divisor, self.channel_min) def _make_block( self, ba, choice_idx, block_idx, block_count, resunit=False, dil_conv=False): drop_path_rate = self.drop_path_rate * block_idx / block_count bt = ba.pop('block_type') ba['in_chs'] = self.in_chs ba['out_chs'] = self._round_channels(ba['out_chs']) if 'fake_in_chs' in ba and ba['fake_in_chs']: # FIXME this is a hack to work around mismatch in origin impl input # filters ba['fake_in_chs'] = self._round_channels(ba['fake_in_chs']) ba['norm_layer'] = self.norm_layer ba['norm_kwargs'] = self.norm_kwargs ba['pad_type'] = self.pad_type # block act fn overrides the model default ba['act_layer'] = ba['act_layer'] if ba['act_layer'] is not None else self.act_layer assert ba['act_layer'] is not None if bt == 'ir': ba['drop_path_rate'] = drop_path_rate ba['se_kwargs'] = self.se_kwargs if self.verbose: self.logger.info( ' InvertedResidual {}, Args: {}'.format( block_idx, str(ba))) block = InvertedResidual(**ba) elif bt == 'ds' or bt == 'dsa': ba['drop_path_rate'] = drop_path_rate ba['se_kwargs'] = self.se_kwargs if self.verbose: self.logger.info( ' DepthwiseSeparable {}, Args: {}'.format( block_idx, str(ba))) block = DepthwiseSeparableConv(**ba) elif bt == 'cn': if self.verbose: self.logger.info( ' ConvBnAct {}, Args: {}'.format( block_idx, str(ba))) block = ConvBnAct(**ba) else: assert False, 'Uknkown block type (%s) while building model.' % bt if choice_idx == self.choice_num - 1: self.in_chs = ba['out_chs'] # update in_chs for arg of next block return block def __call__(self, in_chs, model_block_args): """ Build the blocks Args: in_chs: Number of input-channels passed to first block model_block_args: A list of lists, outer list defines stages, inner list contains strings defining block configuration(s) Return: List of block stacks (each stack wrapped in nn.Sequential) """ if self.verbose: self.logger.info( 'Building model trunk with %d stages...' % len(model_block_args)) self.in_chs = in_chs total_block_count = sum([len(x) for x in model_block_args]) total_block_idx = 0 current_stride = 2 current_dilation = 1 feature_idx = 0 stages = nn.ModuleList() # outer list of block_args defines the stacks ('stages' by some # conventions) for stage_idx, stage_block_args in enumerate(model_block_args): last_stack = stage_idx == (len(model_block_args) - 1) if self.verbose: self.logger.info('Stack: {}'.format(stage_idx)) assert isinstance(stage_block_args, list) blocks = nn.ModuleList() # each stack (stage) contains a list of block arguments for block_idx, block_args in enumerate(stage_block_args): last_block = block_idx == (len(stage_block_args) - 1) if self.verbose: self.logger.info(' Block: {}'.format(block_idx)) # Sort out stride, dilation, and feature extraction details assert block_args['stride'] in (1, 2) if block_idx >= 1: # only the first block in any stack can have a stride > 1 block_args['stride'] = 1 next_dilation = current_dilation if block_args['stride'] > 1: next_output_stride = current_stride * block_args['stride'] if next_output_stride > self.output_stride: next_dilation = current_dilation * block_args['stride'] block_args['stride'] = 1 if self.verbose: self.logger.info( ' Converting stride to dilation to maintain output_stride=={}'.format( self.output_stride)) else: current_stride = next_output_stride block_args['dilation'] = current_dilation if next_dilation != current_dilation: current_dilation = next_dilation if stage_idx == 0 or stage_idx == 6: self.choice_num = 1 else: self.choice_num = len(self.choices) if self.dil_conv: self.choice_num += 2 choice_blocks = nn.ModuleList() block_args_copy = deepcopy(block_args) if self.choice_num == 1: # create the block block = self._make_block( block_args, 0, total_block_idx, total_block_count) choice_blocks.append(block) else: for choice_idx, choice in enumerate(self.choices): # create the block block_args = deepcopy(block_args_copy) block_args = modify_block_args( block_args, choice[0], choice[1]) block = self._make_block( block_args, choice_idx, total_block_idx, total_block_count) choice_blocks.append(block) if self.dil_conv: block_args = deepcopy(block_args_copy) block_args = modify_block_args(block_args, 3, 0) block = self._make_block( block_args, self.choice_num - 2, total_block_idx, total_block_count, resunit=self.resunit, dil_conv=self.dil_conv) choice_blocks.append(block) block_args = deepcopy(block_args_copy) block_args = modify_block_args(block_args, 5, 0) block = self._make_block( block_args, self.choice_num - 1, total_block_idx, total_block_count, resunit=self.resunit, dil_conv=self.dil_conv) choice_blocks.append(block) if self.resunit: block = get_Bottleneck(block.conv_pw.in_channels, block.conv_pwl.out_channels, block.conv_dw.stride[0]) choice_blocks.append(block) blocks.append(choice_blocks) # incr global block idx (across all stacks) total_block_idx += 1 stages.append(blocks) return stages
Cream/Cream/lib/models/builders/build_supernet.py/0
{ "file_path": "Cream/Cream/lib/models/builders/build_supernet.py", "repo_id": "Cream", "token_count": 5205 }
292
# model settings model = dict( type='CascadeRCNN', pretrained=None, backbone=dict( type='SwinTransformer', embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0.2, ape=False, patch_norm=True, out_indices=(0, 1, 2, 3), use_checkpoint=False), neck=dict( type='FPN', in_channels=[96, 192, 384, 768], out_channels=256, num_outs=5), rpn_head=dict( type='RPNHead', in_channels=256, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', scales=[8], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[1.0, 1.0, 1.0, 1.0]), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0)), roi_head=dict( type='CascadeRoIHead', num_stages=3, stage_loss_weights=[1, 0.5, 0.25], bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=[ dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.05, 0.05, 0.1, 0.1]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.033, 0.033, 0.067, 0.067]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)) ], mask_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), mask_head=dict( type='FCNMaskHead', num_convs=4, in_channels=256, conv_out_channels=256, num_classes=80, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0))), # model training and testing settings train_cfg = dict( rpn=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, match_low_quality=True, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), allowed_border=0, pos_weight=-1, debug=False), rpn_proposal=dict( nms_across_levels=False, nms_pre=2000, nms_post=2000, max_per_img=2000, nms=dict(type='nms', iou_threshold=0.7), min_bbox_size=0), rcnn=[ dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0.5, match_low_quality=False, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), mask_size=28, pos_weight=-1, debug=False), dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.6, neg_iou_thr=0.6, min_pos_iou=0.6, match_low_quality=False, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), mask_size=28, pos_weight=-1, debug=False), dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.7, min_pos_iou=0.7, match_low_quality=False, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), mask_size=28, pos_weight=-1, debug=False) ]), test_cfg = dict( rpn=dict( nms_across_levels=False, nms_pre=1000, nms_post=1000, max_per_img=1000, nms=dict(type='nms', iou_threshold=0.7), min_bbox_size=0), rcnn=dict( score_thr=0.05, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100, mask_thr_binary=0.5)))
Cream/EfficientViT/downstream/configs/_base_/models/cascade_mask_rcnn_swin_fpn.py/0
{ "file_path": "Cream/EfficientViT/downstream/configs/_base_/models/cascade_mask_rcnn_swin_fpn.py", "repo_id": "Cream", "token_count": 4748 }
293