code stringlengths 101 5.91M |
|---|
def _normalize_clip_observation(x, clip_range=[(- 5.0), 5.0]):
rms = RunningMeanStd(shape=x.shape[1:])
norm_x = tf.clip_by_value(((x - rms.mean) / rms.std), min(clip_range), max(clip_range))
return (norm_x, rms) |
def latency(args, model_path, forecaster, train_loader, test_loader, records):
try:
forecaster.load(model_path)
except:
forecaster.fit(train_loader, epochs=1)
(latency, latency_onnx, latency_vino, latency_jit) = ([], [], [], [])
latency_trim_portion = 0.1
latency_percentile = [50, 90... |
def text_to_sequence(text, cleaner_names):
sequence = []
clean_text = _clean_text(text, cleaner_names)
for symbol in clean_text:
symbol_id = _symbol_to_id[symbol]
sequence += [symbol_id]
return sequence |
def save_dataset(transform, train_, test_, filename):
torch.save({'transform': transform, 'train': train_, 'test': test_}, filename) |
def getBounds(lvls_arr: list, n_lvl: float):
lower = lvls_arr[0]
upper = lvls_arr[1]
for (i, v) in enumerate(lvls_arr[:(- 1)]):
if (n_lvl <= v):
break
lower = v
upper = lvls_arr[(i + 1)]
return (lower, upper) |
class CplxToConcatenatedReal(BaseCplxToReal):
def __init__(self, dim=(- 1)):
super().__init__()
self.dim = dim
def forward(self, input):
return cplx.to_concatenated_real(input, None, self.dim) |
def get_idx_dicts(data):
(ent_set, rel_set) = (set(), set())
for (lhs, rel, rhs) in data:
ent_set.add(lhs)
rel_set.add(rel)
ent_set.add(rhs)
ent_list = sorted(list(ent_set))
rel_list = sorted(list(rel_set))
(ent_to_idx, rel_to_idx) = ({}, {})
for (i, ent) in enumerate(ent... |
class ZScoreNormalize(intnormb.LocationScaleCLIMixin, intnormb.SingleImageNormalizeCLI):
def __init__(self, *, norm_value: float=1.0, **kwargs: typing.Any):
super().__init__(norm_value=norm_value, **kwargs)
self.voi: (intnormt.ImageLike | None) = None
def calculate_location(self, image: intnormt... |
.register('MobileNetV2')
def build_mbv2_backbone(cfg):
in_channels = cfg.MODEL.BACKBONE.IN_PLANES
base_channels = cfg.MODEL.BACKBONE.BASE_PLANES
out_channels = cfg.MODEL.HEAD.FEATURE_DIMS
round_nearest = cfg.MODEL.COMPRESSION.ROUND_NEAREST
width_multiplier = cfg.MODEL.COMPRESSION.WIDTH_MULTIPLIER
... |
class TestIterators(unittest.TestCase):
def test_counting_iterator(self, ref=None, itr=None):
if (ref is None):
assert (itr is None)
ref = list(range(10))
itr = iterators.CountingIterator(ref)
else:
assert (len(ref) == 10)
assert (itr is no... |
class SquareBoxCoder(box_coder.BoxCoder):
def __init__(self, scale_factors=None):
if scale_factors:
if (len(scale_factors) != 3):
raise ValueError('The argument scale_factors must be a list of length 3.')
if any(((scalar <= 0) for scalar in scale_factors)):
... |
class DeepPrunerProcessor(nn.Module):
def __init__(self, cfg):
super(DeepPrunerProcessor, self).__init__()
self.cfg = cfg.copy()
self.batch_norm = cfg.model.batch_norm
self.patch_match_disparity_sample_number = cfg.model.cost_processor.patch_match_disparity_sample_number
self... |
def merge_cl_lines(content_lines, space_spliters):
def overlap_len(min1, len1, min2, len2):
min_ = min1
max_ = (min1 + len1)
if (min1 > min2):
min_ = min2
if ((min1 + len1) < (min2 + len2)):
max_ = (min2 + len2)
return max(0, ((len1 + len2) - (max_ - m... |
def cal_phi(x, y, z, nx, ny, nz):
(poi_normal_x, poi_normal_y) = (((y * nz) - (ny * z)), ((z * nx) - (x * nz)))
phi_rad = np.arctan2(poi_normal_y, poi_normal_x)
return phi_rad |
def _make_copying_data_provider_base(data_sources_source, data_sources_schema, reader=tf.TextLineReader, num_samples=None, source_delimiter=' ', **kwargs):
decoder_source = split_tokens_decoder.SplitTokensDecoder(tokens_feature_name='source_tokens', length_feature_name='source_len', append_token='SEQUENCE_END', del... |
class DmolNet(nn.Module):
H: hps.Hyperparams
def setup(self):
self.out_conv = Conv1x1((self.H.num_mixtures * 10), precision=self.H.conv_precision)
def loglik(self, px_z, x):
return logistic_mix_logpmf(self.out_conv(px_z), x)
def sample(self, px_z, rng):
img = logistic_mix_sample(... |
class Classifier(nn.Module):
def __init__(self, in_nc=2048, out_nc=2, layers=(2048,), norm_layer=nn.BatchNorm1d, act_layer=nn.ReLU(True), use_dropout=False):
super(Classifier, self).__init__()
self.idx_tensor = None
channels = (([in_nc] + list(layers)) + [out_nc])
self.model = []
... |
class CondenseNet(nn.Module):
def __init__(self, channels, init_block_channels, groups, in_channels=3, in_size=(224, 224), num_classes=1000):
super(CondenseNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.feature... |
def create_qg_prompt(caption):
INTRO_BLURB = 'Given an image description, generate one or two multiple-choice questions that verifies if the image description is correct.\nClassify each concept into a type (object, human, animal, food, activity, attribute, counting, color, material, spatial, location, shape, other)... |
def get_node_mapper(lcc: np.ndarray) -> dict:
mapper = {}
counter = 0
for node in lcc:
mapper[node] = counter
counter += 1
return mapper |
def get_number_footer_lines(docbody, page_break_posns):
num_breaks = len(page_break_posns)
num_footer_lines = 0
empty_line = 0
keep_checking = 1
p_wordSearch = re.compile('([A-Za-z0-9-]+)', re.UNICODE)
if (num_breaks > 2):
while keep_checking:
cur_break = 1
if (((... |
def sklearn_DecisionTreeClassifier(*args, **kwargs):
return sklearn.tree.DecisionTreeClassifier(*args, **kwargs) |
def load_nifi_volume(filepath: str, normalize: bool=False) -> np.ndarray:
proxy_img = nib.load(filepath)
proxy_img.uncache()
img = np.array(proxy_img.dataobj)
if normalize:
img = zero_mean_unit_variance_normalization(img)
return img |
.parametrize('std', [EnglishNumberNormalizer(), EnglishTextNormalizer()])
def test_number_normalizer(std):
assert (std('two') == '2')
assert (std('thirty one') == '31')
assert (std('five twenty four') == '524')
assert (std('nineteen ninety nine') == '1999')
assert (std('twenty nineteen') == '2019')
... |
class MeterpreterSession(MsfSession):
def read(self):
return self.rpc.call(MsfRpcMethod.SessionMeterpreterRead, [self.sid])['data']
def write(self, data):
if (not data.endswith('\n')):
data += '\n'
self.rpc.call(MsfRpcMethod.SessionMeterpreterWrite, [self.sid, data])
def ... |
class AbstractWT(nn.Module):
def fit(self, X=None, train_loader=None, pretrained_model=None, lr: float=0.001, num_epochs: int=20, seed: int=42, attr_methods='Saliency', target=6, lamlSum: float=1.0, lamhSum: float=1.0, lamL2norm: float=1.0, lamCMF: float=1.0, lamConv: float=1.0, lamL1wave: float=1.0, lamL1attr: flo... |
class ExternalOptimizerInterface():
def __init__(self, loss, var_list=None, equalities=None, inequalities=None, var_to_bounds=None, **optimizer_kwargs):
self._loss = loss
self._equalities = (equalities or [])
self._inequalities = (inequalities or [])
if (var_list is None):
... |
class PGDAttack(Attack):
def __init__(self, args, model, nb_iter, loss_fn=nn.CrossEntropyLoss(reduction='sum')):
super(PGDAttack, self).__init__(args, model, nb_iter, loss_fn)
self.args = args
self.model = model
if (args.attack_ball == 'Linf'):
self.adversary = LinfPGDAtt... |
def _check_and_coerce_cfg_value_type(value_a, value_b, key, full_key):
type_b = type(value_b)
type_a = type(value_a)
if (type_a is type_b):
return value_a
if isinstance(value_b, np.ndarray):
value_a = np.array(value_a, dtype=value_b.dtype)
elif isinstance(value_b, six.string_types):
... |
def cmd_output_fixer(cmd: str) -> str:
cmd = cmd.strip(' \n')
if (len(cmd) < 2):
return cmd
stupidity = re.compile('^[ \\n\\r]*```.*\\n(.*)\\n```$', re.MULTILINE)
result = stupidity.search(cmd)
if result:
print('this would have been captured by the multi-line regex 1')
cmd = ... |
def read(*paths: Any, **kwargs: Any) -> str:
with open(Path(__file__).parent.joinpath(*paths), encoding=kwargs.get('encoding', 'utf8')) as open_file:
content = open_file.read().strip()
return content |
def test_getitem():
np.random.seed(0)
torch.manual_seed(0)
root_path = './tests/data/lyft'
ann_file = './tests/data/lyft/lyft_infos.pkl'
class_names = ('car', 'truck', 'bus', 'emergency_vehicle', 'other_vehicle', 'motorcycle', 'bicycle', 'pedestrian', 'animal')
point_cloud_range = [(- 80), (- 80... |
def parepare_dataset(sess, num_repeats):
data_file_size = data_info[(sess + '_dataset_length')]
NUM_CLASSES = data_info['label_length']
x_set = f0.create_dataset(('x_' + sess), ((data_file_size * num_repeats), (SIZE_SUB * SIZE_TOP), (SIZE_SUB * SIZE_TOP), 3), dtype='f')
s_set = f0.create_dataset(('s_' +... |
class CPDataset(data.Dataset):
def __init__(self, opt):
super(CPDataset, self).__init__()
self.opt = opt
self.stage = opt.stage
self.fine_height = opt.fine_height
self.fine_width = opt.fine_width
self.radius = opt.radius
self.grid_image = opt.grid_image
... |
class MobileNetV2_MPNCOV(nn.Module):
def __init__(self, num_classes=1000, width_mult=1.0):
super(MobileNetV2_MPNCOV, self).__init__()
block = InvertedResidual
input_channel = 32
last_channel = 1280
inverted_residual_setting = [[1, 16, 1, 1], [6, 24, 2, 2], [6, 32, 3, 2], [6, ... |
class Linear(fa_constructor.Linear):
def __init__(self, in_features: int, out_features: int, bias: bool=True, layer_config: dict=None) -> None:
if (layer_config is None):
layer_config = {}
layer_config['type'] = 'brsf'
super(Linear, self).__init__(in_features, out_features, bias,... |
def ade_quad_double_track(target, start, sols, gamma=0, verbose=1):
from phcpy.phcpy2c3 import py2c_copy_quaddobl_container_to_target_system
from phcpy.phcpy2c3 import py2c_copy_quaddobl_container_to_start_system
from phcpy.phcpy2c3 import py2c_ade_manypaths_qd
from phcpy.interface import store_quaddobl... |
def test_trunc_normal_init():
def _random_float(a, b):
return (((b - a) * random.random()) + a)
def _is_trunc_normal(tensor, mean, std, a, b):
z_samples = ((tensor.view((- 1)) - mean) / std)
z_samples = z_samples.tolist()
a0 = ((a - mean) / std)
b0 = ((b - mean) / std)
... |
class DepthEvaluationArguments(ArgumentsBase):
DESCRIPTION = 'SGDepth Depth Evaluation'
def __init__(self):
super().__init__()
self._harness_init_system()
self._harness_init_model()
self._harness_init_depth()
self._eval_init_logging()
def parse(self):
opt = se... |
def _main(client_only=False):
parser = options.general_parser()
options.add_server_args(parser)
if (not client_only):
options.add_data_args(parser)
(args, _) = parser.parse_known_args()
if (not client_only):
(_, agent_cls) = find_agent_cls(args)
if (args.data_type is None):
... |
def conv(x, channels, kernel=4, stride=2, pad=0, pad_type='zero', use_bias=True, scope='conv_0'):
with tf.variable_scope(scope):
if (pad_type == 'zero'):
x = tf.pad(x, [[0, 0], [pad, pad], [pad, pad], [0, 0]])
if (pad_type == 'reflect'):
x = tf.pad(x, [[0, 0], [pad, pad], [pa... |
class SupConLoss1(nn.Module):
def __init__(self, temperature=0.07, exclude_other_pos=False):
super().__init__()
self._t = temperature
self._exclude_pos = exclude_other_pos
logger.info(f'initializing {self.__class__.__name__} with t: {self._t}, exclude_pos: {self._exclude_pos}')
d... |
def main():
config = vars(parse_args())
if (config['name'] is None):
if config['deep_supervision']:
config['name'] = ('%s_%s_wDS' % (config['dataset'], config['arch']))
else:
config['name'] = ('%s_%s_woDS' % (config['dataset'], config['arch']))
os.makedirs(('models/%s... |
def main():
wpt_file = sys.argv[1]
with open(wpt_file, 'r') as fd:
wpts = [l.strip() for l in fd]
for ii in range(3):
generate_waypoint_pattern('direct to %s', wpts)
generate_waypoint_pattern('direct %s', wpts)
generate_waypoint_pattern('turn %s', wpts)
generate_waypoint_pattern(... |
def load_index_to_gpu(index: faiss.IndexIVFPQ, single_gpu_id=None):
if ((faiss.get_num_gpus() == 1) or (single_gpu_id is not None)):
res = faiss.StandardGpuResources()
res.setTempMemory(((128 * 1024) * 1024))
co = faiss.GpuClonerOptions()
co.useFloat16 = (index.pq.M >= 56)
if... |
def Train_or_Eval(model, state='Train'):
if (state == 'Train'):
model.train()
else:
model.eval() |
def PGD_perturb(sess, gradient, x, y, x_placeholder, y_placeholder, num_step, step_size, max_perturb):
perturb = np.zeros(x.shape)
for num in range(num_step):
perturb += (step_size * np.sign(sess.run(gradient, feed_dict={x_placeholder: (x + perturb), y_placeholder: y})))
perturb = np.clip(pertur... |
class IndexedCachedDataset(IndexedDataset):
def __init__(self, path, fix_lua_indexing=False):
super().__init__(path, fix_lua_indexing=fix_lua_indexing)
self.cache = None
self.cache_index = {}
def supports_prefetch(self):
return True
def prefetch(self, indices):
if all... |
def ciou_loss(boxes1: torch.Tensor, boxes2: torch.Tensor, reduction: str='none', eps: float=1e-07) -> torch.Tensor:
(x1, y1, x2, y2) = boxes1.unbind(dim=(- 1))
(x1g, y1g, x2g, y2g) = boxes2.unbind(dim=(- 1))
assert (x2 >= x1).all(), 'bad box: x1 larger than x2'
assert (y2 >= y1).all(), 'bad box: y1 larg... |
def get_logger(log_file=None):
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: - %(message)s', datefmt='%Y%m%d %H:%M:%S')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
del logger.handlers[:]
if log_file:
file_handler = logging.FileHandler(log_file, mode='w... |
def read_epe(stream):
sentences = []
for line in stream:
sentence = json.loads(line)
i = 0
for node in sentence['nodes']:
i = max(i, len(node.get('negation', [])))
sentence['negations'] = i
sentences.append(sentence)
return sentences |
class PlainDecoder(nn.Module):
def __init__(self, cfg):
super(PlainDecoder, self).__init__()
self.cfg = cfg
self.dropout = nn.Dropout2d(0.1)
self.conv8 = nn.Conv2d(128, cfg.num_classes, 1)
def forward(self, x):
x = self.dropout(x)
x = self.conv8(x)
x = F.i... |
class group(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1):
super(group, self).__init__()
self.conv_a = mfm(in_channels, in_channels, 1, 1, 0, dilation)
self.conv = mfm(in_channels, out_channels, kernel_size, stride, padding, dilation)
... |
def get_node_and_core_number(bigdl_type='float'):
result = callBigDlFunc(bigdl_type, 'getNodeAndCoreNumber')
return (result[0], result[1]) |
class Data(abc.ABC):
def losses(self, targets, outputs, loss_fn, inputs, model, aux=None):
raise NotImplementedError('Data.losses is not implemented.')
def losses_train(self, targets, outputs, loss_fn, inputs, model, aux=None):
return self.losses(targets, outputs, loss_fn, inputs, model, aux=aux... |
def preprocess_stage_3_build_dict(path, dict_sz, train, valid=None, test=None):
import operator
d = {}
def _count(fname, dic):
with open(os.path.join(path, fname), 'r') as fd:
lines = fd.read().splitlines()
for l in lines:
l = [w for w in l.split(' ') if (w !=... |
def compute_mean_word_length(stanza_doc):
return np.mean([len(word.text) for word in stanza_doc.sentences[0].words]) |
class PHNN(nn.Module):
def __init__(self, p_type, p_args, hparams, beta, device, p_module=__name__):
super().__init__()
self.device = device
self.p_type = getattr(sys.modules[p_module], p_type)
self.p_args = p_args
self.predictor = self.p_type(*self.p_args).to(self.device)
... |
def _weight_init_range(n_in, n_out):
range = ((4.0 * math.sqrt(6.0)) / math.sqrt((n_in + n_out)))
return {'minval': (- range), 'maxval': range} |
def download(url, path=None, overwrite=False, sha1_hash=None):
if (path is None):
fname = url.split('/')[(- 1)]
else:
path = os.path.expanduser(path)
if os.path.isdir(path):
fname = os.path.join(path, url.split('/')[(- 1)])
else:
fname = path
if (overw... |
class Homoglyphs():
def __init__(self, categories=None, languages=None, alphabet=None, strategy=STRATEGY_IGNORE, ascii_strategy=STRATEGY_IGNORE, ascii_range=ASCII_RANGE):
if (strategy not in (STRATEGY_LOAD, STRATEGY_IGNORE, STRATEGY_REMOVE)):
raise ValueError('Invalid strategy')
self.str... |
def getFirstLineInLogWithCertainPattern(filePathToLog, pattern):
foundLine = None
f = open(filePathToLog, 'r')
newLine = f.readline()
while newLine:
if (newLine.find(pattern) > (- 1)):
foundLine = newLine
break
newLine = f.readline()
f.close()
return found... |
def compute_return(reward, value, discount, bootstrap, lmbda, gamma):
next_values = torch.cat([value[1:], bootstrap[None]], 0)
target = (reward + (((gamma * discount) * next_values) * (1 - lmbda)))
outputs = []
accumulated_reward = bootstrap
for t in reversed(range(reward.shape[0])):
discoun... |
class BasicSwap(TransformationPass):
def __init__(self, coupling_map, initial_layout=None):
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
def run(self, dag):
new_dag = DAGCircuit()
if (self.initial_layout is None):
if... |
class Dataset(object):
def __init__(self, data_path):
self.num_items = setting.num_items
self.num_users = setting.num_users
self.batch_size = setting.batch_size
self.kshot_num = setting.kshot_num
self.kshot_second_num = setting.kshot_second_num
self.kshot_third_num = ... |
class KnowledgeSource():
def __init__(self, mongo_connection_string=None, database='kilt', collection='knowledgesource'):
if (not mongo_connection_string):
mongo_connection_string = DEFAULT_MONGO_CONNECTION_STRING
self.client = MongoClient(mongo_connection_string)
self.db = self.... |
def coords_grid(batch, ht, wd, device):
coords = torch.meshgrid(torch.arange(ht, device=device), torch.arange(wd, device=device))
coords = torch.stack(coords[::(- 1)], dim=0).float()
return coords[None].repeat(batch, 1, 1, 1) |
class ConvBertTokenizer(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... |
class MultiScaleRandomCrop(object):
def __init__(self, scales, size, interpolation=Image.BILINEAR):
self.scales = scales
self.size = size
self.interpolation = interpolation
def __call__(self, img):
min_length = min(img.size[0], img.size[1])
crop_size = int((min_length * s... |
def _conjugate_gradient(f_Ax, b, cg_iters, residual_tol=1e-10):
p = b.clone()
r = b.clone()
x = torch.zeros_like(b)
rdotr = torch.dot(r, r)
for _ in range(cg_iters):
z = f_Ax(p)
v = (rdotr / torch.dot(p, z))
x += (v * p)
r -= (v * z)
newrdotr = torch.dot(r, r)... |
def test_recursive_true_and_corrupt_file_ignored():
dataloader = _init_dataloader(imdir=NESTED_IMAGE_DIR, recursive=True)
(all_filenames, ims_arr, all_bad_images) = _iterate_over_dataloader(dataloader)
all_ims = torch.stack(ims_arr)
assert (all_ims.shape == tuple([5, 3, 224, 224]))
assert (len(all_f... |
def filter_answers(answers_dset, min_occurence):
occurence = {}
for ans_entry in answers_dset:
answers = ans_entry['answers']
gtruth = ans_entry['multiple_choice_answer']
gtruth = preprocess_answer(gtruth)
if (gtruth not in occurence):
occurence[gtruth] = set()
... |
class FactorizedAntisymmetry(Module):
spin_split: ParticleSplit
compute_input_streams: ComputeInputStreams
backflow: Backflow
jastrow: Jastrow
rank: int
ndense_resnet: int
nlayers_resnet: int
kernel_initializer_resnet: WeightInitializer
bias_initializer_resnet: WeightInitializer
... |
class RolloutBaseline(Baseline):
def __init__(self, model, problem, opts, epoch=0):
super(Baseline, self).__init__()
self.problem = problem
self.opts = opts
self._update_model(model, epoch)
def _update_model(self, model, epoch, dataset=None):
self.model = copy.deepcopy(mo... |
def resnet152(pretrained=False, progress=True, **kwargs):
return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress, **kwargs) |
def staged_forward(fixed_exp_z, fixed_id_z, fixed_noise_z, generator_ddp, deform_ddp, vae_net_id, vae_net_exp, stage, alpha, metadata, opt):
device = fixed_exp_z.device
img_size = metadata['img_size']
batch_size = fixed_exp_z.shape[0]
z_exp = fixed_exp_z
z_id = fixed_id_z
noise = fixed_noise_z
... |
_tf
class TestTFPegasusCommon(TFModelTesterMixin, unittest.TestCase):
all_model_classes = ((TFPegasusForConditionalGeneration,) if is_tf_available() else ())
all_generative_model_classes = ((TFPegasusForConditionalGeneration,) if is_tf_available() else ())
model_tester_cls = ModelTester
is_encoder_decod... |
def hard_attention_arc_eager_decoder(decoder_inputs, encoder_inputs, initial_state, attention_states, cell, predict_end_attention=True, decoder_vocab_sizes=None, output_size=None, num_heads=1, embed_functions=None, loop_functions=None, output_projections=None, transition_state_map=None, dtype=tf.float32, scope=None, in... |
_model
def nf_regnet_b5(pretrained=False, **kwargs):
return _create_normfreenet('nf_regnet_b5', pretrained=pretrained, **kwargs) |
def download_and_extract():
dest_directory = DATA_DIR
if (not os.path.exists(dest_directory)):
os.makedirs(dest_directory)
filename = DATA_URL.split('/')[(- 1)]
filepath = os.path.join(dest_directory, filename)
if (not os.path.exists(filepath)):
def _progress(count, block_size, total... |
_start_docstrings('XLM-RoBERTa Model with a token classification head on top (a linear layer on top of\n the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. ', XLM_ROBERTA_START_DOCSTRING)
class XLMRobertaForTokenClassification(RobertaForTokenClassification):
config_class = XLMRobertaConfig |
class EpanechnikovProposal(Proposal):
def density(self, z):
return (0.75 * (1 - (z ** 2)))
def kl(self, m, s):
return ((((((0.5 * (m ** 2)) + ((s ** 2) / 10)) - torch.log((s + self.eps))) + (0.5 * np.log((2 * np.pi)))) - (5 / 3)) + np.log(3)).sum(1)
def kl_uniform(self, m, s):
return... |
def batchify_distributed(data, bsz, args, epoch):
np.random.seed(epoch)
pointer = np.random.randint(0, len(data))
data = torch.cat((data[pointer:], data[0:pointer]), dim=0)
num_replicas = dist.get_world_size()
rank = dist.get_rank()
num_samples = int(math.ceil(((data.size(0) * 1.0) / num_replica... |
def create_angle_grid():
w = np.linspace((- 1), 1, 128)
agl_grid = np.degrees(np.arcsin(w))
return agl_grid |
def build_dataset(cfg, default_args=None):
from .dataset_wrappers import ConcatDataset, MultiImageMixDataset, RepeatDataset
if isinstance(cfg, (list, tuple)):
dataset = ConcatDataset([build_dataset(c, default_args) for c in cfg])
elif (cfg['type'] == 'RepeatDataset'):
dataset = RepeatDataset... |
class EltwiseSubEmbed(nn.Module):
def __init__(self, nonlinearity='square', use_batch_norm=False, use_classifier=False, num_features=0, num_classes=0):
super(EltwiseSubEmbed, self).__init__()
self.nonlinearity = nonlinearity
if ((nonlinearity is not None) and (nonlinearity not in ['square', ... |
class DatasetManger(metaclass=ABCMeta):
def __init__(self, task_type, batch_size, dataset_splitter: DatasetSplitter):
self.todo: List[Task] = []
self.doing: Dict[(int, DoingTask)] = {}
self._task_type = task_type
self._batch_size = batch_size
self._dataset_splitter = dataset_... |
class T5Converter(SpmConverter):
def vocab(self, proto):
num_extra_ids = self.original_tokenizer._extra_ids
vocab = [(piece.piece, piece.score) for piece in proto.pieces]
vocab += [(f'<extra_id_{i}>', 0.0) for i in range((num_extra_ids - 1), (- 1), (- 1))]
return vocab
def post_p... |
class CarBikeCollision(Scenario):
def init_scene(self, prefix, settings=None, spectator_tr=None):
super().init_scene(prefix, settings, spectator_tr)
blueprint_library = self.world.get_blueprint_library()
car_tr = carla.Transform(carla.Location(50, (- 255), 0.04), carla.Rotation(yaw=0))
... |
def get_dl(mode: str, cfg_ds: dict, cfg_dl: dict) -> DataLoader:
ds = get_ds(cfg_ds, mode)
ds = list(ds.values())
cfg = ({k: v for (k, v) in cfg_dl.items() if (k not in {'train', 'val', 'test'})} | cfg_dl.get(mode, {}))
cfg['pin_memory'] = cfg.get('pin_memory', True)
cfg['collate_fn'] = ds[0].collat... |
class Data2VecTextConfig(PretrainedConfig):
model_type = 'data2vec-text'
def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_voc... |
def assert_keys_equal(result_keys: List[str], target_keys: List[str]) -> bool:
return (set(result_keys) == set(target_keys)) |
class ValueBFS(Search):
def __init__(self, forward_predictor: ForwardPredictor, forward_enumerator: ForwardEnumerator, value_heuristic: ValueHeuristic, action_enumerator: ActionEnumerator, random_state_enumerator: RandomStateEnumerator, random_state_predictor: RandomStatePredictor, opponent_action_enumerator: Oppon... |
class DownsampleB(nn.Module):
def __init__(self, nIn, nOut, stride):
super(DownsampleB, self).__init__()
self.avg = nn.AvgPool2d(stride)
self.expand_ratio = (nOut // nIn)
def forward(self, x):
x = self.avg(x)
return torch.cat(([x] + ([x.mul(0)] * (self.expand_ratio - 1)))... |
def get_network_fn(name, num_classes, weight_decay=0.0, is_training=False):
if (name not in networks_map):
raise ValueError(('Name of network unknown %s' % name))
func = networks_map[name]
(func)
def network_fn(images):
arg_scope = arg_scopes_map[name](weight_decay=weight_decay)
... |
def has_metadata_cell(cells, fn):
for c in cells:
if re.search(f"update_nb_metadata\('{fn}'", c['source']):
return c |
_builder('vizwiz')
class VizWizBuilder(VQA2Builder):
def __init__(self):
super().__init__()
self.dataset_name = 'vizwiz'
self.set_dataset_class(VizWizDataset)
def update_registry_for_model(self, config):
super().update_registry_for_model(config) |
def compute_progress(dir, iter, egs_dir, run_opts, get_raw_nnet_from_am=True):
suffix = ('mdl' if get_raw_nnet_from_am else 'raw')
prev_model = '{0}/{1}.{2}'.format(dir, (iter - 1), suffix)
model = '{0}/{1}.{2}'.format(dir, iter, suffix)
common_lib.background_command("{command} {dir}/log/progress.{iter}... |
def GetUpdate(observe, collector, return_to_original_position=True):
go_to_js = GetPlanToJointStateService()
req = GetHomeRequest()
servo_mode = GetServoModeService()
def update():
q0 = collector.q
servo_mode('servo')
max_tries = 10
tries = 0
res = None
wh... |
class FPN(Backbone):
_fuse_type: torch.jit.Final[str]
def __init__(self, bottom_up, in_features, out_channels, norm='', top_block=None, fuse_type='sum', square_pad=0):
super(FPN, self).__init__()
assert isinstance(bottom_up, Backbone)
assert in_features, in_features
input_shapes ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.