code stringlengths 101 5.91M |
|---|
class Cache():
def __init__(self, capacity):
self._cache = OrderedDict()
self._capacity = int(capacity)
if (capacity <= 0):
raise ValueError('capacity must be a positive integer')
def capacity(self):
return self._capacity
def size(self):
return len(self._c... |
class IteratorTest(AllenNlpTestCase):
def setUp(self):
super(IteratorTest, self).setUp()
self.token_indexers = {'tokens': SingleIdTokenIndexer()}
self.vocab = Vocabulary()
self.this_index = self.vocab.add_token_to_namespace('this')
self.is_index = self.vocab.add_token_to_name... |
class Production(object):
reduced = 0
def __init__(self, number, name, prod, precedence=('right', 0), func=None, file='', line=0):
self.name = name
self.prod = tuple(prod)
self.number = number
self.func = func
self.callable = None
self.file = file
self.lin... |
class cv_Yolo():
def __init__(self, yolo_path, confidence=0.5, threshold=0.3):
self.confidence = confidence
self.threshold = threshold
labels_path = os.path.sep.join([yolo_path, 'coco.names'])
self.labels = open(labels_path).read().split('\n')
np.random.seed(42)
self.... |
class TestActivationCheckpointing(unittest.TestCase):
def _test_checkpoint_wrapper(self, device, log_memory_usage=False):
def get_loss_and_gnorm(model):
torch.manual_seed(1)
input = torch.rand(2, 16, 32).requires_grad_(True).to(device)
model.zero_grad()
loss =... |
class IBMCloudConfig(AuthenticationConfig):
ibmcloud_access_id: Optional[str] = None
ibmcloud_secret_key: Optional[str] = None
ibmcloud_iam_key: Optional[str] = None
ibmcloud_iam_endpoint: Optional[str] = None
ibmcloud_useragent: Optional[str] = None
ibmcloud_resource_group_id: Optional[str] = N... |
class TestModifiers():
def test_run(self):
img_path = os.path.join(ds_path, 'images')
shutil.rmtree((ds_path + '#dir_modifier'), ignore_errors=True)
mod = DSModifier_dir()
mod.modify(data_input=img_path)
assert os.path.exists((ds_path + '#dir_modifier/images/.jpg')), 'DSModif... |
def _patch_arguments_(gm: GraphModule, mapping: Union[(Dict[(Node, int)], Dict[(int, Node)])], lint_and_recompile: bool=True):
def _patch_slice(s, mapping):
return slice(mapping.get(s.start, s.start), mapping.get(s.stop, s.stop), mapping.get(s.step, s.step))
graph = gm.graph
supported_types = (Node,... |
class VELOLValidation(VELOL):
def __init__(self, dir_data, **kwargs):
super().__init__(dir_data, split='test', **kwargs)
self.transforms = tf.Compose([CenterCrop(size=self.crop_size), ImageToLDMTensor()]) |
def object2Element(ctxObj):
ctxElement = {}
ctxElement['entityId'] = ctxObj['entityId']
ctxElement['attributes'] = []
if ('attributes' in ctxObj):
for key in ctxObj['attributes']:
attr = ctxObj['attributes'][key]
ctxElement['attributes'].append({'name': key, 'type': attr[... |
class MLTSVMTest(ClassifierBaseTest):
TEST_NEIGHBORS = 3
def classifiers(self):
return [MLTSVM(c_k=(2 ** (- 4)))]
def test_if_mlknn_classification_works_on_sparse_input(self):
for classifier in self.classifiers():
self.assertClassifierWorksWithSparsity(classifier, 'sparse')
d... |
def matmul_flop_jit(inputs: List[Any], outputs: List[Any]) -> typing.Counter[str]:
input_shapes = [get_shape(v) for v in inputs]
assert (len(input_shapes) == 2), input_shapes
assert (input_shapes[0][(- 1)] == input_shapes[1][(- 2)]), input_shapes
flop = (prod(input_shapes[0]) * input_shapes[(- 1)][(- 1)... |
def register_Ns3LtePdcpSapProvider_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::LtePdcpSapProvider const &', 'arg0')])
cls.add_method('TransmitPdcpSdu', 'void', [param('ns3::LtePdcpSapProvider::TransmitPdcpSduParameters', 'params')], is_pure_virtual=True, is_virtual=Tr... |
def test_qmanager__measure_density():
NUM_TESTS = 1000
qm = QuantumManagerDensity()
meas_0 = []
meas_1 = []
state_single = [math.sqrt((1 / 2)), math.sqrt((1 / 2))]
state = np.outer(state_single, state_single)
for _ in range(NUM_TESTS):
key = qm.new()
samp = np.random.random()... |
def get_slot_code_by_name(scope, slot_name):
slot = get_slot_by_name(slot_name)
return slot.slot_code(scope) |
class ReducerConfig(Config):
compute_bundle_dir = None
models_dir = None
initial_model = None
storage_backend = {'type': 's3', 'settings': {'bucket': 'models'}}
def __init__(self):
pass |
class WhileScope(ControlFlowScope):
header: cf.WhileScope
def as_string(self, indent: int=0):
result = ((indent * INDENTATION) + f'''while {self.header.test.as_string}:
''')
return (result + super().as_string(indent)) |
def load_vocab(vocab_file):
vocab = collections.OrderedDict()
index = 0
with tf.gfile.GFile(vocab_file, 'r') as reader:
while True:
token = convert_to_unicode(reader.readline())
if (not token):
break
token = token.strip()
vocab[token] =... |
def test_omop_concept_code_labeler(tmp_path: pathlib.Path):
time_horizon = TimeHorizon(datetime.timedelta(days=0), datetime.timedelta(days=10))
ontology = DummyOntology_OMOPConcept()
labeler = DummyLabeler_OMOPConcept(ontology, time_horizon, prediction_codes=['1', '2'])
assert (set(labeler.outcome_codes... |
class Experiment(object):
def __init__(self, name, experiments_path, results_path, global_configuration, experiment_configuration, seed):
self._name = name
self._experiments_path = experiments_path
self._results_path = results_path
self._global_configuration = global_configuration
... |
class AnnotateEM():
def __init__(self, collection, qas):
qas = load_qas_(qas)
collection = Collection.cast(collection)
self.parallel_pool = Pool(30)
print_message('#> Tokenize the answers in the Q&As in parallel...')
qas = list(self.parallel_pool.map(tokenize_all_answers, qas... |
def _get_psd_matrix(N):
from gpflow.kernels import SquaredExponential
x = np.linspace((- 1), 1, N).reshape((- 1), 1)
A = SquaredExponential()(x, full_cov=True).numpy()
return (A + (1e-06 * np.eye(N, dtype=A.dtype))) |
class DRN(nn.Module):
def __init__(self, block, layers, num_classes=1000, channels=(16, 32, 64, 128, 256, 512, 512, 512), out_map=False, out_middle=False, pool_size=28, arch='D'):
super(DRN, self).__init__()
self.inplanes = channels[0]
self.out_map = out_map
self.out_dim = channels[(... |
def get_version():
init_py_path = path.join(path.abspath(path.dirname(__file__)), 'detectron2', '__init__.py')
init_py = open(init_py_path, 'r').readlines()
version_line = [l.strip() for l in init_py if l.startswith('__version__')][0]
version = version_line.split('=')[(- 1)].strip().strip('\'"')
suf... |
def get_unique_stat_by_matcher(stats: List[Stat], matcher: MetricNameMatcher) -> Optional[Stat]:
matching_stats = [stat for stat in stats if matcher.matches(stat.name)]
if (len(matching_stats) == 0):
if (matcher.name == 'quasi_exact_match'):
hlog('WARNING: No quasi_exact_match metric found, ... |
def test_sum():
content2 = ak.contents.NumpyArray(np.array([1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048], dtype=np.int64))
offsets3 = ak.index.Index64(np.array([0, 4, 8, 12], dtype=np.int64))
depth1 = ak.contents.ListOffsetArray(offsets3, content2)
assert (to_list(ak.sum(depth1, (- 1), highlevel=F... |
class F30KCaptionKarpathyDataset(BaseDataset):
def __init__(self, *args, split='', **kwargs):
assert (split in ['train', 'val', 'test'])
if (split == 'train'):
names = ['f30k_caption_karpathy_train', 'f30k_caption_karpathy_val']
elif (split == 'val'):
names = ['f30k_c... |
def flatgrad(loss, var_list, clip_norm=None):
grads = tf.gradients(loss, var_list)
if (clip_norm is not None):
grads = [tf.clip_by_norm(grad, clip_norm=clip_norm) for grad in grads]
return tf.concat(axis=0, values=[tf.reshape((grad if (grad is not None) else tf.zeros_like(v)), [numel(v)]) for (v, gr... |
def main():
logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)
parser = ArgumentParserShowHelpOnError(prog='Deep Deterministic Policy Gradient (DDPG)', description='Deep Deterministic Policy Gradient (DDPG) in Tensorflow 2')
parser.add_argument('--env', type=str, nargs='?', default='Bipeda... |
def test_conll_sysa():
assert check_correct(EXPECTED_CONLL_SYSA, _get_stats(CONLL_GOLD_UNSTITCHED, CONLL_SYSA_UNSTITCHED)) |
def test_simple_moves():
(board, player, game) = init_board_from_moves([4, 5, 4, 3, 0, 6])
expected = textwrap.dedent(' [[ 0. 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 1. 0.... |
class OpenAIGPTModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class Benchmark(LoggingBase):
def typename() -> str:
return 'Benchmark'
def benchmark(self):
return self._benchmark
def benchmark_path(self):
return self._benchmark_path
def benchmark_config(self) -> BenchmarkConfig:
return self._benchmark_config
def code_package(self... |
class CARTOON_THRESH_METHODS(Enum):
BINARY = 'thresh_binary'
BINARY_INV = 'thresh_binary_inv'
TRIANGLE = 'thresh_triangle'
MASK = 'thresh_mask'
TRUNC = 'thresh_trunc'
OTSU = 'thresh_otsu'
TOZERO = 'thresh_tozero'
TOZERO_INV = 'thresh_tozero_inv' |
def restore_optimizer_state(optimizer):
optimizer.solver.set_states_from_protobuf(optimizer.proto)
if hasattr(optimizer, 'solver_checkpoint'):
(ext, handler) = optimizer.solver_checkpoint
if (ext == '.protobuf'):
optimizer.solver.set_states_from_protobuf(handler)
elif (ext ==... |
def _capture_stream(is_origin=True):
torch.cuda.init()
return torch.cuda.Stream(_cdata=torch._C._cuda_getCaptureStream(is_origin)) |
def add_retrieved_documents(args, examples):
ret_object = DPRDoc_Retrieval(topk=args.topk, model_type=args.model_type)
for example in tqdm(examples):
responses = example['response_candidates']
context = example['context']
context_string = ' '.join(context[(- 2):])
response_docs =... |
def plot_average_reward_per_n_rounds(rewards):
rewards_pd = pd.DataFrame(rewards)
rewards_pd = pd.melt(rewards_pd, ['n_rounds'])
rewards_pd['value'] = (rewards_pd['value'] / rewards_pd['n_rounds'])
plot = sns.lineplot(data=rewards_pd, x='n_rounds', y='value', style='variable', hue='variable', markers=Tr... |
class PLBartPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def add_loss_for_each_scale(scales_to_logits, labels, num_classes, ignore_label, loss_weight=1.0, upsample_logits=True, scope=None, loss_function='sce'):
if (labels is None):
raise ValueError('No label for softmax cross entropy loss.')
if (loss_function is None):
loss_function = 'sce'
for (s... |
def von_mises_cdf_normalapprox(k, x):
b = ((np.sqrt((2 / np.pi)) * np.exp(k)) / i0(k))
z = (b * np.sin((x / 2.0)))
return scipy.stats.norm.cdf(z) |
def handle_special_chars(t):
t = re.sub('(\\w)-(\\w)', '\\1 \\2', t)
return re.sub('([%&\\/$*])', ' \\1 ', t) |
def barron_factor(x: sf.Matrix51, y: sf.Matrix51, mu: sf.Scalar, eps: sf.Scalar) -> sf.Matrix51:
alpha = BarronNoiseModel.compute_alpha_from_mu(mu, eps)
noise_model = BarronNoiseModel(alpha=alpha, delta=1, scalar_information=1, x_epsilon=eps)
return noise_model.whiten((x - y)) |
class VersionControl(object):
name = ''
dirname = ''
schemes = ()
unset_environ = ()
default_arg_rev = None
def __init__(self, url=None, *args, **kwargs):
self.url = url
super(VersionControl, self).__init__(*args, **kwargs)
def get_base_rev_args(self, rev):
raise NotI... |
class ForecastExperiment(Experiment):
()
def instance(self, model_type: str, save_vals: Optional[bool]=True):
(train_set, train_loader) = get_data(flag='train')
(val_set, val_loader) = get_data(flag='val')
(test_set, test_loader) = get_data(flag='test')
model = get_model(model_ty... |
class IndexExtractorNodeLister(NodeVisitor):
def __init__(self):
self.nodes: List[ast_internal_classes.Array_Subscript_Node] = []
def visit_Call_Expr_Node(self, node: ast_internal_classes.Call_Expr_Node):
if (node.name.name in ['sqrt', 'exp', 'pow', 'max', 'min', 'abs', 'tanh']):
ret... |
class Resample2dFunction(Function):
def forward(ctx, input1, input2, kernel_size=1, bilinear=True):
assert input1.is_contiguous()
assert input2.is_contiguous()
ctx.save_for_backward(input1, input2)
ctx.kernel_size = kernel_size
ctx.bilinear = bilinear
(_, d, _, _) = i... |
def proxyless_base(pretrained=True, net_config=None, net_weight=None):
assert (net_config is not None), 'Please input a network config'
net_config_path = download_url(net_config)
net_config_json = json.load(open(net_config_path, 'r'))
if (net_config_json['name'] == ProxylessNASNets.__name__):
ne... |
class VibrateLR(_LRScheduler):
def __init__(self, optimizer, total_iter, last_epoch=(- 1)):
self.total_iter = total_iter
super(VibrateLR, self).__init__(optimizer, last_epoch)
def get_lr(self):
process = (self.last_epoch / self.total_iter)
f = 0.1
if (process < (3 / 8)):
... |
def cached_property(func):
atrribute_name = f'_{func.__name__}'
def _wrapper(self):
try:
return getattr(self, atrribute_name)
except AttributeError:
val = func(self)
self.__dict__[atrribute_name] = val
return val
return property(_wrapper) |
def savemodel():
if PARAMS['use_cloud']:
savemodel_dir = (PARAMS['gcs_results'].rstrip('/') + f'/{str(VERSION)}')
else:
savemodel_dir = (get_results_dir(PARAMS['dataset']) + f'savemodel/{str(VERSION)}')
return Checkpoint(savemodel_dir) |
def main(args):
print('Dataset: {}, Label: {}, LR: {}'.format(args.dataset, args.label, args.lr))
device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu'))
model = utils.get_resnet_model(resnet_type=args.resnet_type)
model.fc = torch.nn.Linear(args.latent_dim_size, 1)
model = model.t... |
def create_argparser():
defaults = dict(data_dir='', schedule_sampler='uniform', lr=0.0003, weight_decay=0.0, lr_anneal_steps=0, batch_size=1, microbatch=(- 1), ema_rate='0.9999', log_interval=10, save_interval=10000, resume_checkpoint='', use_fp16=False, fp16_scale_growth=0.001, model='MDT_S_2', mask_ratio=None, d... |
def test_validate_references_nested_raises_value_error():
with pytest.raises(ValueError, match='Expected type'):
optplan.validate_references(optplan.Sum(functions=[optplan.Power(function=optplan.Sum(functions=[optplan.make_constant(2), optplan.SimulationSpace()])), optplan.make_constant(2)])) |
()
('policy_file', type=str)
('--seed', type=int, default=0)
('--n_test_rollouts', type=int, default=20)
('--render', type=click.Choice(['human', 'rgb_array']), default='rgb_array')
('--exploit', type=bool, default=True)
('--compute_q', type=bool, default=True)
('--collect_data', type=bool, default=True)
('--goal_gener... |
class ColumnBroadcastOp():
Template = '\nusing ${instance_name} = cutlass::epilogue::threadblock::VisitorOpColumnBroadcast<\n ${element_accumulator}, ${element_fragment}, ${input_tile_iterator}>;\n'
counter = 0
def __init__(self, element_accumulator, element_fragment) -> None:
self.element_accumu... |
class NSP_Prompt():
def __init__(self, dataset_name=''):
(self.label_texts, self.template) = ([], '')
self.label_num = 0
if (dataset_name in ['SST-2', 'MR']):
self.label_texts = ['terrible', 'great']
self.template = 'A [label] piece of work'
self.is_pre = ... |
.parametrize('nntxt_idx', CASE_INDEX)
.parametrize('parameter_format', ['.h5', '.protobuf'])
.parametrize('dataset_sample_num', [64])
.parametrize('batch_size', [16])
.parametrize('include_params', [False])
.parametrize('variable_batch_size', [True])
def test_load_and_save_equivalence(nntxt_idx, parameter_format, datas... |
def learnable_resizer(inputs, filters=16, num_res_blocks=1, interpolation=INTERPOLATION):
naive_resize = layers.experimental.preprocessing.Resizing(*TARGET_SIZE, interpolation=interpolation)(inputs)
x = layers.Conv2D(filters=filters, kernel_size=7, strides=1, padding='same')(inputs)
x = layers.LeakyReLU(0.2... |
def prepare_keys_reds(folder_path):
print('Reading image path list ...')
img_path_list = sorted(list(scandir(folder_path, suffix='png', recursive=True)))
keys = [v.split('.png')[0] for v in img_path_list]
return (img_path_list, keys) |
def main(flags):
if (flags.model == 'vanilla'):
train_vanilla(flags)
elif (flags.model == 'count'):
train_count(flags)
elif (flags.model == 'curiosity'):
train_curiosity(flags)
elif (flags.model == 'rnd'):
train_rnd(flags)
elif (flags.model == 'ride'):
train_r... |
def inception_v3(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.8, min_depth=16, depth_multiplier=1.0, prediction_fn=slim.softmax, spatial_squeeze=True, reuse=None, scope='InceptionV3'):
if (depth_multiplier <= 0):
raise ValueError('depth_multiplier is not greater than zero.')
depth = (... |
class RecallMetric(BaseSKLearnMetric):
def _evaluate(self, y_true, y_pred):
return recall_score(y_true, y_pred) |
def register_Ns3DefaultDeleter__Ns3MmWaveControlMessage_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::DefaultDeleter< ns3::MmWaveControlMessage > const &', 'arg0')])
cls.add_method('Delete', 'void', [param('ns3::MmWaveControlMessage *', 'object')], is_static=True)
r... |
def named_parameters(partition, recurse=True):
params = nn.Module.named_parameters(partition, recurse=recurse)
lookup = partition.lookup
for (k, v) in params:
if (k in lookup):
(yield (lookup[k], v))
else:
assert ('.' in k)
split_idx = k.find('.')
... |
def build_sdist(source_dir, sdist_dir, config_settings=None):
if (config_settings is None):
config_settings = {}
(requires, backend, backend_path) = _load_pyproject(source_dir)
hooks = Pep517HookCaller(source_dir, backend, backend_path)
with BuildEnvironment() as env:
env.pip_install(req... |
def log_trial(agents, trial_n):
(correct, incorrect, not_finish) = summarize_trial(agents)
log = f'''
BEGIN TRIAL {trial_n}
Trial summary: Correct: {len(correct)}, Incorrect: {len(incorrect)} , Not Finished: {len(not_finish)}
'''
log += ' BEGIN CORRECT AGENTS \n\n'
for agent in correct:
log += (... |
class BM1688Context(BModelContext):
device = Target.BM1688
memmap = memmap
dma_sys = dma_sys
tiu_sys = tiu_sys
local_layout_to_stride = local_layout_to_stride
valid_tag = {1: 0, 2: 1, 3: 2}
base_addr = [(2 ** 32), ( + (2 ** 32)), GET_LMEM_START_ADDR]
def __init__(self) -> None:
s... |
def preprocess(dataset, remove_from=False):
output_vocab = ['_UNK', '_EOS', '.', 't1', 't2', '=', 'select', 'from', 'as', 'value', 'join', 'on', ')', '(', 'where', 't3', 'by', ',', 'count', 'group', 'order', 'distinct', 't4', 'and', 'limit', 'desc', '>', 'avg', 'having', 'max', 'in', '<', 'sum', 't5', 'intersect', ... |
class Conv2DBlock(nn.Module):
def __init__(self, in_channels, out_channels, kernel_sizes, strides, norm=None, activation=None, padding_mode='replicate'):
super(Conv2DBlock, self).__init__()
padding = ((kernel_sizes // 2) if isinstance(kernel_sizes, int) else ((kernel_sizes[0] // 2), (kernel_sizes[1]... |
def val_collate_fn_visual(batch):
(imgs, pids, camids, _, mask, path) = zip(*batch)
return (torch.stack(imgs, dim=0), pids, camids, torch.stack(mask, dim=0), path) |
class TestMultiClassWrapper(TestCase):
def test_invariance_to_data_types(self):
x = np.array([['a', 'b', 'c'], ['a', 'b', 'c'], ['b', 'b', 'c'], ['b', 'b', 'b'], ['b', 'b', 'b'], ['a', 'b', 'a']])
y = [1, 2, 3, 3, 3, 3]
wrapper = PolynomialWrapper(encoders.TargetEncoder())
result = w... |
def smithform_ZZ(n=128, min=0, max=9, system='sage'):
if (system == 'sage'):
A = random_matrix(ZZ, n, n, x=min, y=(max + 1))
t = cputime()
v = A.elementary_divisors()
return cputime(t)
elif (system == 'magma'):
code = ('\nn := %s;\nA := MatrixAlgebra(IntegerRing(), n)![Ra... |
class AperiodicSemigroups(CategoryWithAxiom):
def extra_super_categories(self):
return [Semigroups().HTrivial()] |
def test_srp_randomsubspaces():
stream = ConceptDriftStream(position=1000, width=20, random_state=1)
learner = StreamingRandomPatchesClassifier(n_estimators=3, subspace_mode='percentage', training_method='randomsubspaces', random_state=1)
y_expected = np.asarray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,... |
_cached
def _tutte_polynomial_internal(G, x, y, edge_selector, cache=None):
if (not G.num_edges()):
return x.parent().one()
def recursive_tp(graph=None):
if (graph is None):
graph = G
return _tutte_polynomial_internal(graph, x, y, edge_selector, cache=cache)
with removed_... |
class DatasetWriter(object):
def __init__(self, mujoco=False, goal=False):
self.mujoco = mujoco
self.goal = goal
self.data = self._reset_data()
self._num_samples = 0
def _reset_data(self):
data = {'observations': [], 'actions': [], 'terminals': [], 'rewards': []}
... |
class TestDataset(torch.utils.data.Dataset):
def __init__(self, args):
self.args = args
self.size = (self.w, self.h) = args['size']
self.video_root = args['video_root']
self.mask_root = args['mask_root']
self.flow_root = args['flow_root']
self.load_flow = args['load_f... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm3d(planes)
self.conv2 = nn.Conv3d(... |
def requires_gloo():
return unittest.skipUnless(c10d.is_gloo_available(), 'c10d was not compiled with the Gloo backend') |
class IterableDataset(Dataset[T_co], metaclass=_DataPipeMeta):
functions: Dict[(str, Callable)] = {}
reduce_ex_hook: Optional[Callable] = None
def __iter__(self) -> Iterator[T_co]:
raise NotImplementedError
def __add__(self, other: Dataset[T_co]):
return ChainDataset([self, other])
d... |
_properties
class Memlet(object):
volume = SymbolicProperty(default=0, desc='The exact number of elements moved using this memlet, or the maximum number if dynamic=True (with 0 as unbounded)')
dynamic = Property(default=False, dtype=bool, desc='Is the number of elements moved determined at runtime (e.g., data d... |
class SymplecticDerivationLieAlgebra(InfinitelyGeneratedLieAlgebra, IndexedGenerators):
def __init__(self, R, g):
if (g < 4):
raise ValueError('g must be at least 4')
cat = LieAlgebras(R).WithBasis().Graded()
self._g = g
d = Family(NonNegativeIntegers(), (lambda n: Partit... |
class StrideSupport(enum.Enum):
Strided = enum_auto()
Unity = enum_auto()
Fixed = enum_auto() |
def get_AA_golden_ratio():
global AA_golden_ratio
if (AA_golden_ratio is None):
AA_golden_ratio_nf = NumberField((((ZZX_x ** 2) - ZZX_x) - 1), 'phi')
AA_golden_ratio_generator = AlgebraicGenerator(AA_golden_ratio_nf, ANRoot((((AAPoly.gen() ** 2) - AAPoly.gen()) - 1), RIF(1.618, 1.6181)))
... |
def load_pretrained_feature_extractor(feature_extractor_name, device):
net_test = PreActResNet18()
net_test = net_test.to(device)
net_test.load_state_dict(torch.load(('checkpoint/' + feature_extractor_name)))
net_test.eval()
return net_test |
def rand_augment_transform(config_str, hparams):
magnitude = _MAX_LEVEL
num_layers = 2
weight_idx = None
transforms = _RAND_TRANSFORMS
config = config_str.split('-')
assert (config[0] == 'rand')
config = config[1:]
for c in config:
cs = re.split('(\\d.*)', c)
if (len(cs) ... |
def build_segmentor(cfg, train_cfg=None, test_cfg=None):
if ((train_cfg is not None) or (test_cfg is not None)):
warnings.warn('train_cfg and test_cfg is deprecated, please specify them in model', UserWarning)
assert ((cfg.get('train_cfg') is None) or (train_cfg is None)), 'train_cfg specified in both o... |
def evaluate(args, model, tokenizer, mode, prefix=''):
eval_task = args.task_name
eval_output_dir = args.output_dir
eval_dataset = load_and_cache_examples(args, eval_task, tokenizer, mode)
if ((not os.path.exists(eval_output_dir)) and (args.local_rank in [(- 1), 0])):
os.makedirs(eval_output_dir... |
class OpenExecutor(ActionExecutor):
def __init__(self, close: bool):
self.close = close
def execute(self, script: Script, state: EnvironmentState, info: ExecutionInfo):
current_line = script[0]
info.set_current_line(current_line)
node = state.get_state_node(current_line.object())... |
class KerasFakeQuantExporterBaseTest(ABC):
def run_test(self):
self.model = self.get_model()
(self.exportable_model, _) = mct.ptq.keras_post_training_quantization_experimental(in_model=self.model, core_config=mct.core.CoreConfig(quantization_config=self.get_quantization_config()), representative_dat... |
def add_test(cls, layouts, alignments, element_output, element_accumulator, element_epilogue, cluster_shape, threadblock_shape, stages, opclass, persistent=False):
def run(self):
element_A = cutlass.float16
element_B = cutlass.float16
inst_shape = ([1, 1, 1] if (opclass == cutlass.OpClass.Si... |
def uniform_init(module: nn.Module, a: float=0, b: float=1, bias: float=0) -> None:
if (hasattr(module, 'weight') and (module.weight is not None)):
nn.init.uniform_(module.weight, a, b)
if (hasattr(module, 'bias') and (module.bias is not None)):
nn.init.constant_(module.bias, bias) |
def add_generation_args(parser):
group = parser.add_argument_group('Generation')
add_common_eval_args(group)
group.add_argument('--beam', default=5, type=int, metavar='N', help='beam size')
group.add_argument('--nbest', default=1, type=int, metavar='N', help='number of hypotheses to output')
group.a... |
def test_f():
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
f = function_symbol('f', x)
g = function_symbol('g', x)
assert (f != g)
f = function_symbol('f', x)
g = function_symbol('f', x)
assert (f == g)
f = function_symbol('f', x, y)
g = function_symbol('f', y, x)
asse... |
class CudaTensorHolder(pycuda_driver.PointerHolderBase):
def __init__(self, t):
super().__init__()
self.gpudata = t.data_ptr() |
def test_attribute_in_ranged_loop():
a = np.random.rand(20, 20)
regression = (a * 5)
doublefor_jit(a)
assert np.allclose(a, regression) |
def val_seg(model, dataset_loader, criterion=None, num_classes=21, device='cuda'):
model.eval()
inter_meter = AverageMeter()
union_meter = AverageMeter()
batch_time = AverageMeter()
end = time.time()
miou_class = MIOU(num_classes=num_classes)
if criterion:
losses = AverageMeter()
... |
def FibonacciTree(n):
T = Graph(name=('Fibonacci-Tree-%d' % n))
if (n == 1):
T.add_vertex(0)
if (n < 2):
return T
from sage.combinat.combinat import fibonacci_sequence
F = list(fibonacci_sequence((n + 2)))
s = (1.618 ** ((n / 1.618) - 1.618))
pos = {}
def fib(level, node,... |
def _dataset_info(txt_labels):
with open(txt_labels, 'r') as f:
images_list = f.readlines()
file_names = []
labels = []
for row in images_list:
row = row.split(' ')
file_names.append(row[0])
labels.append(int(row[1]))
return (file_names, labels) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.