code stringlengths 101 5.91M |
|---|
def embed(params, data, policy, states, k=100):
if (params['embedding'] == 'a_s'):
embedding = np.concatenate([policy.forward(x, eval=False) for x in states], axis=0)
return embedding |
class Conv2dIndepNormal(_DeepIndepNormal):
def __init__(self, backbone: nn.Module, hidden_channels: List[int], out_channels: int=1, logstd_ref: float=(- 5.0), **kwargs):
super().__init__(backbone=backbone, mean_head=_create_head(hidden_channels, out_channels, **kwargs), logstd_head=_create_head(hidden_chann... |
_task('dummy_masked_lm')
class DummyMaskedLMTask(FairseqTask):
def add_args(parser):
parser.add_argument('--dict-size', default=50000, type=int)
parser.add_argument('--dataset-size', default=100000, type=int)
parser.add_argument('--tokens-per-sample', default=512, type=int, help='max number ... |
def binary_surprise(x: Union[(float, ArrayLike)], expected_mean: Union[(float, ArrayLike)]) -> ArrayLike:
return jnp.where(x, (- jnp.log(expected_mean)), (- jnp.log((jnp.array(1.0) - expected_mean)))) |
def test_sudoku_animation(sudoku_env: Sudoku, mocker: pytest_mock.MockerFixture) -> None:
states = mocker.MagicMock()
animation = sudoku_env.animate(states)
assert isinstance(animation, matplotlib.animation.Animation) |
def rearrange(csv_file_path, mode=''):
(title, data) = load_csv(((os.getcwd() + os.sep) + csv_file_path))
title.insert(2, title.pop(0))
for i in range(len(data)):
data[i].insert(2, data[i].pop(0))
data = sorted(data, key=functools.cmp_to_key(sort_by_time_stamp))
csv_file_name = csv_file_path... |
class TestGatesOnWireSlice(QiskitTestCase):
def test_wire_slice(self):
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(slice(0, 2))
expected = QuantumCircuit(qreg)
expected.h(qreg[0:2])
self.assertEqual(circuit, expected)
def test_wire_list(self... |
class Accumulator(object):
def Set(self, y):
if (type(self) == type(y)):
(self._s, self._t) = (y._s, y._t)
else:
(self._s, self._t) = (float(y), 0.0)
def __init__(self, y=0.0):
self.Set(y)
def Add(self, y):
(y, u) = Math.sum(y, self._t)
(self._... |
def main(cfg):
if (cfg.SEED_VALUE >= 0):
print(f'Seed value for the experiment {cfg.SEED_VALUE}')
os.environ['PYTHONHASHSEED'] = str(cfg.SEED_VALUE)
random.seed(cfg.SEED_VALUE)
torch.manual_seed(cfg.SEED_VALUE)
np.random.seed(cfg.SEED_VALUE)
logger = create_logger(cfg.LOG... |
def check_spherical_symmetry(samp, l, m, tol):
(thetas, phis) = (numpy.arctan2(samp.R(), samp.z()), samp.phi())
assert (numpy.fabs(((numpy.sum((special.lpmv(m, l, numpy.cos(thetas)) * numpy.cos((m * phis)))) / samp.size) - ((l == 0) * (m == 0)))) < tol), f'Sample does not appear to be spherically symmetric, fai... |
def df_to_loader(df: pd.DataFrame, batch_size: int=128, line_graph: bool=True, pin_memory: bool=False, shuffle: bool=True, **kwargs: Any) -> DataLoader:
graphs = load_graphs(df, neighbor_strategy=config.neighbor_strategy, use_canonize=config.use_canonize)
dataset = StructureDataset(df.reset_index(drop=True), gr... |
def dice_coef_metric(pred, label):
pred[(pred >= 0.5)] = 1.0
pred[(pred < 0.5)] = 0.0
intersection = (2.0 * (pred * label).sum())
union = (pred.sum() + label.sum())
if ((pred.sum() == 0) and (label.sum() == 0)):
return 1.0
return (intersection / union) |
class ConfigGenerator():
def __init__(self):
self.p_list = []
for func in dir(self):
if hasattr(getattr(self, func), '__name__'):
if getattr(self, func).__name__.startswith(TRIGGER_REG_NAME_PREFIX):
p = Thread(target=getattr(self, func), args=(), daemo... |
def dangling_context(is_dangling: bool=True) -> Generator[(None, None, None)]:
token = dangling_ctx_var.set((is_dangling or dangling_ctx_var.get()))
try:
(yield)
finally:
dangling_ctx_var.reset(token) |
def _build_regularizer(regularizer):
regularizer_oneof = regularizer.WhichOneof('regularizer_oneof')
if (regularizer_oneof == 'l1_regularizer'):
return slim.l1_regularizer(scale=float(regularizer.l1_regularizer.weight))
if (regularizer_oneof == 'l2_regularizer'):
return slim.l2_regularizer(s... |
class FairseqEncoderModel(BaseFairseqModel):
def __init__(self, encoder):
super().__init__()
self.encoder = encoder
check_type(self.encoder, FairseqEncoder)
def forward(self, src_tokens, src_lengths, **kwargs):
return self.encoder(src_tokens, src_lengths, **kwargs)
def get_no... |
def mctsLoop(env, policies, seed, save, animate, **kwargs):
if (seed is not None):
world_id = int(seed)
else:
world_id = np.random.randint(10000)
np.random.seed(world_id)
env.reset()
world = env._world
current_root = Node(world=world)
done = current_root.terminal
if (poli... |
_subclass('projected_sgd')
class ProjSGD(Inference):
def __init__(self, model, loader, criterion, epochs=10, **kwargs):
super(ProjSGD, self).__init__()
self.kwargs = kwargs
self.optimizer = None
self.epochs = epochs
(self.mean, self.var, self.subspace) = (None, None, None)
... |
def MakeDir(dir):
try:
os.mkdir(dir)
except OSError as exc:
if (exc.errno != errno.EEXIST):
raise exc
raise Exception('Directory {0} already exists'.format(dir))
pass |
class FineTuneTrainer(SemiTrainer):
activate_hooks = False
def train_epocher(self) -> Type[EpocherBase]:
return FineTuneEpocher |
class Attribute_Embedding(nn.Module):
def __init__(self, d_model, attribute_vocab_size):
super().__init__()
self.embed = nn.Linear(attribute_vocab_size, d_model)
self.norm = nn.BatchNorm1d(attribute_vocab_size, momentum=0.01)
def forward(self, attribute):
attribute = self.norm(at... |
class ConfigTester(unittest.TestCase):
def test_load_not_from_mixin(self):
with self.assertRaises(ValueError):
ConfigMixin.load_config('dummy_path')
def test_register_to_config(self):
obj = SampleObject()
config = obj.config
assert (config['a'] == 2)
assert (c... |
def resnet110_cifar100(num_classes=100, **kwargs):
return get_resnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False, model_name='resnet110_cifar100', **kwargs) |
class TestDARNTop(RWSTopLayerTest, unittest.TestCase):
def setUp(self):
self.n_samples = 10
self.layer = DARNTop(n_X=8)
self.layer.setup() |
def CheckAccess(filename, clean_lines, linenum, nesting_state, error):
line = clean_lines.elided[linenum]
matched = Match('\\s*(DISALLOW_COPY_AND_ASSIGN|DISALLOW_EVIL_CONSTRUCTORS|DISALLOW_IMPLICIT_CONSTRUCTORS)', line)
if (not matched):
return
if (nesting_state.stack and isinstance(nesting_stat... |
def cal_torsion_energy(m):
energy = 0
(torsion_list, torsion_list_ring) = CalculateTorsionLists(m)
angles = CalculateTorsionAngles(m, torsion_list, torsion_list_ring)
for (idx, t) in enumerate(torsion_list):
(indice, _) = t
(indice, angle) = (indice[0], angles[idx][0][0])
v = rdF... |
def dataset_registry(dataset_type, framework, dataset_format=''):
def decorator_dataset(cls):
for single_framework in [fwk.strip() for fwk in framework.split(',')]:
assert (single_framework in ['tensorflow', 'tensorflow_itex', 'mxnet', 'pytorch', 'pytorch_ipex', 'pytorch_fx', 'onnxrt_qlinearops'... |
class Transformer(base_converter.ConverterInterface):
def __init__(self, option, model, converter_info):
self._registered_transformers = {TransformerRule.TRANSFORM_FAKE_QUANTIZE: self.transform_fake_quantize, TransformerRule.REMOVE_USELESS_OP: self.remove_useless_op, TransformerRule.FOLD_DIV_BN: self.fold_d... |
def
if (status == 451):
return 'Unavailable_for_Legal_Reasons (451)'
if (not try_status(status)):
return ('Other Unexpected Status (%s)' % status)
return ('%s (%s)' % (str(HTTPStatus(status)).split('.')[1].title(), status)) |
def main(args, init_distributed=False):
utils.import_user_module(args)
assert ((args.max_tokens is not None) or (args.max_sentences is not None)), 'Must specify batch size either with --max-tokens or --max-sentences'
if (torch.cuda.is_available() and (not args.cpu)):
torch.cuda.set_device(args.devic... |
def get_paths(agent_name: str, args) -> dict:
dir = rospkg.RosPack().get_path('arena_local_planner_drl')
PATHS = {'model': os.path.join(dir, 'agents', agent_name), 'tb': os.path.join(dir, 'training_logs', 'tensorboard', agent_name), 'eval': os.path.join(dir, 'training_logs', 'train_eval_log', agent_name), 'robo... |
class CFooterNode(Node):
__instance: CFooterNode = None
def instance() -> CFooterNode:
return CFooterNode.__instance
snippet = '\n return;\n}}\n\n#ifdef CNN_TEST\n#include <stdio.h>\n#ifdef TIMING\n#include <ctime>\n#endif\n\nint main()\n{{\n int i, j, k, width, height, max_colour;\n unsign... |
def main(params):
model = build_model(params['model'])
post_process = build_post_process(params['post_process'])
pt = Predictor(model, post_process, params)
pt.predict() |
def iobes2bio(iobes_labels):
bio_labels = []
for label in iobes_labels:
if (label[0] == 'S'):
bio_labels.append(('B' + label[1:]))
elif (label[0] == 'E'):
bio_labels.append(('I' + label[1:]))
else:
bio_labels.append(label)
return bio_labels |
_sentencepiece
_tokenizers
class T5TokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = T5Tokenizer
rust_tokenizer_class = T5TokenizerFast
test_rust_tokenizer = True
def setUp(self):
super().setUp()
tokenizer = T5Tokenizer(SAMPLE_VOCAB)
tokenizer.save_pret... |
def get_globalso_net(worker, enc_net, ref_net, init_net_path=None):
net = get_net(enc_net, ref_net, init_net_path=init_net_path)
train_set = _verify_and_get_test_set(worker)
return GlobalSONet(net, train_set) |
class RetinaNetE2ETest(unittest.TestCase):
def setUp(self):
self.model = get_model_zoo('COCO-Detection/retinanet_R_50_FPN_1x.yaml')
def test_empty_data(self):
inst = [get_empty_instance(200, 250), get_empty_instance(200, 249)]
self.model.eval()
self.model([create_model_input(torc... |
def to_absolute_coordinates(boxlist, height, width, check_range=True, scope=None):
with tf.name_scope(scope, 'ToAbsoluteCoordinates'):
height = tf.cast(height, tf.float32)
width = tf.cast(width, tf.float32)
if check_range:
box_maximum = tf.reduce_max(boxlist.get())
ma... |
def read_file_list(filename):
file = open(filename)
data = file.read()
lines = data.replace(',', ' ').replace('\t', ' ').split('\n')
list = [[v.strip() for v in line.split(' ') if (v.strip() != '')] for line in lines if ((len(line) > 0) and (line[0] != '#'))]
list = [(float(l[0]), l[1:]) for l in li... |
class TestGuidedAnchorHead(TestCase):
def test_guided_anchor_head_loss(self):
s = 256
img_metas = [{'img_shape': (s, s), 'pad_shape': (s, s), 'scale_factor': (1, 1)}]
guided_anchor_head = GuidedAnchorHead(**guided_anchor_head_config)
feats = (torch.rand(1, 4, (s // stride[1]), (s // ... |
def look_for_implied_ibids(splitted_citations):
def look_for_journal(els):
for el in els:
if (el['type'] == 'JOURNAL'):
return True
return False
current_journal = None
for citation in splitted_citations:
if (current_journal and (not look_for_journal(citati... |
class MidasCore(nn.Module):
def __init__(self, midas, trainable=False, fetch_features=True, layer_names=('out_conv', 'l4_rn', 'r4', 'r3', 'r2', 'r1'), freeze_bn=False, keep_aspect_ratio=True, img_size=384, **kwargs):
super().__init__()
self.core = midas
self.output_channels = None
se... |
def gaussian_orthogonal_random_matrix(nb_rows, nb_columns, scaling=0, device=None):
nb_full_blocks = int((nb_rows / nb_columns))
block_list = []
for _ in range(nb_full_blocks):
q = orthogonal_matrix_chunk(nb_columns, device=device)
block_list.append(q)
remaining_rows = (nb_rows - (nb_ful... |
class Objective():
def initialize(cls, target_rate, alpha):
cls.softmax = torch.nn.Softmax(dim=1)
cls.target_rate = target_rate
cls.alpha = alpha
cls.eps = 1e-30
def weighted_cross_entropy(cls, correlation_matrix, easy_match, hard_match, batch):
loss_buf = correlation_mat... |
class MLP(nn.Module):
def __init__(self, params: ModelArgs):
super().__init__()
self.params = params
self.vocab_size = params.vocab_size
self.n_layers = params.n_layers
self.tok_embeddings = VocabParallelEmbedding(params.vocab_size, params.dim)
self.layers = torch.nn.... |
def get_data_from_batch(batch, w2i, act2i):
uttrs_list = [d[0] for d in batch]
dialog_maxlen = max([len(uttrs) for uttrs in uttrs_list])
uttr_maxlen = max([len(u) for uttrs in uttrs_list for u in uttrs])
uttr_var = make_word_vector(uttrs_list, w2i, dialog_maxlen, uttr_maxlen)
batch_labels = [d[1] fo... |
class MJVOPTION(Structure):
_fields_ = [('label', c_int), ('frame', c_int), ('geomgroup', (c_ubyte * 5)), ('sitegroup', (c_ubyte * 5)), ('flags', (c_ubyte * 18))] |
class Broadcast2D(Lambda):
def __init__(self, size):
Lambda.__init__(self, (lambda x: tf.tile(tf.expand_dims(tf.expand_dims(x, 2), 3), [1, 1, size, size]))) |
def find_unused_parameters(model: nn.Module, inputs: Any) -> List[str]:
assert model.training
for (_, prm) in model.named_parameters():
prm.grad = None
if isinstance(inputs, tuple):
losses = model(*inputs)
else:
losses = model(inputs)
if isinstance(losses, dict):
loss... |
def sample_rule_priority(preds):
pred_num = len(preds)
rule_num = random.randint(0, (4 * pred_num))
fact_num = random.randint(0, pred_num)
cache = set()
rules = []
for _ in range(0, rule_num):
rule = None
while True:
rule = sample_one_rule(preds)
rule_hash... |
class LeNet(MetaModule):
def __init__(self, n_out):
super(LeNet, self).__init__()
layers = []
layers.append(MetaConv2d(1, 6, kernel_size=5))
layers.append(nn.ReLU(inplace=True))
layers.append(nn.MaxPool2d(kernel_size=2, stride=2))
layers.append(MetaConv2d(6, 16, kerne... |
def load_remove_save(input_file: str, output_file: str, for_which_classes: list, minimum_valid_object_size: dict=None):
img_in = sitk.ReadImage(input_file)
img_npy = sitk.GetArrayFromImage(img_in)
volume_per_voxel = float(np.prod(img_in.GetSpacing(), dtype=np.float64))
(image, largest_removed, kept_size... |
class TPUDistributedDataParallel(nn.Module):
def __init__(self, module, process_group):
super().__init__()
self.module = module
self.process_group = process_group
self.world_size = utils.get_world_size(self.process_group)
def forward(self, *inputs, **kwargs):
return self.... |
class SplinterTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self, vocab_file, do_l... |
def setup_python(interval=1):
gpu_memory_list = get_info()
i = 2
while True:
if (gpu_memory_list[i] <= 10000):
if ((i == 2) or (i == 3)):
print(('\n' + cmd))
os.system(cmd)
gpu_memory_list = get_info()
else:
gpu_memory_s... |
class SharedQueue(LocalSocketComm):
def __init__(self, name='', create=False, maxsize=1):
super().__init__(name, create)
if self._create:
self._queue = queue.Queue(maxsize)
else:
self._queue = None
def _sync(self):
while True:
(connection, _) =... |
class ResidualDenseBlock_5C(nn.Module):
def __init__(self, nf=64, gc=32, bias=True):
super(ResidualDenseBlock_5C, self).__init__()
self.conv1 = nn.Conv2d(nf, gc, 3, 1, 1, bias=bias)
self.conv2 = nn.Conv2d((nf + gc), gc, 3, 1, 1, bias=bias)
self.conv3 = nn.Conv2d((nf + (2 * gc)), gc, ... |
(unsafe_hash=True)
class FeedEntry():
title: str = dataclasses.field(compare=False)
long_url: str = dataclasses.field(compare=True)
summary: str = dataclasses.field(compare=False)
categories: List[str] = dataclasses.field(compare=False, repr=True)
data: Dict[(str, Any)] = dataclasses.field(compare=F... |
_module
class ConcatDataset(_ConcatDataset):
def __init__(self, datasets):
super(ConcatDataset, self).__init__(datasets)
self.CLASSES = datasets[0].CLASSES
if hasattr(datasets[0], 'flag'):
flags = []
for i in range(0, len(datasets)):
flags.append(datas... |
def get_all_parameters(cls, parsed_args):
prefix = _get_prefix(cls)
if ((prefix is None) or (len(prefix) == 0)):
raise ValueError('Cannot retrieve parameters without prefix')
info = _get_info(cls)
if inspect.ismethod(cls.__init__):
spec = inspect.getargspec(cls.__init__)
if (spec... |
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, in_chans=3, cardinality=1, base_width=64, stem_width=64, stem_type='', output_stride=32, block_reduce_first=1, down_kernel_size=1, avg_down=False, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, aa_layer=None, drop_rate=0.0, drop_path_rate=0... |
def matplotlib_imshow(img, one_channel=False):
if one_channel:
img = img.mean(dim=0)
img = ((img / 2) + 0.5)
npimg = img.numpy()
if one_channel:
plt.imshow(npimg, cmap='Greys')
else:
plt.imshow(np.transpose(npimg, (1, 2, 0))) |
class SENet(nn.Module):
def __init__(self, block, layers, groups, reduction, dropout_p=0.2, inplanes=128, input_3x3=True, downsample_kernel_size=3, downsample_padding=1, num_classes=1000):
super(SENet, self).__init__()
self.inplanes = inplanes
if input_3x3:
layer0_modules = [('co... |
def build_fake_ut():
fake_ut = '\nimport shutil\nimport unittest\nimport time\nimport os\nimport sys\n\nimport numpy as np\n\nfrom neural_compressor.utils import logger\nfrom neural_compressor.quantization import fit\nfrom neural_compressor.config import PostTrainingQuantConfig\nfrom neural_compressor.data import D... |
def get_open_cases(date):
return sum(((dt_first_last_timestamps['start_time'] <= date) & (dt_first_last_timestamps['end_time'] > date))) |
def z_rotation(vector, theta):
R = np.array([[np.cos(theta), (- np.sin(theta)), 0], [np.sin(theta), np.cos(theta), 0], [0, 0, 1]])
return np.dot(R, vector) |
def listdir(*parts):
list1 = [d for d in os.listdir(os.path.join(*parts)) if ('.DS_Store' not in d)]
list1.sort()
return list1 |
class DensePoseConfidenceBasedSampler(DensePoseBaseSampler):
def __init__(self, confidence_channel: str, count_per_class: int=8, search_count_multiplier: Optional[float]=None, search_proportion: Optional[float]=None):
super().__init__(count_per_class)
self.confidence_channel = confidence_channel
... |
class IvarCorrection(Correction):
def __init__(self, config):
self.logger = logging.getLogger(__name__)
filename = config.get('filename')
if (filename is None):
raise CorrectionError("Missing argument 'filename' required by SdssIvarCorrection")
try:
hdu = fits... |
_task('semisupervised_translation')
class SemisupervisedTranslationTask(MultilingualTranslationTask):
def add_args(parser):
MultilingualTranslationTask.add_args(parser)
parser.add_argument('--lambda-parallel-config', default='1.0', type=str, metavar='CONFIG', help='cross-entropy reconstruction coeff... |
def generate_and_tokenize_prompt(tokenizer, data_point):
full_prompt = generate_prompt(data_point)
tokenized_full_prompt = tokenize(tokenizer, full_prompt)
return tokenized_full_prompt |
def train(model, data_loader, optimizer, tokenizer, epoch, warmup_steps, device, scheduler, config):
model.train()
metric_logger = utils.MetricLogger(delimiter=' ')
metric_logger.add_meter('lr', utils.SmoothedValue(window_size=50, fmt='{value:.6f}'))
metric_logger.add_meter('loss', utils.SmoothedValue(... |
class QGRLModel(QGModel):
def __init__(self, config, word_mat=None, elmo_word_mat=None, label_mat=None, pos_mat=None, ner_mat=None, trainable=True):
QGModel.__init__(self, config, word_mat=word_mat, elmo_word_mat=elmo_word_mat, label_mat=label_mat, pos_mat=pos_mat, ner_mat=ner_mat, trainable=trainable)
... |
def test_handle_market_order_bid_3():
(book, agent, limit_orders) = setup_book_with_orders(asks=[(100, [30, 40])])
market_order = MarketOrder(agent_id=2, time_placed=TIME, symbol=SYMBOL, quantity=70, side=Side.BID)
book.handle_market_order(market_order)
assert (book.get_l3_ask_data() == [])
assert (... |
def quantize_sym_model(sym_model, ctx, qconfig):
assert (isinstance(sym_model, tuple) and isinstance(sym_model[0], mx.symbol.Symbol))
(symnet, args, auxs) = sym_model
if (not check_mx_version('1.7.0')):
qconfig.pop('quantize_granularity', None)
arguments = {'sym': symnet, 'offline_params': list(... |
class TestDraw(unittest.TestCase):
def test_draw_net(self):
for filename in getFilenames():
net = caffe_pb2.NetParameter()
with open(filename) as infile:
text_format.Merge(infile.read(), net)
caffe.draw.draw_net(net, 'LR') |
def get_intrinsics_path(mode: str) -> Path:
return ((PATHS['mannequin_lmdb'] / mode) / 'intrinsics') |
def download_pcl(data_path, mode):
if (mode == 'gdrive'):
path = os.path.join(data_path, 'pcl')
os.makedirs(name=path, exist_ok=True)
archive_url = '
download_gdrive(archive_url, path, 'pcl.zip')
elif (mode == 'at'):
at_hash = 'e8b0af9c3f8c3c63a8212546f67a25a3'
do... |
class TicTacTeo(SymbolicEnvironment):
all_variations = ''
def __init__(self, width=3, know_valid_pos=True):
actions = [PLACE]
self.language = LanguageFrame(actions, extensional=[ZERO, MINE, EMPTY, OPPONENT, SUCC], constants=[str(i) for i in range(width)])
background = []
backgrou... |
_tf
class TFTransfoXLModelTest(TFModelTesterMixin, unittest.TestCase):
all_model_classes = ((TFTransfoXLModel, TFTransfoXLLMHeadModel) if is_tf_available() else ())
all_generative_model_classes = (() if is_tf_available() else ())
test_resize_embeddings = False
def setUp(self):
self.model_tester ... |
def placeholder_inputs(batch_size, num_point):
pointclouds_pl = tf.placeholder(tf.float32, shape=(batch_size, num_point, 6))
labels_pl = tf.placeholder(tf.int32, shape=(batch_size, num_point))
return (pointclouds_pl, labels_pl) |
def gather_grad(params):
world_size = get_world_size()
if (world_size == 1):
return
for param in params:
if (param.grad is not None):
dist.all_reduce(param.grad.data, op=dist.ReduceOp.SUM)
param.grad.data.div_(world_size) |
def get_pattern(config, modules, framework='pytorch'):
assert (framework in FRAMEWORK.keys()), f'does not support {framework}, currently only support {FRAMEWORK.keys()}'
name = config.pattern
name = name.split('_')[(- 1)]
pattern = FRAMEWORK[framework]
if ('x' in name):
pattern += 'NxM'
... |
def test_dbnet_draw_border_map():
target_generator = textdet_targets.DBNetTargets()
poly = np.array([[20, 21], [(- 14), 20], [(- 11), 30], [(- 22), 26]])
img_size = (40, 40)
thr_map = np.zeros(img_size, dtype=np.float32)
thr_mask = np.zeros(img_size, dtype=np.uint8)
target_generator.draw_border_... |
def write_sequences(gt, output_folder):
os.makedirs(output_folder, exist_ok=True)
for (seq, seq_frames) in gt.items():
write_sequence(seq_frames, os.path.join(output_folder, (seq + '.txt')))
return |
class TripletEvaluator(SentenceEvaluator):
def __init__(self, dataloader: DataLoader, main_distance_function: SimilarityFunction=None, name: str=''):
self.dataloader = dataloader
self.main_distance_function = main_distance_function
self.device = torch.device(('cuda' if torch.cuda.is_availabl... |
_module()
class SCFlowDecoder(BaseModule):
_h_channels = {'Basic': 128, 'Small': 96}
_cxt_channels = {'Basic': 128, 'Small': 64}
def __init__(self, net_type: str, num_levels: int, radius: int, iters: int, detach_flow: bool, detach_mask: bool, detach_pose: bool, mask_flow: bool, mask_corr: bool, pose_head_cf... |
class _Unbuffered():
def __init__(self, stream: TextIO) -> None:
self.stream = stream
def write(self, data: Any) -> None:
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr: str) -> Any:
return getattr(self.stream, attr) |
def run_all_reduce_sparse(rank, size, backend='gloo'):
dist.init_process_group(backend, rank=rank, world_size=size)
if (rank == 0):
data = torch.tensor([[0.0, 0.0, 0.0], [0.0, 1.1, 1.2]]).to_sparse(2)
result = all_reduce_sparse(data)
else:
data = torch.tensor([[0.0, 0.0, 0.0], [0.0, ... |
class VerticalFlip(object):
def __init__(self, p=0.5):
self.p = p
self.t = A.VerticalFlip(p=self.p)
def __call__(self, image):
return self.t(image=image)['image']
def __repr__(self):
return (self.__class__.__name__ + '(p={0})'.format(self.p)) |
class FunnelTokenizerFast(BertTokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
cls_token_type_id: int = 2
def ... |
class DataLoader(object):
def __init__(self, fname, mode):
self.fname = fname
self.mode = mode
def preprocess(self, line, speaker_tag='<first_speaker>'):
line = ((speaker_tag + ' ') + line.lower())
return line
def load_data(self):
dataset = []
f = codecs.open(... |
def specificity(y_true, y_pred):
y_true = np.asarray(y_true)
y_pred = np.asarray(y_pred)
spec_out = []
for classe in np.unique(y_true):
negatives = np.sum((y_true != classe).astype(int))
tn = np.sum((y_pred[(y_true != classe)] != classe).astype(int))
spec_out.append((tn / negativ... |
def create_image_or_video_tensor(size: Sequence[int]) -> torch.Tensor:
return torch.randint(0, 256, size, dtype=torch.uint8) |
def conv_layer(x, input_channel, output_channel, k_size=3, relu=True, stride=1, bn=True, name='conv_layer'):
with tf.name_scope(name):
w = weight_variable([k_size, k_size, input_channel, output_channel], 'weight')
b = bias_variable([output_channel], 'bias')
answer = (conv2d(x, w, s=stride) +... |
def data_files(data_dir, subset):
if (subset not in ['train', 'validation', 'test']):
print('Invalid subset!')
exit((- 1))
tf_record_pattern = os.path.join(data_dir, ('%s-*' % subset))
data_files = tf.gfile.Glob(tf_record_pattern)
print(data_files)
if (not data_files):
print(... |
def train(train_loader, model, model_base, landscape_model, criterion, optimizer, epoch, args):
batch_time = AverageMeter('Time', ':6.3f')
data_time = AverageMeter('Data', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('', ':6.2f')
top5 = AverageMeter('', ':6.2f')
progress = ... |
class ValueNode(Node):
def __init__(self, state, parents=set(), children=set()):
super().__init__(state, parents, children)
self.state = state
self.value = 0.0
self.visits = 0
def backward(self, value):
self.visits += 1
self.value += value |
class GroupsSimpleStationarySingleItem(GroupsSimpleStationary):
def _reset(self):
super()._reset()
self.world.remove_object(self.distractor_item) |
class ImageNet(datasets.ImageFolder):
def __init__(self, root=MyPath.db_root_dir('imagenet'), split='train', transform=None):
super(ImageNet, self).__init__(root=os.path.join(root, ('ILSVRC2012_img_%s' % split)), transform=None)
self.transform = transform
self.split = split
self.resi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.