code stringlengths 101 5.91M |
|---|
def transform_epbcs(adict, prefix='epbc'):
d2 = {}
for (ii, (key, conf)) in enumerate(six.iteritems(adict)):
if isinstance(conf, tuple):
if (len(conf) == 3):
c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match'])
else:
c2 = tuple_to_conf(key, c... |
def filter_tapaco(cosine_low=0.0, cosine_high=0.8, edit_high=70, diff_ratio=1.0, min_len=5):
texts = []
labels = []
with open('../data/processed_datasets/tapaco/tapaco_train_score.tsv') as f:
for line in f:
line = line.rstrip('\n')
(text, paraphrase, cosine_score, edit_distan... |
class DummyAlgo():
def __init__(self, action_size: int, ref_x: NDArray, ref_y: NDArray, action_scaler: Optional[ActionScaler]=None):
self.action_size = action_size
self.ref_x = ref_x
self.ref_y = ref_y
self.action_scaler = action_scaler
def predict(self, x: Observation) -> NDArra... |
def parse(exit_code, log, output):
(findings, infos) = ([], set())
cleaned_log = filter(is_relevant, log)
(errors, fails) = sb.parse_utils.errors_fails(exit_code, cleaned_log)
errors.discard('EXIT_CODE_1')
analysis_completed = False
in_tx = False
for line in log:
if in_tx:
... |
def test_case_5():
int_0 = 1235
queue_0 = module_0.Queue(int_0)
assert (f'{type(queue_0).__module__}.{type(queue_0).__qualname__}' == 'queue_example.Queue')
assert (queue_0.max == 1235)
assert (queue_0.head == 0)
assert (queue_0.tail == 0)
assert (queue_0.size == 0)
assert (f'{type(queue... |
.parametrize('lil_container', LIL_CONTAINERS)
def test_error(lil_container):
clf = svm.SVC()
X_sp = lil_container(X)
Y2 = Y[:(- 1)]
with pytest.raises(ValueError):
clf.fit(X_sp, Y2)
clf.fit(X_sp, Y)
assert_array_equal(clf.predict(T), true_result) |
class WindowDataParameter(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _WINDOWDATAPARAMETER |
def julia_plot(f=None, **kwds):
period = kwds.pop('period', None)
mandelbrot = kwds.pop('mandelbrot', True)
point_color = kwds.pop('point_color', 'tomato')
x_center = kwds.pop('x_center', 0.0)
y_center = kwds.pop('y_center', 0.0)
image_width = kwds.pop('image_width', 4.0)
max_iteration = kwd... |
class ExteriorAlgebraCoboundary(ExteriorAlgebraDifferential):
def __init__(self, E, s_coeff):
self._cos_coeff = {}
zero = E.zero()
B = E.basis()
for (k, v) in dict(s_coeff).items():
if (k[0] > k[1]):
k = sorted(k)
v = (- v)
k = ... |
class AdamDictionary(Dictionary[Dict[(str, Set[str])]]):
def __init__(self, trove_path: str, target_concepts: Collection[str]):
super().__init__(trove_path, 'AdamDictionary')
self.target_concepts = target_concepts
def get_url(self) -> str:
return '
def load(self) -> Dict[(str, Set[st... |
def empty(dir):
if os.path.isdir(dir):
shutil.rmtree(dir, ignore_errors=True)
else:
os.makedirs(dir) |
def let_model_save_mem_when_zero_grad(model: nn.Module):
def new_zero_grad(self, set_to_none: bool=True) -> None:
if getattr(self, '_is_replica', False):
warnings.warn("Calling .zero_grad() from a module created with nn.DataParallel() has no effect. The parameters are copied (in a differentiable... |
def split_text_into_sentences_by_length(text, length=512):
result = []
for i in range(0, len(text), length):
result.append((text[i:(i + length)], i))
return result |
class DEO(BaseScore):
def __call__(self, **kwargs):
logits = kwargs[self.logits_name]
labels = kwargs[self.label_name]
sensible_attribute = kwargs['sensible_attribute']
with torch.no_grad():
n = logits.shape[0]
logits_s_negative = logits[(sensible_attribute.bo... |
class SmoothValue(object):
def __init__(self, beta: float):
(self.beta, self.n, self.mov_avg) = (beta, 0, 0)
self.smooth = None
def add_value(self, val: float) -> None:
self.n += 1
self.mov_avg = ((self.beta * self.mov_avg) + ((1 - self.beta) * val))
self.smooth = (self.m... |
def get_parser():
parser = argparse.ArgumentParser(description='writes text from binarized file to stdout')
parser.add_argument('--dataset-impl', help='dataset implementation', choices=indexed_dataset.get_available_dataset_impl())
parser.add_argument('--dict', metavar='FP', help='dictionary containing known... |
def simPushStringOntoStack(stackHandle, value):
ret = lib.simPushStringOntoStack(stackHandle, value.encode('ascii'), 0)
_check_return(ret) |
class FlaxAutoModelForTokenClassification(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
class GroupedBatchSampler(BatchSampler):
def __init__(self, sampler, group_ids, batch_size):
if (not isinstance(sampler, Sampler)):
raise ValueError('sampler should be an instance of torch.utils.data.Sampler, but got sampler={}'.format(sampler))
self.sampler = sampler
self.group_... |
def _format(val: Any, output_format: str='standard', split: bool=False, errors: str='coarse') -> Any:
val = str(val)
result: Any = []
if (val in NULL_VALUES):
return [np.nan]
if (not validate_at_vnr(val)):
if (errors == 'raise'):
raise ValueError(f'Unable to parse value {val}... |
def run_search(executable, args, sas_file, plan_manager, time, memory):
complete_args = (([executable] + args) + ['--internal-plan-file', plan_manager.get_plan_prefix()])
print(('args: %s' % complete_args))
try:
exitcode = call.check_call('search', complete_args, stdin=sas_file, time_limit=time, mem... |
class ProppyEmbedder(nn.Module):
def __init__(self, dim, base_embedder, iterations, neighbor_rels, max_neighbors, aggregator):
super(ProppyEmbedder, self).__init__()
self._dim = dim
self._base_embedder = base_embedder
self._iterations = iterations
self._neighbor_rels = {x: i ... |
.parametrize('ctx, func_name', ctxs)
.parametrize('start, stop, num', test_data)
def test_linspace_forward_half(start, stop, num, ctx, func_name):
(ext, dtype) = ctx.backend[0].split(':')
assert (dtype == 'float')
ctx_h = ext_utils.get_extension_context(ext, type_config='half')
ctx_h.device_id = ctx.dev... |
.skipif((packaging.version.Version(cppyy.__version__) < packaging.version.Version('3.0.1')), reason='Awkward Array can only work with cppyy 3.0.1 or later.')
def test_array_as_type():
array = ak.Array([[{'x': 1, 'y': [1.1]}, {'x': 2, 'y': [2.2, 0.2]}], [], [{'x': 3, 'y': [3.0, 0.3, 3.3]}]])
source_code_cpp = f'... |
def _encode(s):
errors = ('surrogateescape' if six.PY3 else 'strict')
return s.encode('utf-8', errors) |
def save_model(model_dir, filename, model_params, train_params, feature_metas, feature_column_names, label_meta, feature_column_code):
pai_model_store.save_file(model_dir, filename)
pai_model_store.save_file(model_dir, '{}.pmml'.format(filename))
pai_model_store.save_file(model_dir, 'model_meta.json')
p... |
class TestBoundaryConditionAnalytics(unittest.TestCase):
def test_ana_boundary_computation(self):
hxind = [(0, 25, 1.3), (21, 12.5), (0, 25, 1.3)]
hyind = [(0, 25, 1.3), (21, 12.5), (0, 25, 1.3)]
hzind = [(0, 25, 1.3), (20, 12.5), (0, 25, 1.3)]
M3 = discretize.TensorMesh([hxind, hyin... |
def test_doors(trainer, env, cfg):
ctrl_stats_fname = f'{cfg.log_dir}/hole_stats.pkl'
if (LOAD_STATS and os.path.isfile(ctrl_stats_fname)):
ctrl_stats = pickle.load(open(ctrl_stats_fname, 'rb'))
print(f'Loaded {len(ctrl_stats)} hole stats.')
else:
ctrl_stats = {}
all_holes = env.... |
def get_image_generation_adapter_spec(num_outputs: int=1, output_image_width: Optional[int]=None, output_image_height: Optional[int]=None, guidance_scale: Optional[float]=None, diffusion_denoising_steps: Optional[int]=None, random: Optional[str]=None) -> AdapterSpec:
image_generation_parameters: ImageGenerationPara... |
def get_transform(train):
transforms = []
transforms.append(T.ToTensor())
if train:
transforms.append(T.RandomHorizontalFlip(0.5))
return T.Compose(transforms) |
class TestLargestNConnectedComponents(unittest.TestCase):
def setUp(self):
image = sitk.Image((5, 5), sitk.sitkUInt8)
image.SetPixel((0, 0), 1)
image.SetPixel((2, 0), 1)
image.SetPixel((2, 1), 1)
image.SetPixel((4, 0), 1)
image.SetPixel((4, 1), 1)
image.SetPix... |
def test_unnormalized_pmf():
counts = numpy.random.random(size=100)
pk = (counts / counts.sum())
assert (ndd.entropy(counts) == approx(Pmf().entropy_from_pmf(pk))) |
def binary_cross_entropy(pred, label, weight=None, reduction='mean', avg_factor=None, class_weight=None, ignore_index=(- 100), avg_non_ignore=False, **kwargs):
if (pred.size(1) == 1):
assert (label[(label != ignore_index)].max() <= 1), 'For pred with shape [N, 1, H, W], its label must have at most 2 classes... |
class ResBlock(nn.Module):
def __init__(self, n_feats, kernel_size, bias=True, conv=default_conv, norm=False, act=default_act):
super(ResBlock, self).__init__()
modules = []
for i in range(2):
modules.append(conv(n_feats, n_feats, kernel_size, bias=bias))
if norm:
... |
class ASTModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def _rebuild_qtensor(storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks):
qscheme = quantizer_params[0]
if (qscheme == torch.per_tensor_affine):
(_, scale, zero_point) = quantizer_params
tensor = torch._empty_affine_quantized(size, scale=scale, zero_point=zero... |
def get_modified_python_files(diff_with_last_commit=False):
repo = Repo(PATH_TO_TRANFORMERS)
if (not diff_with_last_commit):
print(f'Master is at {repo.refs.master.commit}')
print(f'Current head is at {repo.head.commit}')
branching_commits = repo.merge_base(repo.refs.master, repo.head)
... |
class ResnetDiscriminator(nn.Module):
def __init__(self, input_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, gpu_ids=[], padding_type='reflect', use_sigmoid=False, n_downsampling=2):
assert (n_blocks >= 0)
super(ResnetDiscriminator, self).__init__()
self.input_nc = in... |
def __is_functional_inputs_a_list(op_call_args: Any) -> bool:
if ((len(op_call_args) > 0) and isinstance(op_call_args[0], list)):
inputs_as_list = True
for arg in op_call_args[0]:
inputs_as_list = (inputs_as_list and isinstance(arg, KerasTensor))
return inputs_as_list
return ... |
class ScaleToFixed(object):
def __init__(self, dimA, dimB, dimC):
self.dimA = dimA
self.dimB = dimB
self.dimC = dimC
def __call__(self, image, imageA, imageB, imageC, label):
image = skTrans.resize(image, (self.dimA, self.dimB, self.dimC), order=1, preserve_range=True)
im... |
class ChooseGuardSubprocVecEnv(ShareVecEnv):
def __init__(self, env_fns, spaces=None):
self.waiting = False
self.closed = False
nenvs = len(env_fns)
(self.remotes, self.work_remotes) = zip(*[Pipe() for _ in range(nenvs)])
self.ps = [Process(target=chooseguardworker, args=(wor... |
def merge_new_config(config, new_config):
if ('_BASE_CONFIG_' in new_config):
with open(new_config['_BASE_CONFIG_'], 'r') as f:
try:
yaml_config = yaml.load(f, Loader=yaml.FullLoader)
except:
yaml_config = yaml.load(f)
config.update(EasyDict(ya... |
class AttendNodeModule(nn.Module):
def __init__(self, dim_vis_feat, visual_init_norm, jemb_dim, dim_lang_feat, jemb_dropout):
super(AttendNodeModule, self).__init__()
self.matching = Matching(dim_vis_feat, dim_lang_feat, jemb_dim, jemb_dropout, (- 1))
self.feat_normalizer = NormalizeScale(di... |
def t_stop(j, Js=[(1, 2), (3, 4), (5, 6)], Trange=(1, 10)):
if (j == (- 1)):
a = min(Trange)
return ((2 * a) - t_start(0, Js, Trange))
else:
return Js[j][1] |
def isomers_c11h24(mean_function='geometric') -> GoalDirectedBenchmark:
specification = uniform_specification(159)
return GoalDirectedBenchmark(name='C11H24', objective=IsomerScoringFunction('C11H24', mean_function=mean_function), contribution_specification=specification) |
def test_numpyarray_localindex():
v2_array = ak.contents.numpyarray.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3], dtype=np.float64))
assert (to_list(ak._do.local_index(v2_array, axis=0)) == [0, 1, 2, 3])
assert (ak._do.local_index(v2_array.to_typetracer(), axis=0).form == ak._do.local_index(v2_array, axis=0).fo... |
class Sqrtm(Benchmark):
params = [['float64', 'complex128'], [64, 256], [32, 64, 256]]
param_names = ['dtype', 'n', 'blocksize']
def setup(self, dtype, n, blocksize):
n = int(n)
dtype = np.dtype(dtype)
blocksize = int(blocksize)
A = np.random.rand(n, n)
if (dtype == n... |
def add_VGG16_roi_context_2fc_head(model, blob_in, dim_in, spatial_scale):
blobs_out = []
l = model.RoIFeatureTransform(blob_in, 'pool5', blob_rois='rois', method=cfg.FAST_RCNN.ROI_XFORM_METHOD, resolution=7, sampling_ratio=cfg.FAST_RCNN.ROI_XFORM_SAMPLING_RATIO, spatial_scale=spatial_scale)
l = model.net.R... |
def get_target_list(target_path):
targets = inout.load_json(target_path)
target_list = []
for i in range(len(targets)):
tgt = targets[i]
im_id = tgt['im_id']
inst_count = tgt['inst_count']
obj_id = tgt['obj_id']
scene_id = tgt['scene_id']
target_list.append([s... |
_grad()
def convert_wav2vec2_checkpoint(checkpoint_path, pytorch_dump_folder_path, config_path=None, dict_path=None, is_finetuned=True):
if (config_path is not None):
config = Data2VecAudioConfig.from_pretrained(config_path)
else:
config = Data2VecAudioConfig()
if (not is_finetuned):
... |
def fetch_data(splits, sample_pct, seed=1234):
ds_splits = {}
for split in splits:
key = f'{split.parent}_{split.stem}'
ds_splits[key] = sb.dataio.dataset.DynamicItemDataset.from_json(json_path=split, output_keys=['id', 'wav'])
data = list(itertools.chain(*ds_splits.values()))
random.see... |
def __wordnet_lookup_gender(head):
synsets = wn.synsets(head)
while synsets:
lemma_name = synsets[0].lemma_names()[0]
if ((lemma_name == 'man') or (lemma_name == 'male')):
return 'MALE'
elif ((lemma_name == 'woman') or (lemma_name == 'female')):
return 'FEMALE'
... |
class NbsDataset(VisionDataset):
def __init__(self, dataset, group):
self.dataset = dataset
self.group = group
def __getitem__(self, idx):
(img, label) = self.dataset[idx]
index = np.where((self.group == idx))[0][0]
return (img, label, index)
def __len__(self):
... |
def setup_model_loss_criterion(args, rank, is_cuda):
args.distributed_rank = rank
distributed_utils.distributed_init(args)
torch.manual_seed(1)
model = Model(args.input_size, args.nb_classes)
loss_fn = nn.CrossEntropyLoss()
if is_cuda:
model = model.cuda()
loss_fn = loss_fn.cuda(... |
class OutputInTheMiddleNetTest(BasePytorchTest):
def __init__(self, unit_test):
super().__init__(unit_test)
def create_feature_network(self, input_shape):
return OutputInTheMiddleNet() |
def set_score_text(fig, ax, bar, entry):
score_text = ax.text(x=((bar.get_x() + bar.get_width()) - 30), y=(bar.get_y() + (bar.get_height() / 2)), s=str(entry['score']), color='white', fontweight='bold', ha='right', va='center')
bar_x1 = bar.get_window_extent(renderer=fig.canvas.get_renderer()).x1
ax_x1 = ax... |
class c_nvmlMemory_t(ctypes.Structure):
_fields_ = [('total', ctypes.c_ulonglong), ('free', ctypes.c_ulonglong), ('used', ctypes.c_ulonglong)] |
def create_backbone(cfg):
if (cfg.MODEL.BACKBONE.TYPE == 'vit'):
return vit(cfg)
else:
raise NotImplementedError('Backbone type is not implemented') |
class SystemAct(object):
IMPLICIT_CONFIRM = 'implicit_confirm'
EXPLICIT_CONFIRM = 'explicit_confirm'
INFORM = 'inform'
REQUEST = 'request'
GREET = 'greet'
GOODBYE = 'goodbye'
CLARIFY = 'clarify'
ASK_REPHRASE = 'ask_rephrase'
ASK_REPEAT = 'ask_repeat'
QUERY = 'query' |
def generate(model, styles, mean_latent=None, truncation=1.0, batch_size=16, *args, **kwargs):
(images, segs) = ([], [])
for head in range(0, styles.size(0), batch_size):
(images_, segs_) = model([styles[head:(head + batch_size)]], *args, input_is_latent=True, truncation=truncation, truncation_latent=me... |
class GPT2TokenizationTest(CommonTestCases.CommonTokenizerTester):
tokenizer_class = GPT2Tokenizer
def setUp(self):
super(GPT2TokenizationTest, self).setUp()
vocab = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'G', 'Gl', 'Gn', 'Glo', 'Glow', 'er', 'Glowest', 'Gnewer', 'Gwider', '<unk>']
... |
_grad()
def calculate_lpips_given_images(group_of_images):
device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
lpips = LPIPS().eval().to(device)
lpips_values = []
num_rand_outputs = len(group_of_images)
for i in range((num_rand_outputs - 1)):
for j in range((i + 1), num_r... |
def register_types_ns3_Hash_Function(module):
root_module = module.get_root()
module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
module.add_clas... |
def read_all_Datasets(inpath, isLower=True):
all_instances = []
code_graph_len = []
doc_token_len = []
with gzip.GzipFile(inpath, 'r') as f:
lines = list(f)
results = parallel_process(lines, single_instance_process, args=(isLower,))
for result in results:
if (type(result) is tupl... |
def flickr8k_demo():
io = KarpathyIO(img_folder='data/flickr8k/Flicker8k_Dataset')
(train_data, *_) = io.read('data/flickr8k/demo.flickr8k-karpathy2015cvpr.json')
return train_data |
def test_graph_reverse_cuthill_mckee_ordering():
data = np.ones(63, dtype=int)
rows = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 15])
... |
def test_construct_kernel_separate_independent_duplicates():
kernel = Matern52(variance=5)
output_dim = 3
mok = construct_basic_kernel(kernel, output_dim=output_dim, share_hyperparams=False)
assert isinstance(mok, MultioutputKernel)
assert isinstance(mok, SeparateIndependent)
assert all([isinsta... |
def main(args):
torch.cuda.set_device(args.gpu_id)
builder = ModelBuilder()
net_encoder = builder.build_encoder(arch=args.arch_encoder, fc_dim=args.fc_dim, weights=args.weights_encoder)
net_decoder = builder.build_decoder(arch=args.arch_decoder, fc_dim=args.fc_dim, num_class=args.num_class, weights=args... |
class ParameterExtraction():
def __init__(self, coarse_model: CoarseModel, cost_functional_form: Union[(List[_typing.CostFunctional], _typing.CostFunctional)], states: Union[(List[fenics.Function], fenics.Function)], controls: Union[(List[fenics.Function], fenics.Function)], config: Optional[io.Config]=None, desire... |
def module_has_exports(mod):
for name in dir(mod):
item = getattr(mod, name)
if callable(item):
if (get_torchscript_modifier(item) is FunctionModifiers.EXPORT):
return True
return False |
class AI21TokenCounter(TokenCounter):
def count_tokens(self, request: Request, completions: List[Sequence]) -> int:
return sum((len(sequence.tokens) for sequence in completions)) |
class SpLinear(nn.Module):
def __init__(self, input_features, output_features, bias=True):
super(SpLinear, self).__init__()
self.input_features = input_features
self.output_features = output_features
self.weight = nn.Parameter(torch.Tensor(output_features, input_features))
if... |
def mask_attn_weights(w):
n = shape_list(w)[(- 1)]
b = tf.matrix_band_part(tf.ones([n, n]), (- 1), 0)
b = tf.reshape(b, [1, 1, n, n])
w = ((w * b) + ((- .0) * (1 - b)))
return w |
.parametrize('obj, method, inputs, err_cls, err_msg', [(MethodMapping(), 'add', {'callee': 'invalid', 'caller': 'fit'}, ValueError, 'Given callee'), (MethodMapping(), 'add', {'callee': 'fit', 'caller': 'invalid'}, ValueError, 'Given caller'), (MethodMapping, 'from_str', {'route': 'invalid'}, ValueError, "route should b... |
.operations('failure')
def test_cli_output(cli, base_url, schema_url, snapshot_cli):
assert (cli.run(schema_url, '--code-sample-style=python') == snapshot_cli) |
class SG_reg(atomic_reg):
OP_NAME = 'SG'
_fields_ = [('cmd_short', ctypes.c_uint64, 1), ('cmd_id', ctypes.c_uint64, 20), ('cmd_id_dep', ctypes.c_uint64, 20), ('tsk_typ', ctypes.c_uint64, 4), ('tsk_eu_typ', ctypes.c_uint64, 5), ('eu_half_en', ctypes.c_uint64, 1), ('tsk_opd_num', ctypes.c_uint64, 2), ('pad_mode',... |
class EnvTool():
def __init__(self, action_info, env):
self.action_info = action_info
self.env = env
def run(self, action_input: str) -> str:
try:
parsed_input = LangChainAgent.parse_action_input(action_input, self.action_info)
observation = self.env.execute(Actio... |
def extract_done_markers(dones: np.ndarray) -> Tuple[(np.ndarray, np.ndarray, np.ndarray)]:
(ends,) = np.where(dones)
starts = np.concatenate(([0], (ends[:(- 1)] + 1)))
lengths = ((ends - starts) + 1)
return (starts, ends, lengths) |
def load(filepath: str, **kwargs):
if (not filepath.startswith('hdfs://')):
return torch.load(filepath, **kwargs)
with hopen(filepath, 'rb') as reader:
accessor = io.BytesIO(reader.read())
state_dict = torch.load(accessor, **kwargs)
del accessor
return state_dict |
def infer_gib_multiclass(metric: Callable) -> bool:
label = np.array([0, 1, 2])
pred = np.array([[0.9, 0.05, 0.05], [0.05, 0.9, 0.05], [0.05, 0.05, 0.9]])
g_val = metric(label, pred)
b_val = metric(label, pred[::(- 1)])
assert (g_val != b_val), 'Cannot infer greater is better from metric. Should be ... |
class Down(nn.Module):
def __init__(self, in_ch, out_ch):
super(Down, self).__init__()
self.mpconv = nn.Sequential(nn.MaxPool2d(2), DoubleConv(in_ch, out_ch))
def forward(self, x):
x = self.mpconv(x)
return x |
def computeSequenceClassificationF1(outputs, targets, tasks):
targets = [target[0] for target in targets]
label2id = tasks[0].label2id
outputs = [label2id[output] for output in outputs]
targets = [label2id[target] for target in targets]
f1_metric = load_metric('f1')
return (f1_metric.compute(ref... |
_utils.test(require=ti.extension.adstack)
def test_ad_fibonacci_index():
N = 5
M = 10
a = ti.field(ti.f32, shape=M, needs_grad=True)
b = ti.field(ti.f32, shape=M, needs_grad=True)
f = ti.field(ti.f32, shape=(), needs_grad=True)
def fib():
for i in range(N):
p = 0
... |
_grad()
def convert_sew_checkpoint(checkpoint_path, pytorch_dump_folder_path, config_path=None, dict_path=None, is_finetuned=True):
if is_finetuned:
(model, _, _) = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path], arg_overrides={'data': '/'.join(dict_path.split('/')[:(- 1)])})
el... |
def _sort_commands(cmddict, order):
def keyfn(key):
try:
return order.index(key[1])
except ValueError:
return 255
return sorted(cmddict.items(), key=keyfn) |
def NumberField_relative_v1(base_field, poly, name, latex_name, canonical_embedding=None):
return NumberField(poly.change_ring(base_field), name, check=False, embedding=canonical_embedding, latex_name=latex_name) |
class GCPKeyManager():
def __init__(self, local_key_dir: Path=(key_root / 'gcp')):
self.local_key_dir = local_key_dir
def get_private_key(self, key_name: str) -> Path:
return (self.local_key_dir / f'{key_name}.pem')
def get_public_key(self, key_name: str) -> Path:
return (self.local_... |
def basic1d(filters=([128] * 5), kernel_size=3, stride=2, dilation=1, pool=0, pool_stride=1, squeeze_excite_reduction=0, num_classes=2, input_channels=8, act='relu', bn=True, headless=False, drop_p=0.0, lin_ftrs_head=None, ps_head=0.5, bn_final_head=False, bn_head=True, act_head='relu', concat_pooling=True):
return... |
def register_Ns3RadiotapHeader_methods(root_module, cls):
cls.add_constructor([param('ns3::RadiotapHeader const &', 'arg0')])
cls.add_constructor([])
cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True)
cls.add_method('GetAmpduStatusFlags', 'uint16_t', []... |
class NumpyArray(NumpyMeta, Content):
def __init__(self, data: ArrayLike, *, parameters=None, backend=None):
if (backend is None):
backend = backend_of_obj(data, default=NumpyBackend.instance())
self._data = backend.nplike.asarray(data)
if (not isinstance(backend.nplike, Jax)):
... |
class BaseInpaintingTrainingModule(ptl.LightningModule):
def __init__(self, config, use_ddp, *args, predict_only=False, visualize_each_iters=100, average_generator=False, generator_avg_beta=0.999, average_generator_start_step=30000, average_generator_period=10, store_discr_outputs_for_vis=False, **kwargs):
... |
class _ndptr(_ndptr_base):
def from_param(cls, obj):
if (not isinstance(obj, ndarray)):
raise TypeError('argument must be an ndarray')
if ((cls._dtype_ is not None) and (obj.dtype != cls._dtype_)):
raise TypeError(('array must have data type %s' % cls._dtype_))
if ((c... |
def activation_summary(x):
tensor_name = x.op.name
tf.summary.histogram((tensor_name + '/activations'), x)
tf.summary.scalar((tensor_name + '/sparsity'), tf.nn.zero_fraction(x)) |
class Invocation():
def __init__(self, name, error_context):
self._name = name
self._error_context = error_context
def name(self):
return self._name
def error_context(self):
return self._error_context |
class Dataset(InMemoryDataset):
def __init__(self, root, dataset, pred_edges=1, transform=None, pre_transform=None):
self.path = root
self.dataset = dataset
self.pred_edges = pred_edges
super(Dataset, self).__init__(root, transform, pre_transform)
(self.data, self.slices) = t... |
class ParseTreeBuilder():
def __init__(self, rules, tree_class, propagate_positions=False, ambiguous=False, maybe_placeholders=False):
self.tree_class = tree_class
self.propagate_positions = propagate_positions
self.ambiguous = ambiguous
self.maybe_placeholders = maybe_placeholders
... |
def db_iterator():
return [{'round': 1, 'tensor_name': 'tensor1', 'tags': 'aggregated', 'nparray': [1]}] |
def test_default_replacement_unchanged(config):
new_keys = {'new_key1', 'new_key2'}
updated_config = config.with_keys_to_sanitize(*new_keys)
assert (updated_config.replacement == DEFAULT_REPLACEMENT) |
_test(assert_ii_1=False)
def test_map_unroll_processing_elements():
spec = importlib.util.spec_from_file_location('gemm', (((Path(__file__).parent.parent.parent / 'samples') / 'fpga') / 'gemm_systolic_vectorized.py'))
gemm = importlib.util.module_from_spec(spec)
spec.loader.exec_module(gemm)
N = 128
... |
class ONNXTracedModule(torch.nn.Module):
def __init__(self, inner, strict=True, force_outplace=False, return_inputs=False, return_inputs_states=False):
super(ONNXTracedModule, self).__init__()
self.inner = inner
self.strict = strict
self._force_outplace = force_outplace
self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.