code stringlengths 101 5.91M |
|---|
def create_json(foldername, trainingcsv):
dataset_name = foldername
dataset_id = str(uuid.uuid4())
columns = list()
colnames = list(pd.read_csv(trainingcsv))
for i in range(len(colnames)):
if (colnames[i] != 'class_'):
columns.append({'colIndex': i, 'colName': colnames[i], 'colTy... |
def torch_default_param_init_fn_(module: nn.Module, verbose: int=0, **kwargs):
del kwargs
if (verbose > 1):
warnings.warn(f"Initializing network using module's reset_parameters attribute")
if hasattr(module, 'reset_parameters'):
module.reset_parameters() |
def test_psp_head():
with pytest.raises(AssertionError):
PSPHead(in_channels=4, channels=2, num_classes=19, pool_scales=1)
head = PSPHead(in_channels=4, channels=2, num_classes=19)
assert (not _conv_has_norm(head, sync_bn=False))
head = PSPHead(in_channels=4, channels=2, num_classes=19, norm_cfg... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None, NL=True):
super(Bottleneck, self).__init__()
if (norm_layer is None):
norm_layer = nn.BatchNorm2d
width = (int((pla... |
(events=subsets(_ALL_EVENTS_WITH_HANDLERS))
_events_with_registered_handlers_to_subset
def test_function_call(events):
assert (_RECORDED_EVENTS == [])
run_cell('\n def foo(x):\n return [x]\n ')
throw_and_print_diff_if_recorded_not_equal_to(filter_events_to_subset([TraceEvent.init_mo... |
def edge_density_and_new_pairs(pairs, cycle):
new_pairs = list()
all_pairs = list()
for (i, e1) in enumerate(cycle):
for e2 in cycle[(i + 1):(- 1)]:
all_pairs.append(sorted([e1, e2]))
if ((not (e2 in pairs[e1])) and (not (e1 in pairs[e2]))):
new_pairs.append(s... |
def make_data_loader(args, yaml_file, tokenizer, is_distributed=True, is_train=True, start_iter=0, is_pretrain=False, transform=None):
if is_pretrain:
assert is_train
dataset = build_dataset(yaml_file, tokenizer, args, is_train, transform)
else:
dataset = build_dataset(yaml_file, tokeniz... |
def test_elliptical_cold_vt():
idf = dehnendf(beta=0.0, profileParams=((1.0 / 3.0), 1.0, 0.0125))
cp = 0.05
pot = [LogarithmicHaloPotential(normalize=1.0), EllipticalDiskPotential(cp=cp, sp=0.0, p=0.0, tform=(- 150.0), tsteady=125.0)]
edf = evolveddiskdf(idf, pot=pot, to=(- 150.0))
(mvt, grid) = edf... |
def _create_dummy_loader():
loader = dict(type='HardDiskLoader', repeat=1, parser=dict(type='LineJsonParser', keys=['file_name', 'height', 'width', 'annotations']))
return loader |
def test_ChandrasekharDynamicalFrictionForce_constLambda():
from galpy.orbit import Orbit
from galpy.util import conversion
(ro, vo) = (8.0, 220.0)
GMs = ((10.0 ** 9.0) / conversion.mass_in_msol(vo, ro))
const_lnLambda = 7.0
r_init = 2.0
dt = (2.0 / conversion.time_in_Gyr(vo, ro))
lp = p... |
class MaCowUnit(Flow):
def __init__(self, in_channels, kernel_size, s_channels, scale=True, inverse=False):
super(MaCowUnit, self).__init__(inverse)
self.actnorm1 = ActNorm2dFlow(in_channels, inverse=inverse)
self.actnorm2 = ActNorm2dFlow(in_channels, inverse=inverse)
self.conv1 = Ma... |
def shortest_path_length(length_by_edge, startnode, goalnode):
unvisited_nodes = []
heappush(unvisited_nodes, (0, startnode))
visited_nodes = set()
while (len(unvisited_nodes) > 0):
(distance, node) = heappop(unvisited_nodes)
if (node is goalnode):
return distance
vis... |
def interpolate_3d(vec1, vec2, n_points):
ret = []
m = (vec2 - vec1)
step = (m / (n_points + 1))
for i in range(1, (n_points + 1)):
ret.append((vec1 + (step * i)))
return np.array(ret) |
def get_parser(desc, default_task='translation'):
usr_parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False)
usr_parser.add_argument('--user-dir', default=None)
(usr_args, _) = usr_parser.parse_known_args()
utils.import_user_module(usr_args)
parser = argparse.ArgumentParser(allow_abbre... |
class ExpansionNet_v2(CaptioningModel):
def __init__(self, d_model, N_enc, N_dec, ff, num_heads, num_exp_enc_list, num_exp_dec, output_word2idx, output_idx2word, max_seq_len, drop_args, img_feature_dim=2048, rank=0):
super().__init__()
self.output_word2idx = output_word2idx
self.output_idx2w... |
class BatchSampler(BaseSampler):
def __init__(self, algo, env):
super().__init__(algo, env)
warnings.warn(DeprecationWarning('BatchSampler is deprecated, and will be removed in the next release. Please use one of the samplers which implements garage.sampler.Sampler, such as LocalSampler.'))
def ... |
class Critic(nn.Module):
def __init__(self, encoder_cfg, action_shape, hidden_dim, hidden_depth):
super().__init__()
self.encoder = Encoder(**encoder_cfg)
self.Q1 = utils.mlp((self.encoder.feature_dim + action_shape[0]), hidden_dim, 1, hidden_depth)
self.Q2 = utils.mlp((self.encoder.... |
class InceptionV3(nn.Module):
def __init__(self):
super().__init__()
inception = models.inception_v3(pretrained=True)
self.block1 = nn.Sequential(inception.Conv2d_1a_3x3, inception.Conv2d_2a_3x3, inception.Conv2d_2b_3x3, nn.MaxPool2d(kernel_size=3, stride=2))
self.block2 = nn.Sequent... |
class McLoader(object):
def __init__(self, mclient_path):
assert (mclient_path is not None), "Please specify 'data_mclient_path' in the config."
self.mclient_path = mclient_path
server_list_config_file = '{}/server_list.conf'.format(self.mclient_path)
client_config_file = '{}/client.... |
def test_clone():
from sklearn.base import clone
a = sgd.FMRegression()
b = clone(a)
assert (a.get_params() == b.get_params())
a = sgd.FMClassification()
b = clone(a)
assert (a.get_params() == b.get_params()) |
class AdapterOutput():
up: SamplerOutput = None
down: SamplerOutput = None
pre_norm: LayerNormOutput = None
post_norm: LayerNormOutput = None |
class Instances():
def __init__(self, image_size: Tuple[(int, int)], **kwargs: Any):
self._image_size = image_size
self._fields: Dict[(str, Any)] = {}
for (k, v) in kwargs.items():
self.set(k, v)
def image_size(self) -> Tuple[(int, int)]:
return self._image_size
d... |
def twomassPath(dr='tgas'):
return os.path.join(_GAIA_TOOLS_DATA, 'Gaia', 'gdr1', 'dstn_match', 'tgas-matched-2mass.fits.gz') |
def is_module_wrapper(module: nn.Module) -> bool:
def is_module_in_wrapper(module, module_wrapper):
module_wrappers = tuple(module_wrapper.module_dict.values())
if isinstance(module, module_wrappers):
return True
for child in module_wrapper.children.values():
if is_mo... |
_tf
class UtilsFunctionsTest(unittest.TestCase):
def test_top_k_top_p_filtering(self):
logits = tf.convert_to_tensor([[8.2220991, (- 0.5620044), 5., 4.0386393, (- 6.8798378), (- 0.), (- 3.2012153), 2., 1., 7., 8., (- 9.), (- 5.), (- 1.), (- 7.1115294), (- 0.8369633), (- 5.3186408), 7., 0., (- 0.), (- 5.9179... |
class APCModel(nn.Module):
def __init__(self, mel_dim, prenet_config, rnn_config):
super(APCModel, self).__init__()
self.mel_dim = mel_dim
if (prenet_config is not None):
assert (prenet_config.input_size == mel_dim)
assert (prenet_config.hidden_size == rnn_config.inpu... |
class _ParseType():
def __name__(self) -> str:
name = self.__class__.__name__
assert isinstance(name, str)
return name
def __str__(self) -> str:
return self.__name__ |
def tag_json_files(json_file):
for sentence in json_file:
tagged_sent = nlp(sentence['text'])
conllu = ''
for (i, token) in enumerate(tagged_sent.iter_tokens()):
head = token.head
conllu += '{}\t{}\t{}\t{}\t{}\t_\t{}\t{}\t_\t_\n'.format((i + 1), token, token.lemma_, t... |
_model
def SoT_Base(pretrained=False, **kwargs):
ViTConfig['embed_dim'] = 528
ViTConfig['depth'] = 24
ViTConfig['num_heads'] = 8
ViTConfig['mlp_ratio'] = 3
representationConfig['args']['dim'] = 528
representationConfig['args']['num_heads'] = 6
representationConfig['args']['wr_dim'] = 38
... |
def using_backend(test_backend):
require_set_backend()
if isinstance(test_backend, str):
return (backend.BACKEND_NAME == test_backend)
return isinstance(backend, test_backend) |
def test_constructor_path(waveform):
sound = waveform.waveform
assert isinstance(sound, np.ndarray) |
def set_random_seed(seed):
random.seed(seed)
numpy.random.seed(seed)
torch.manual_seed(seed)
mpu.model_parallel_cuda_manual_seed(seed) |
class ISeg2017SemiInterface(MedicalDatasetSemiInterface):
def __init__(self, root_dir=DATA_PATH, labeled_data_ratio: float=0.2, unlabeled_data_ratio: float=0.8, seed: int=0, verbose: bool=True) -> None:
super().__init__(ISeg2017Dataset, root_dir, labeled_data_ratio, unlabeled_data_ratio, seed, verbose)
... |
def _update_avg_gradients(avg_gradients, gradients, step):
if (avg_gradients is None):
avg_gradients = [np.zeros_like(gradient) for gradient in gradients]
for i in range(len(gradients)):
avg_gradients[i] = ((avg_gradients[i] * (1.0 - (1.0 / (step + 1)))) + (gradients[i] / (step + 1)))
return... |
def train(config):
logger = logging.getLogger('')
du = DataUtil(config=config)
du.load_vocab(src_vocab=config.src_vocab, dst_vocab=config.dst_vocab, src_vocab_size=config.src_vocab_size_a, dst_vocab_size=config.src_vocab_size_b)
model = Model(config=config)
model.build_variational_train_model()
... |
def get_parser(**parser_kwargs):
def str2bool(v):
if isinstance(v, bool):
return v
if (v.lower() in ('yes', 'true', 't', 'y', '1')):
return True
elif (v.lower() in ('no', 'false', 'f', 'n', '0')):
return False
else:
raise argparse.Argum... |
def mkdir_p(dirname):
assert (dirname is not None)
if ((dirname == '') or os.path.isdir(dirname)):
return
try:
os.makedirs(dirname)
except OSError as e:
if (e.errno != errno.EEXIST):
raise e |
class MnliProcessor(DataProcessor):
def get_train_examples(self, data_dir):
return self._create_examples(self._read_tsv(os.path.join(data_dir, 'train.tsv')), 'train')
def get_dev_examples(self, data_dir):
return self._create_examples(self._read_tsv(os.path.join(data_dir, 'dev_matched.tsv')), 'de... |
class DIV2K(srdata.SRData):
def __init__(self, args, train=True):
super(DIV2K, self).__init__(args, train)
self.repeat = (args.test_every // (args.n_train // args.batch_size))
def _scan(self):
list_hr = []
if self.train:
idx_begin = 0
idx_end = self.args.n... |
class TestHerReplayBuffer():
def setup_method(self):
self.env = GarageEnv(DummyDictEnv())
self.obs = self.env.reset()
self._replay_k = 4
self.replay_buffer = HERReplayBuffer(env_spec=self.env.spec, capacity_in_transitions=10, replay_k=self._replay_k, reward_fn=self.env.compute_reward... |
def get_a2j_conf_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--seed', default=0, type=int)
parser.add_argument('--phase', default='train')
parser.add_argument('--dataset', default='nyu')
parser.add_argument('--num_epoch', default=20, type=int)
parser.add_argument('--batch_s... |
def _make_group(N, ni, nf, block, stride, drop_p):
return [block((ni if (i == 0) else nf), nf, (stride if (i == 0) else 1), drop_p) for i in range(N)] |
class MultiprocessLoader(object):
def __init__(self, dataloader, num_workers=2):
self.dl = dataloader
self.queue_size = (2 * num_workers)
def __iter__(self):
output_queue = queue.Queue(self.queue_size)
output_thread = threading.Thread(target=_multiproc_iter, args=(self.dl, output... |
class TestDrawAverageWithSTD(TestCase):
def setUp(self) -> None:
config = {'avg': AveragewithStd()}
self.METER = MeterInterface(config)
columns_to_draw = [['avg_mean', 'avg_lstd', 'avg_hstd']]
from pathlib import Path
self.drawer = DrawCSV2(columns_to_draw=columns_to_draw, sa... |
class Args(object):
def __init__(self, config):
is_test = False
if is_test:
self.experiment_id = (('KPConvNet' + time.strftime('%m%d%H%M')) + 'Test')
else:
self.experiment_id = ('KPConvNet' + time.strftime('%m%d%H%M'))
self.device = torch.device(('cuda' if tor... |
(jax.jit, static_argnames=('backup_entropy', 'update_target'))
def _update_jit(rng: PRNGKey, actor: Model, critic: Model, target_critic: Model, temp: Model, batch: Batch, discount: float, tau: float, target_entropy: float, backup_entropy: bool, update_target: bool) -> Tuple[(PRNGKey, Model, Model, Model, Model, InfoDic... |
def article_recommendation(json):
json = json.get('recommendations')
if (not json):
return ('No recommendations submitted.', 400)
if (len(json) > app.config['max_users_per_recommendation']):
return (('Requests must not contain more than %s users.' % app.config['max_users_per_recommendation']... |
def dump(obj, file=None, file_format=None, **kwargs):
if isinstance(file, Path):
file = str(file)
if (file_format is None):
if is_str(file):
file_format = file.split('.')[(- 1)]
elif (file is None):
raise ValueError('file_format must be specified since file is Non... |
class ConvGroupBlock(nn.Module):
def __init__(self, channels, multi_blocks, groups, dropout_rate):
super(ConvGroupBlock, self).__init__()
self.conv = ChannelwiseConv2d(groups=groups, dropout_rate=dropout_rate)
self.block = SimpleGroupBlock(channels=channels, multi_blocks=multi_blocks, groups... |
class EncoderModel(nn.Module):
def __init__(self, encoder, **kwargs):
super().__init__()
if (encoder.proto is not None):
path = encoder.pop('proto')
enc_config = AutoConfig.from_pretrained(path)
self.encoder = AutoModel.from_pretrained(path, config=enc_config)
... |
def build_VAE(cfg, device='cpu'):
x_dim = cfg.getint('Network', 'x_dim')
z_dim = cfg.getint('Network', 'z_dim')
activation = cfg.get('Network', 'activation')
dropout_p = cfg.getfloat('Network', 'dropout_p')
dense_x_z = ([] if (cfg.get('Network', 'dense_x_z') == '') else [int(i) for i in cfg.get('Net... |
class ConvPool2D():
def __init__(self, n_layers, filters, kernel_size, activation, pooling='max', initializer='glorot_uniform', batchnorm=False, use_bias=True, name=None):
self.n_layers = n_layers
self.filters = filters
self.kernel_size = kernel_size
self.activation = activation
... |
class ReformerTokenizer():
def __init__(self, *args, **kwargs):
requires_sentencepiece(self)
def from_pretrained(self, *args, **kwargs):
requires_sentencepiece(self) |
def bernoulli_nll(x, p):
(x_exp, p_exp) = ([], [])
for (x_size, p_size) in zip(x.size(), p.size()):
if (x_size > p_size):
x_exp.append((- 1))
p_exp.append(x_size)
elif (x_size < p_size):
x_exp.append(p_size)
p_exp.append((- 1))
else:
... |
def cyl_vol_func(X, Y, Z, xymin=0.0, xymax=0.15, zmin=0.05, zmax=0.15):
xy = numpy.sqrt(((X ** 2.0) + (Y ** 2.0)))
out = numpy.zeros_like(X)
out[((((xy >= xymin) * (xy < xymax)) * (Z >= zmin)) * (Z < zmax))] = 1.0
return out |
def print_available_pretrained_models():
print('The following pretrained models are available:\n')
av_models = get_available_models()
for m in av_models.keys():
print('')
print(m)
print(av_models[m]['description']) |
def store_json(fpath, obj, pretty=False):
kwargs = {}
if pretty:
kwargs['indent'] = 2
kwargs['sort_keys'] = True
with open(fpath, 'w') as fp:
json.dump(obj, fp, **kwargs) |
class RandomFPHook(Hook):
def after_train_epoch(self, runner):
dataset = runner.data_loader.dataset
if (not hasattr(dataset, 'add_random_fp')):
return
data_infos = dataset.add_random_fp()
ori_infos = runner.data_loader.dataset.data_infos
assert (len(data_infos) ==... |
def biattention_layer(is_train, h, u, h_mask=None, u_mask=None, scope=None, tensor_dict=None):
with tf.variable_scope((scope or 'attention_layer')):
h = tf.expand_dims(h, 1)
h_mask = tf.expand_dims(h_mask, 1)
(u_a, h_a) = bi_attention(is_train, h, u, h_mask=h_mask, u_mask=u_mask, tensor_dict... |
def fdmobilenet_w1(**kwargs):
return get_mobilenet(version='fd', width_scale=1.0, model_name='fdmobilenet_w1', **kwargs) |
def fake_transition() -> chex.ArrayTree:
return {'obs': jnp.array((5, 4)), 'reward': jnp.zeros((3,))} |
def init_dist(rank, world_size):
os.environ['LOCAL_RANK'] = str(rank)
os.environ['RANK'] = str(rank)
os.environ['WORLD_SIZE'] = str(world_size)
os.environ['NPROC_PER_NODE'] = str(world_size)
atorch.init_distributed('nccl')
torch.cuda.device(atorch.local_rank())
parallel_config = ([('model', ... |
def character_metric_detect(preds, targs):
assert (len(preds) == len(targs)), f'{len(preds)},{len(targs)}'
(tp, targ_p, pred_p, hit) = (0, 0, 0, 0)
for (pred_item, targ_item) in zip(preds, targs):
assert (pred_item[0] == targ_item[0])
(pred, targ) = (sorted(pred_item[1:]), sorted(targ_item[1... |
def build_fake_yaml_disable_first_quantization():
fake_yaml = '\n model:\n name: fake_yaml\n framework: tensorflow\n inputs: input\n outputs: op_to_store\n device: cpu\n quantization:\n recipes:\n first_conv_or_matmul_quantization: False\n... |
class Encoder(nn.Module):
def __init__(self, num_classes):
super().__init__()
self.initial_block = DownsamplerBlock(3, 16)
self.layers = nn.ModuleList()
self.layers.append(DownsamplerBlock(16, 64))
for x in range(0, 5):
self.layers.append(non_bottleneck_1d(64, 0.0... |
def cross_entropy(pred, label, weight=None, class_weight=None, reduction='mean', avg_factor=None, ignore_index=(- 100)):
loss = F.cross_entropy(pred, label, weight=class_weight, reduction='none', ignore_index=ignore_index)
if (weight is not None):
weight = weight.float()
loss = weight_reduce_loss(lo... |
class PreActResNet(nn.Module):
def __init__(self, block, num_blocks, num_classes=10):
super(PreActResNet, self).__init__()
self.in_planes = 64
self.other_layers = nn.ModuleList()
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.layer_one = se... |
def unpad_input(padded: torch.Tensor, attention_mask: torch.Tensor) -> tuple[(torch.Tensor, Callable, torch.Tensor, int)]:
(batch_size, padded_seqlen) = padded.shape[:2]
(unpadded, indices, cu_seqlens, max_seqlen) = bert_padding.unpad_input(padded, attention_mask)
def pad_back(unpadded: torch.Tensor):
... |
.parametrize(['space', 'lower_x_hyperplane', 'upper_x_hyperplane', 'lower_y_hyperplane', 'upper_y_hyperplane', 'lower_z_hyperplane', 'upper_z_hyperplane'], [(Space(x1=0, x2=1, y1=0, y2=1, z1=0, z2=1), Space(x1=(- jnp.inf), x2=0, y1=(- jnp.inf), y2=jnp.inf, z1=(- jnp.inf), z2=jnp.inf), Space(x1=1, x2=jnp.inf, y1=(- jnp.... |
def main():
if args.save_images:
result_dir_img = os.path.join(args.result_dir, 'png')
result_dir_mat = os.path.join(args.result_dir, 'mat')
utils.mkdir(result_dir_img)
utils.mkdir(result_dir_mat)
test_dataset = get_test_data(args.input_dir)
test_loader = DataLoader(dataset=t... |
def hf_bucket_url(model_id: str, filename: str, subfolder: Optional[str]=None, revision: Optional[str]=None, mirror=None) -> str:
if (subfolder is not None):
filename = f'{subfolder}/{filename}'
if mirror:
if (mirror in ['tuna', 'bfsu']):
raise ValueError('The Tuna and BFSU mirrors a... |
def dtype_to_name(dtype_mapping, dtype):
return list(dtype_mapping.keys())[list(dtype_mapping.values()).index(dtype)] |
class _ROIPool(Function):
def forward(ctx, input, rois, output_size, spatial_scale):
ctx.output_size = _pair(output_size)
ctx.spatial_scale = spatial_scale
ctx.input_shape = input.size()
(output, argmax) = C_ROIPooling.roi_pool_forward(input, rois, spatial_scale, output_size[0], outp... |
def build_model(model, device, channel=1):
if (model == 'unet'):
from other_models import U_Net
net = U_Net(img_ch=channel, output_ch=1).to(device)
elif (model == 'cenet'):
print('input channel of CE-Net must be 3, param channel no used')
from imed_models import CE_Net
ne... |
def shuffle_data(inputs):
input = torch.cat(inputs)
output = input.new_empty(input.size())
req = dist.all_to_all_single(output, input)
output = output.reshape(my_size, (- 1))
return output |
class MobileViTLayer(nn.Module):
def __init__(self, config: MobileViTConfig, in_channels: int, out_channels: int, stride: int, hidden_size: int, num_stages: int, dilation: int=1) -> None:
super().__init__()
self.patch_width = config.patch_size
self.patch_height = config.patch_size
if... |
class TestAdaptorONNXRT(unittest.TestCase):
qlinear_backend = QuantizationMode.QLinearOps
qdq_backend = 'qdq'
integer_backend = QuantizationMode.IntegerOps
static_q_config = {'weight': {'dtype': 3, 'algorithm': 'minmax', 'scheme': 'sym', 'granularity': 'per_tensor'}, 'activation': {'dtype': 2, 'algorith... |
class BPE(object):
def __init__(self, codes, merges=(- 1), separator='', vocab=None, glossaries=None):
codes.seek(0)
firstline = codes.readline()
if firstline.startswith('#version:'):
self.version = tuple([int(x) for x in re.sub('(\\.0+)*$', '', firstline.split()[(- 1)]).split('.... |
def encode_audio(video_path, audio_path, output_path):
ffmpeg.concat(ffmpeg.input(video_path), ffmpeg.input(audio_path), v=1, a=1).output(output_path, strict='-2').run(overwrite_output=True) |
def sb_cnn(x, is_training, config):
print(('Input: ' + str(x.get_shape)))
input_layer = tf.expand_dims(x, 3)
return sb_cnn_core(input_layer, is_training, config) |
class PrependTokenDataset(BaseWrapperDataset):
def __init__(self, dataset, token=None):
super().__init__(dataset)
self.token = token
if (token is not None):
self._sizes = (np.array(dataset.sizes) + 1)
else:
self._sizes = dataset.sizes
def __getitem__(self,... |
def extend_schema_with_default(validator_class):
validate_properties = validator_class.VALIDATORS['properties']
def set_defaults(validator, properties, instance, schema):
for (property_, subschema) in properties.items():
if (('default' in subschema) and (not isinstance(instance, list))):
... |
def network_weight_zero_init(net: nn.Module):
with torch.no_grad():
for m in net.modules():
if isinstance(m, nn.Conv2d):
device = m.weight.device
(in_channels, out_channels, k1, k2) = m.weight.shape
m.weight[:] = ((torch.randn(m.weight.shape, devic... |
class ConvBlock(nn.Module):
def __init__(self, in_channels, out_channels):
super(ConvBlock, self).__init__()
self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
self.conv2 = nn.Conv2d(in_channels=out_channe... |
def add_feature_maps(feature_maps, layer_name):
with tf.name_scope(layer_name):
(batch, maps_height, maps_width, num_maps) = np.array(feature_maps.shape).astype(np.int32)
map_width_out = 300
ratio = (map_width_out / maps_width)
map_height_out = int((maps_height * ratio))
map_... |
def pairwise_concat(nodes):
n_nodes = tf.shape(nodes)[0]
node_embedding_dim = tf.shape(nodes)[1]
tile_as = tf.reshape(tf.tile(nodes, [1, n_nodes]), [(n_nodes * n_nodes), node_embedding_dim])
tile_as.set_shape([None, 40])
tile_bs = tf.tile(nodes, [n_nodes, 1])
toret = tf.concat([tile_as, tile_bs]... |
def test_unique_nodelete4a():
o = m.MyObject4a(23)
assert (o.value == 23)
cstats = ConstructorStats.get(m.MyObject4a)
assert (cstats.alive() == 1)
del o
assert (cstats.alive() == 1) |
def file_process(dialogue_file='1224_ms.json'):
def qrfa_check(item):
if (item[0] == USER_TAG):
label = item[2]
elif (item[0] == AGENT_TAG):
label = ('REQUEST' if (item[2] in REQUEST) else 'ANSWER')
else:
label = 'MISSING'
return label
diags = ... |
def save_tflite(tflite_model, path, filename):
open(os.path.join(path, (filename + '.tflite')), 'wb').write(tflite_model) |
def load_mlp(our, oai, dst2src=False):
load_weights(oai.c_fc, our.dense_h_to_4h, dst2src)
load_weights(oai.c_proj, our.dense_4h_to_h, dst2src) |
def load_folds(options=None, df=None):
if ((df is not None) and ('fold' in df.columns)):
i_train = df.query("fold != 'test'").index.to_numpy()
i_test = df.query("fold == 'test'").index.to_numpy()
return [(i_train, i_test)]
print('No folds specified in CSV file')
if (options.folds == ... |
def main(translate_args: Dict[(str, Any)], dataset_args: Dict[(str, Any)]) -> None:
dataset = get_dataset(dataset_args)
texts = get_texts(dataset, dataset_args)
few_shot_dataset = get_few_shot_dataset(dataset_args)
prompts = get_few_shot_prompts(few_shot_dataset, dataset_args, translate_args, shots=4)
... |
def main():
parser = argparse.ArgumentParser(description='PyTorch Object Detection Training')
parser.add_argument('--config-file', default='', metavar='FILE', help='path to config file', type=str)
parser.add_argument('--local_rank', type=int, default=0)
parser.add_argument('--skip-test', dest='skip_test... |
def update_user(users, user, line_no):
if (user in reserved):
return
all_digit = True
for char in user:
if (char not in string.digits):
all_digit = False
if all_digit:
return
if (user not in users):
users[user] = (line_no, line_no)
else:
(cmin,... |
class TestPAAHead(TestCase):
def test_paa_head_loss(self):
class mock_skm():
def GaussianMixture(self, *args, **kwargs):
return self
def fit(self, loss):
pass
def predict(self, loss):
components = np.zeros_like(loss, dtype=n... |
def quantize_targ_layer(graph, bit_weight=8, targ_type=None, quant_type='uniform'):
print('Quantizing Layer parameters')
assert (quant_type in ['uniform', 'pwg', 'pwl', 'pws']), 'quant_type not supported'
assert (targ_type != None), 'targ_type cannot be None!'
for layer_idx in graph:
if (type(gr... |
def parse_pound(line):
all_pound = re.findall('[0-9][0-9.,]*', line)
for pound in all_pound:
number_text = engine.number_to_words(pound[1:].replace(',', ''))
number_text = number_text.replace('-', ' ')
pound_text = (number_text + ' pounds')
line = line.replace(pound, pound_text, ... |
def convert_examples_to_features(examples, tokenizer, max_seq_length, doc_stride, max_query_length, is_training, output_fn):
uid_to_qid = {}
unique_id =
for (example_index, example) in enumerate(examples):
query_tokens = tokenizer.tokenize(example.question_text)
if (len(query_tokens) > max_... |
class DummySpace(object):
def __init__(self, dim):
self._dim = dim
def shape(self):
return self._dim |
class Environment():
def __init__(self):
self.action_space = ()
pass
def reset(self):
raise NotImplementedError()
def step(self, action_dict):
raise NotImplementedError()
def get_agent_handles(self):
raise NotImplementedError() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.