code stringlengths 101 5.91M |
|---|
class BytecodeCache(object):
def load_bytecode(self, bucket):
raise NotImplementedError()
def dump_bytecode(self, bucket):
raise NotImplementedError()
def clear(self):
def get_cache_key(self, name, filename=None):
hash = sha1(name.encode('utf-8'))
if (filename is not None... |
class CloseConstituent(Transition):
def delta_opens(self):
return (- 1)
def update_state(self, state, model):
children = []
constituents = state.constituents
while (not isinstance(model.get_top_constituent(constituents), Dummy)):
children.append(constituents.value)
... |
def _do_matlab_eval(json_dataset, salt, output_dir='output'):
import subprocess
logger.info('')
logger.info('Computing results with the official MATLAB eval code.')
logger.info('')
info = voc_info(json_dataset)
path = os.path.join(cfg.ROOT_DIR, 'lib', 'datasets', 'VOCdevkit-matlab-wrapper')
... |
.torch
def test_sasrec_predictions(tensor_schema, simple_masks):
model = SasRecModel(tensor_schema.subset(['item_id']), hidden_size=64, max_len=5)
(item_sequences, padding_mask, _, _) = simple_masks
inputs = {'item_id': item_sequences}
predictions_by_one = model.predict(inputs, padding_mask, torch.tenso... |
def logical_or(a, b):
return _binary_operation(_ti_core.expr_logical_or, (lambda a, b: (a or b)), a, b) |
class RemBertConfig(PretrainedConfig):
model_type = 'rembert'
def __init__(self, vocab_size=250300, hidden_size=1152, num_hidden_layers=32, num_attention_heads=18, input_embedding_size=256, output_embedding_size=1664, intermediate_size=4608, hidden_act='gelu', hidden_dropout_prob=0.0, attention_probs_dropout_pr... |
class TestSearchBitwidthConfiguration(unittest.TestCase):
def run_search_bitwidth_config_test(self, core_config):
(base_config, mixed_precision_cfg_list) = get_op_quantization_configs()
base_config = base_config.clone_and_edit(enable_activation_quantization=False)
tpc = get_weights_only_mp_t... |
def get_datasets_for_test(P):
test_transform = get_test_transform()
benchmark = P.dataset
file_path = f'data/data_txt/{benchmark}/{P.test_domain}.txt'
target_ds = FileDataset(benchmark, file_path, test_transform, add_idx=True)
if (benchmark == 'OfficeHome'):
source_name = f'no_{P.test_domain... |
def p2_2partitions(model='wrn_28x10_c100_dr03_p2'):
csv = '2partitions.csv'
out_file_name = f'{model}_output.png'
out_file_name = os.path.join('.', out_file_name)
df = pd.read_csv(csv).query("dataset == 'cifar100' and model == ").query('epoch == 200')
ax = sns.barplot(x='epoch', y='test_acc', hue='a... |
def create_model_4(input_shape):
random_uniform = initializers.random_uniform(0, 1)
inputs = Input(shape=input_shape)
x = Conv2D(2, 3, padding='same', name='conv2d')(inputs)
x_bn = BatchNormalization(gamma_initializer='random_normal', beta_initializer='random_normal', moving_mean_initializer='random_nor... |
_function_dispatch(_linspace_dispatcher)
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):
num = _index_deprecate(num)
if (num < 0):
raise ValueError(('Number of samples, %s, must be non-negative.' % num))
div = ((num - 1) if endpoint else num)
start = (asanyar... |
def create_dummy_data(data_dir, num_examples=1000, maxlen=20, alignment=False):
def _create_dummy_data(filename):
data = torch.rand((num_examples * maxlen))
data = (97 + torch.floor((26 * data)).int())
with open(os.path.join(data_dir, filename), 'w') as h:
offset = 0
... |
def evaluate_on_saved_data(args, data_loader, epoch):
total_lsd = 0
total_visqol = 0
lsd_count = 0
visqol_count = 0
total_cnt = 0
files_to_log = []
wandb_n_files_to_log = (args.wandb.n_files_to_log if ('wandb' in args) else args.wandb_n_files_to_log)
with torch.no_grad():
iterato... |
def test_rpad_listoffset_array():
content = ak.contents.numpyarray.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]))
offsets = ak.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))
listoffsetarray = ak.contents.listoffsetarray.ListOffsetArray(offsets, content)
assert (to_list(listof... |
class ManglingDomainBase(object):
directive_mangling_map = {}
def __init__(self, *a, **kw):
super(ManglingDomainBase, self).__init__(*a, **kw)
self.wrap_mangling_directives()
def wrap_mangling_directives(self):
for (name, objtype) in self.directive_mangling_map.items():
s... |
class DepLabelDataset(PosTagDataset):
def load_data_index(self):
data_ud = util.read_data((self.input_name_base % (self.mode, 'ud')))
(x_raw, y_raw) = ([], [])
for (sentence_ud, words) in data_ud:
for (i, token) in enumerate(sentence_ud):
head = token['head']
... |
def get_checkpoints_for_epochs(experiment_folder: Path, epochs: Union[(List, str)]) -> List:
if isinstance(epochs, str):
epochs = epochs.split(',')
epochs = list(map(int, epochs))
ep = (lambda s: int(s.stem.split('=')[1]))
return [chk for chk in get_all_checkpoints(experiment_folder) if (ep(... |
def auto_augment_transform(config_str, hparams):
config = config_str.split('-')
policy_name = config[0]
config = config[1:]
for c in config:
cs = re.split('(\\d.*)', c)
if (len(cs) < 2):
continue
(key, val) = cs[:2]
if (key == 'mstd'):
hparams.setd... |
class IsotopicMassFraction(pd.DataFrame):
_metadata = ['time_0']
def __init__(self, *args, **kwargs):
if ('time_0' in kwargs):
time_0 = kwargs['time_0']
kwargs.pop('time_0')
else:
time_0 = (0 * u.d)
super(IsotopicMassFraction, self).__init__(*args, **k... |
class _BatchNorm(_NormBase):
def __init__(self, num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True):
super(_BatchNorm, self).__init__(num_features, eps, momentum, affine, track_running_stats)
def forward(self, input: Tensor) -> Tensor:
self._check_input_dim(input)
... |
def is_nominal(dtype: Any) -> bool:
if (is_continuous(dtype) or is_datetime(dtype)):
return False
if isinstance(dtype, np.dtype):
dtype = dtype.type
return any((issubclass(dtype, c) for c in CATEGORICAL_NUMPY_DTYPES))
else:
return any((isinstance(dtype, c) for c in CATEGORICA... |
def make_lr_scheduler(cfg, optimizer):
return WarmupMultiStepLR(optimizer, cfg.SOLVER.STEPS, cfg.SOLVER.GAMMA, warmup_factor=cfg.SOLVER.WARMUP_FACTOR, warmup_iters=cfg.SOLVER.WARMUP_ITERS, warmup_method=cfg.SOLVER.WARMUP_METHOD) |
class AstToTestCaseTransformer(ast.NodeVisitor):
def __init__(self, test_cluster: ModuleTestCluster, create_assertions: bool, constant_provider: ConstantProvider):
self._current_testcase: dtc.DefaultTestCase = dtc.DefaultTestCase(test_cluster)
self._current_parsable: bool = True
self._var_re... |
def boundary_handle(pos: ti.types.ndarray(ndim=1), vel: ti.types.ndarray(ndim=1), boundary_box: ti.types.ndarray(ndim=1)):
for i in range(particle_num):
collision_normal = ti.Vector([0.0, 0.0, 0.0])
for j in ti.static(range(3)):
if (pos[i][j] < boundary_box[0][j]):
pos[i]... |
def psp_block(prev_layer, level, feature_map_shape, input_shape):
if (input_shape == (512, 512)):
kernel_strides_map = {1: [64, 64], 2: [32, 32], 3: [22, 21], 6: [11, 9]}
else:
raise ValueError((('Pooling parameters for input shape ' + input_shape) + ' are not defined.'))
if (K.image_data_fo... |
def count_params(model: tf.keras.models.Model) -> int:
return int(sum((np.prod(p.shape.as_list()) for p in model.trainable_weights))) |
class DEAPQDAlgorithm(object):
def __init__(self, toolbox, container=None, stats=None, halloffame=None, iteration_filename='iteration-%i.p', final_filename='final.p', ea_fn=qdSimple, cxpb=0.0, mutpb=1.0, verbose=False, results_infos=None, log_base_path='.', save_period=None, iteration_callback_fn=None, **kwargs):
... |
def loss_fn(x, y):
x = F.normalize(x, dim=(- 1), p=2)
y = F.normalize(y, dim=(- 1), p=2)
return (2 - (2 * (x * y).sum(dim=(- 1)))) |
def construct_optimizer(model: torch.nn.Module, cfg: OmegaConf):
optimizer_type = cfg.train.optimizer
lr = cfg.train.lr
radius_lr_factor = cfg.train.radius_lr_factor
momentum = cfg.train.optimizer_params.momentum
nesterov = cfg.train.optimizer_params.nesterov
(others, radius, no_decay) = ([], []... |
def _calc_estimate_time(timeinfo, max_iter, last_iter, iter):
timeinfo.past_time = (time.time() - timeinfo.start_time)
timeinfo.estimate_time = ((timeinfo.past_time * (max_iter - last_iter)) / (iter - last_iter))
timeinfo.remain_time = (timeinfo.estimate_time - timeinfo.past_time)
timeinfo.last_past_tim... |
def test_random(env, nb_episodes, nb_dims=2, gif=False, score_step=1000, verbose=True, params={}):
scores = []
gif_step_size = 250
bk = {'comp_grids': [], 'comp_xs': [], 'comp_ys': [], 'tasks': []}
for i in range((nb_episodes + 1)):
if ((i % score_step) == 0):
scores.append(env.get_s... |
class AlgebraicReal(AlgebraicNumber_base):
def __init__(self, x):
AlgebraicNumber_base.__init__(self, AA, x)
self._ensure_real()
def _ensure_real(self):
if is_ComplexIntervalFieldElement(self._value):
self._value = self._value.real()
def _more_precision(self):
Alg... |
def check_ieee_macros(config):
priv = []
pub = []
macros = []
def _add_decl(f):
priv.append(fname2def(('decl_%s' % f)))
pub.append(('NPY_%s' % fname2def(('decl_%s' % f))))
_macros = ['isnan', 'isinf', 'signbit', 'isfinite']
for f in _macros:
py_symbol = fname2def(('decl_%... |
def GenerateSM60_Simt(manifest, cuda_version):
layouts = [(LayoutType.ColumnMajor, LayoutType.ColumnMajor, LayoutType.ColumnMajor), (LayoutType.ColumnMajor, LayoutType.RowMajor, LayoutType.ColumnMajor), (LayoutType.RowMajor, LayoutType.ColumnMajor, LayoutType.ColumnMajor), (LayoutType.RowMajor, LayoutType.RowMajor,... |
class stanford_params():
def __init__(self):
self.class_freq = np.asarray([19.203, 16.566, 27.329, 2.428, 2.132, 2.123, 5.494, 3.25, 4.079, 0.488, 4.726, 1.264, 10.918, 100.0])
self.class_weights = (- np.log((self.class_freq / 100.0)))
self.num_classes = (len(self.class_freq) + 1)
se... |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, norm_type='batch', stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv_stride1(inplanes, planes, kernel_size=3, norm_type=norm_type)
self.bn1 = normalization(planes, norm_type)
... |
def _get_resource(resources, resource_name):
if ((resource_name not in resources) or (resources[resource_name] is None)):
raise MissingResource(("Resource '%s' not found" % resource_name))
return resources[resource_name] |
class EvaluateParser(JavaProtobufContext):
def __init__(self, classpath=None, kbest=None, silent=False):
if (kbest is not None):
extra_args = ['-evalPCFGkBest', '{}'.format(kbest), '-evals', 'pcfgTopK']
else:
extra_args = []
if silent:
extra_args.extend(['... |
def test_gmm_e2e():
gmm = learn_gmm(np.random.random((100, 64)), n_modes=5)
assert (gmm.means_ is not None)
assert (gmm.covariances_ is not None)
assert (gmm.weights_ is not None) |
class TestPadding(TestCase):
(batch_size=st.integers(1, 64), channels=st.integers(1, 64), width=st.integers(16, 128), qtype=st.sampled_from(hu._ALL_QINT_TYPES))
def test_reflection_pad1d(self, batch_size, channels, width, qtype):
padding = (width // 4)
x = torch.arange(((batch_size * channels) *... |
def clipped_error(x):
return tf.where((tf.abs(x) < 1.0), (0.5 * tf.square(x)), (tf.abs(x) - 0.5)) |
def test__extract_geometry(h3_tess):
extracted_geometry = h3_tess._extract_geometry(bbox)
assert (extracted_geometry['type'] == 'Polygon') |
def parse_args():
parser = argparse.ArgumentParser(description='Train a model')
parser.add_argument('config', help='train config file path')
args = parser.parse_args()
return args |
class DWConv(nn.Module):
def __init__(self, dim):
super().__init__()
self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, groups=dim)
def forward(self, x: Tensor, H, W) -> Tensor:
(B, _, C) = x.shape
x = x.transpose(1, 2).view(B, C, H, W)
x = self.dwconv(x)
return x.flatten... |
def evaluate(model, batches):
model.eval()
meters = collections.defaultdict((lambda : AverageMeter()))
with torch.no_grad():
for (inputs, targets) in batches:
losses = model.autoenc(inputs, targets)
for (k, v) in losses.items():
meters[k].update(v.item(), inpu... |
def get(dataset, crop_size, batch_size, min_resize_value=None, max_resize_value=None, resize_factor=None, min_scale_factor=1.0, max_scale_factor=1.0, scale_factor_step_size=0, num_readers=1, num_threads=1, dataset_split=None, is_training=True, model_variant=None):
if (dataset_split is None):
raise ValueErro... |
def _workers(workers):
if (workers is None):
return getattr(_config, 'default_workers', 1)
if (workers < 0):
if (workers >= (- _cpu_count)):
workers += (1 + _cpu_count)
else:
raise ValueError('workers value out of range; got {}, must not be less than {}'.format(wo... |
def _tested_estimators():
for (name, Estimator) in all_estimators():
try:
estimator = _construct_instance(Estimator)
set_random_state(estimator)
except SkipTest:
continue
if isinstance(estimator, NearMiss):
for version in (1, 2, 3):
... |
class DropboxDeleteItem(VirtualFunctionTool):
name = 'DropboxDeleteItem'
summary = "Delete a file or folder from the user's Dropbox account."
parameters: List[ArgParameter] = [{'name': 'item_path', 'type': 'string', 'description': "The cloud file or folder path in the user's Dropbox account to be deleted.",... |
class ParserImageInTar(Parser):
def __init__(self, root, class_map='', cache_tarfiles=True, cache_tarinfo=None):
super().__init__()
class_name_to_idx = None
if class_map:
class_name_to_idx = load_class_map(class_map, root)
self.root = root
(self.samples, self.targ... |
def de_vectorize_field_ptr(vec_cpu, rev_vocab, memory, schema, table_po=None, field_po=None, post_process=None, return_tokens=False):
tokens = []
for j in range(len(vec_cpu)):
token_id = int(vec_cpu[j])
if ((j == 0) and (token_id == rev_vocab.start_id)):
continue
if ((token_i... |
class BridgeLayer(nn.Module):
def __init__(self, enc_hidden_size, dec_hidden_size):
super(BridgeLayer, self).__init__()
self.input_size = enc_hidden_size
self.output_size = dec_hidden_size
self.proj_layer = nn.Linear(self.input_size, self.output_size)
def forward(self, enc_final_... |
def get_strongly_connected_components(dependencies):
sorted_vars = sorted(dependencies.derived_variables)
variable_to_index = {var: index for (index, var) in enumerate(sorted_vars)}
adjacency_list = []
for derived_var in sorted_vars:
pos = dependencies.positive_dependencies[derived_var]
... |
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 16, 3)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(16, 32, 3)
self.fc1 = nn.Linear(((32 * 5) * 5), 32)
self.fc2 = nn.Linear(32, 84)
self.fc3 = nn.Linear(8... |
class GEM(keras.Model):
def __init__(self, input_dim, output_dim, args):
super().__init__()
self.nodes_num = args.nodes_num
self.class_size = args.class_size
self.input_dim = input_dim
self.output_dim = output_dim
self.device_num = args.device_num
self.hop = a... |
def compute_head_information(attributes):
mention_subtree = attributes['parse_tree']
head_finder = head_finders.HeadFinder()
head_index = 0
head = [attributes['tokens'][0]]
if (len(mention_subtree.leaves()) == len(attributes['tokens'])):
head_tree = head_finder.get_head(mention_subtree)
... |
_utils.test(arch=archs_support_ndarray_ad, require=ti.extension.adstack)
def test_multiple_ib_deeper():
x = ti.ndarray(float, (), needs_grad=True)
y = ti.ndarray(float, (), needs_grad=True)
def compute_y(x: ti.types.ndarray(), y: ti.types.ndarray()):
for j in range(2):
for i in range(3):... |
class Theta(nn.Module):
def __init__(self, n_comp=100, T=431, num_classes=50):
super().__init__()
self.hard_att = nn.Linear(T, 1, bias=False)
self.classifier = nn.Sequential(nn.Linear(n_comp, num_classes, bias=False), nn.Softmax(dim=1))
def forward(self, H):
theta_out = self.hard... |
class RandomMaskingGenerator():
def __init__(self, input_size, mask_ratio):
(self.frames, self.height, self.width) = input_size
self.total_patches = ((self.frames * self.height) * self.width)
self.num_masks = int((mask_ratio * self.total_patches))
self.total_masks = self.num_masks
... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('sections', type=str, nargs='*', help='Which transformations to use: {}'.format(' '.join(ARGUMENTS.keys())))
args = parser.parse_args()
if (not args.sections):
args.sections = list(ARGUMENTS.keys())
return args |
def get_optimizer(args, params_list, **options):
if (args.optim is None):
if (options['dataset'] == 'tinyimagenet'):
optimizer = torch.optim.Adam(params_list, lr=args.lr)
else:
optimizer = torch.optim.SGD(params_list, lr=args.lr, momentum=0.9, weight_decay=args.weight_decay)
... |
class PruningException(Exception):
_node: Node
def __init__(self, message, node):
super().__init__(message)
self._node = node
def node(self):
return self._node |
class TFLEDForConditionalGeneration():
def __init__(self, *args, **kwargs):
requires_tf(self)
def from_pretrained(self, *args, **kwargs):
requires_tf(self) |
def test_scanvi_predict_use_posterior_mean():
adata = synthetic_iid()
SCANVI.setup_anndata(adata, labels_key='labels', unlabeled_category='label_0')
model = SCANVI(adata)
model.train(max_epochs=1)
_ = model.predict(use_posterior_mean=True)
_ = model.predict(use_posterior_mean=False) |
def compile_dense_field_aot_test(arch):
ti.init(arch)
if (ti.lang.impl.current_cfg().arch != arch):
return
n = 10
place = ti.field(ti.i32, shape=(n,))
def simple_return() -> ti.f32:
sum = 0.2
return sum
def init():
for index in range(n):
place[index] =... |
def mkdir_p(folder_path):
try:
makedirs(folder_path)
except OSError as exc:
if ((exc.errno == EEXIST) and path.isdir(folder_path)):
pass
else:
raise |
def test_sanitize_output(case_factory, request_factory):
response = Response()
response.headers = {'API-Key': 'secret'}
response.request = request_factory(headers={'Custom-Token': 'custom_token_value'})
case = case_factory(headers={'Authorization': 'Bearer token'}, query={'api_key': '12345'})
saniti... |
class BaseBadSampler(BaseEstimator):
_sampling_type = 'bypass'
def fit(self, X, y):
return self
def fit_resample(self, X, y):
check_classification_targets(y)
self.fit(X, y)
return (X, y) |
def test_histosys_additional_properties():
spec = {'channels': [{'name': 'channel', 'samples': [{'name': 'sample', 'data': [10.0], 'modifiers': [{'name': 'histosys', 'type': 'histosys', 'data': {'hi_data': [1.0], 'lo_data': [0.5], 'foo': 2.0}}]}]}]}
with pytest.raises(pyhf.exceptions.InvalidSpecification):
... |
def build_param(ctx, py_arg, self_name, kwarg_only):
name = py_arg.arg
r = ctx.make_range(py_arg.lineno, py_arg.col_offset, (py_arg.col_offset + len(name)))
if (getattr(py_arg, 'annotation', None) is not None):
annotation_expr = build_expr(ctx, py_arg.annotation)
elif ((self_name is not None) an... |
def _decode_value(value):
if (not isinstance(value, str)):
return value
if (value == 'None'):
value = None
try:
value = literal_eval(value)
except ValueError:
pass
except SyntaxError:
pass
return value |
class MlpAttention(Attention):
def __init__(self, query_size, key_size, out_size=100, dropout=0):
super(MlpAttention, self).__init__(dropout)
self.query_projection = nn.Linear(query_size, out_size)
self.key_projection = nn.Linear(key_size, out_size)
self.v = nn.Parameter(torch.FloatT... |
_node_type()
class PlaneWaveSource(optplan.EmSource):
type = schema_utils.polymorphic_model_type('source.plane_wave')
center = optplan.vec3d()
extents = optplan.vec3d()
normal = optplan.vec3d()
theta = types.FloatType()
psi = types.FloatType()
polarization_angle = types.FloatType()
overw... |
class HierarchyLinkage(Benchmark):
params = ['single', 'complete', 'average', 'weighted', 'centroid', 'median', 'ward']
param_names = ['method']
def __init__(self):
rnd = np.random.RandomState(0)
self.X = rnd.randn(2000, 2)
def time_linkage(self, method):
linkage(self.X, method=m... |
def _memoize_get_funcs(func):
memo = {}
func.memo = memo
(func)
def getter(names, arrays=(), dtype=None):
key = (names, dtype)
for array in arrays:
key += (array.dtype.char, array.flags.fortran)
try:
value = memo.get(key)
except TypeError:
... |
def meta_net(x, params):
x = F.linear(x, params[0], params[1])
x1 = F.relu(x)
x = F.linear(x1, params[2], params[3])
x2 = F.relu(x)
y = F.linear(x2, params[4], params[5])
return (y, x2, x1) |
class DialogsReader(object):
def __init__(self, dialogs_jsonpath: str):
with open(dialogs_jsonpath, 'r') as visdial_file:
visdial_data = json.load(visdial_file)
self._split = visdial_data['split']
self.captions = {}
self.dialogs = {}
self.num_round... |
class chamferDist(nn.Module):
def __init__(self):
super(chamferDist, self).__init__()
def forward(self, input1, input2):
return chamferFunction.apply(input1, input2) |
def split_sequence(sequence):
(X, y) = (list(), list())
for i in range(len(sequence)):
end_ix = (i + w)
out_end_ix = (end_ix + p_w)
if (out_end_ix > len(sequence)):
break
(seq_x, seq_y) = (sequence[i:end_ix], sequence[end_ix:out_end_ix])
X.append(seq_x)
... |
def main(argv=None):
if (FLAGS.non_linearity == 'tanh'):
non_linearity = tf.nn.tanh
elif (FLAGS.non_linearity == 'sigmoid'):
non_linearity = tf.nn.sigmoid
else:
non_linearity = myrelu
args = parseArgs()
adam_beta1 = args.adam_beta1
adam_beta2 = args.adam_beta2
learnin... |
class A000302(SloaneSequence):
def __init__(self):
SloaneSequence.__init__(self, offset=0)
def _repr_(self):
return 'Powers of 4: a(n) = 4^n.'
def _eval(self, n):
return ZZ((4 ** n)) |
def prepare_sentence(sent):
ret_str = []
ret_box_seq = []
for word in sent:
if isinstance(word, list):
ret_str.append(BOXES_PLACEHOLDER)
ret_box_seq.append(word)
else:
ret_str.append(word)
return (' '.join(ret_str), ret_box_seq) |
class TestCheckpointUtils(unittest.TestCase):
def setUp(self):
logging.disable(logging.CRITICAL)
def tearDown(self):
logging.disable(logging.NOTSET)
def _train_transformer(self, seed, extra_args=None):
if (extra_args is None):
extra_args = []
with tempfile.Tempora... |
class QuestionAnsweringPipeline(Pipeline):
default_input_names = 'question,context'
def __init__(self, model, tokenizer: Optional[PreTrainedTokenizer], modelcard: Optional[ModelCard], framework: Optional[str]=None, device: int=(- 1), **kwargs):
super().__init__(model=model, tokenizer=tokenizer, modelcar... |
class NnpExpander():
def __init__(self, nnp):
self._nnp = nnp
self._parameters = {}
for param in self._nnp.parameter:
self._parameters[param.variable_name] = True
def _expand_repeat(self, network):
def _search_repeat_id(mes, rid):
return (list(mes.repeat_i... |
def test_reassign():
def shouldfail(A: dace.float64[20], B: dace.float64[30], selector: dace.int32):
if (selector == 0):
tmp = np.empty_like(A)
tmp[:] = A
return tmp
else:
tmp = np.empty_like(B)
tmp[:] = B
return tmp[0:20]
w... |
class RecurrentCapsuleNetwork(CapsuleNetwork):
def __init__(self, embedding, aspect_embedding, num_layers, bidirectional, capsule_size, dropout, num_categories):
super(RecurrentCapsuleNetwork, self).__init__(embedding=embedding, aspect_embedding=aspect_embedding, hidden_size=(embedding.embedding_dim * (2 if... |
def test_indexedarray():
layout = ak.from_buffers({'class': 'IndexedArray', 'index': 'i64', 'content': {'class': 'NumpyArray', 'primitive': 'int64', 'form_key': 'node1'}, 'form_key': 'node0'}, 3, {'node0-index': np.array([0, 1, 2], dtype=np.int64), 'node1-data': PlaceholderArray(numpy, (3,), np.int64)}, highlevel=F... |
(name='kendalltau-scipy', pure=True)
def kendalltau(a: np.ndarray, b: np.ndarray) -> np.ndarray:
corr = kendalltau_(a, b).correlation
return np.float64(corr) |
def GetBfsEffDiam(tspec, *args):
if (type(tspec) == PUNGraph):
return GetBfsEffDiam_PUNGraph(tspec, *args)
if (type(tspec) == PUndirNet):
return GetBfsEffDiam_PUndirNet(tspec, *args)
if (type(tspec) == PDirNet):
return GetBfsEffDiam_PDirNet(tspec, *args)
if (type(tspec) == PNGrap... |
class Array(np.ndarray):
def __new__(cls, array, meta=None):
if (not isinstance(array, np.ndarray)):
raise ValueError('Array expects a numpy array.')
if (not ((meta is None) or isinstance(meta, dict))):
raise ValueError('Array expects meta data to be a dict.')
meta = ... |
.gpu
def test_batchmm():
(b, m, n, k) = tuple((dace.symbol(k) for k in 'bmnk'))
with change_default(blas, 'cuBLAS'):
def bmmtest(A: dace.float64[(b, m, k)], B: dace.float64[(b, k, n)], C: dace.float64[(b, m, n)]):
C[:] = (A B)
sdfg = bmmtest.to_sdfg()
sdfg.apply_gpu_transfor... |
def construct_train_loader(args, dataset=None):
if args.distributed:
drop_last = True
else:
drop_last = False
return _construct_loader(args=args, split='train', batch_size=int((args.batch_size / args.num_gpus)), shuffle=True, drop_last=drop_last, dataset=(dataset if dataset else args.dataset... |
class PairProcessor(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.tsv')), 'dev')
... |
def get_img_output_length(width, height):
def get_output_length(input_length):
input_length += 6
filter_sizes = [7, 3, 1, 1]
stride = 2
for filter_size in filter_sizes:
input_length = (((input_length - filter_size) + stride) // stride)
return input_length
retu... |
def _infer_semantic_data_type(column: pd.Series) -> Any:
column_not_na = column[column.apply(_check_valid_values, 0)]
sample_size = (column_not_na.size if (column_not_na.size <= 100) else min(int((0.1 * column_not_na.size)), 500))
column_not_na_subset = column_not_na.sample(n=sample_size, random_state=1)
... |
def convert_question_into_desc(qa_pair):
predicate = get_predicate(qa_pair['question'])
return predicate |
class LossScaler():
def __init__(self, scale=1):
self.cur_scale = scale
def has_overflow(self, params):
return False
def _has_inf_or_nan(x):
return False
def update_scale(self, overflow):
pass
def loss_scale(self):
return self.cur_scale
def scale_gradient(... |
class SimpleStem(CNNBlockBase):
def __init__(self, w_in, w_out, norm, activation_class):
super().__init__(w_in, w_out, 2)
self.conv = conv2d(w_in, w_out, 3, stride=2)
self.bn = get_norm(norm, w_out)
self.af = activation_class()
def forward(self, x):
for layer in self.chil... |
def create_r_distance(distance):
def r_distance(tn, t):
return [('distance', tn[0], (lambda : distance))]
return r_distance |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.