code stringlengths 101 5.91M |
|---|
def test_single_data_multiple_connectors():
outer_sdfg = dace.SDFG('single_data_multiple_connectors')
outer_sdfg.add_array('A', (2, 10), dtype=dace.int32)
outer_sdfg.add_array('B', (2, 10), dtype=dace.int32)
inner_sdfg = dace.SDFG('inner')
inner_sdfg.add_array('A0', (10,), dtype=dace.int32)
inne... |
def define_tf_flags():
if (os.environ.get('SQLFLOW_USE_DEFAULT_FLAGS', '').lower() == 'true'):
return DefaultFlags()
if hasattr(tf.app.flags.FLAGS, 'task_index'):
return tf.app.flags.FLAGS
tf.app.flags.DEFINE_integer('task_index', 0, 'Worker task index')
tf.app.flags.DEFINE_string('ps_ho... |
class TestLUTActivationsQuantizerParams(unittest.TestCase):
def test_signed_lut_activation_quantization_params(self):
data = np.random.randn(3, 4, 5, 6)
(counts, bins) = np.histogram(data, bins=20)
n_bits = 4
quantization_params = lut_kmeans_histogram(bins=bins, counts=counts, p=2, n... |
class YelpFull(Task):
def __init__(self):
super().__init__()
self.class_number = 5
self.file_by_split = dict(train='yelp_review_full_csv/train.train.csv', val='yelp_review_full_csv/train.dev.csv', test='yelp_review_full_csv/test.csv')
self.max_length = 400
def read_data(path, max... |
def recursively_load_weights(fairseq_model, hf_model, is_finetuned):
unused_weights = []
fairseq_dict = fairseq_model.state_dict()
feature_extractor = (hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor)
for (name, value) in fairseq_dict.items():
is_used = False
... |
def get_data_max():
data = get_data()
xcoord = data.x.values
ycoord = data.y.values
training_data_ids = np.where(((((xcoord ** 2) + (ycoord ** 2)) - (RADI ** 2)).reshape((- 1)) > 0))[0]
data_max = {}
for v in data.keys():
data_max[v] = abs(data[v].values[training_data_ids]).max()
ret... |
def test_evaluate_prequential_delayed_classifier(tmpdir, test_path):
data = RandomTreeGenerator(tree_random_state=23, sample_random_state=12, n_classes=4, n_cat_features=2, n_num_features=5, n_categories_per_cat_feature=5, max_tree_depth=6, min_leaf_depth=3, fraction_leaves_per_level=0.15)
max_samples = 1000
... |
class BayesianMVLinReg(ConjPrior):
def __init__(self, sample=None):
self.nu = 0
self.w_0 = None
self.Lambda_0 = (np.array([[0, 0], [0, 1]]) + _epsilon)
self.V_0 = None
super().__init__(sample=sample)
def n_params(self) -> int:
d = (0 if (self.w_0 is None) else sel... |
class MLlogger():
def __init__(self, log_dir, experiment_name, args=None, name_args=[]):
self.log_dir = log_dir
self.args = vars(args)
self.name_args = name_args
mlflow.set_tracking_uri(log_dir)
mlflow.set_experiment(experiment_name)
self.auto_steps = {}
self.... |
def calc_reconstruction_loss(x, recon_x, loss_type='mse', reduction='sum'):
if (reduction not in ['sum', 'mean', 'none']):
raise NotImplementedError
recon_x = recon_x.view(recon_x.size(0), (- 1))
x = x.view(x.size(0), (- 1))
if (loss_type == 'mse'):
recon_error = F.mse_loss(recon_x, x, r... |
class AnomalibVideoDataset(AnomalibDataset, ABC):
def __init__(self, task: TaskType, transform: A.Compose, clip_length_in_frames: int, frames_between_clips: int) -> None:
super().__init__(task, transform)
self.clip_length_in_frames = clip_length_in_frames
self.frames_between_clips = frames_b... |
def test_getter_after_setter(setter_getter_test):
module_name = 'tests.fixtures.linecoverage.setter_getter'
test_case_chromosome = tcc.TestCaseChromosome(test_case=setter_getter_test)
config.configuration.statistics_output.coverage_metrics = [config.CoverageMetric.CHECKED]
tracer = ExecutionTracer()
... |
def ResUnit(inputs, filters, kernel_size, strides, scope, reuse=None):
with tf.variable_scope(scope, reuse=reuse):
outputs = tf.contrib.layers.layer_norm(inputs, scope='layernorm1', reuse=reuse)
outputs = tf.nn.relu(outputs, name='relu')
outputs = tf.layers.conv2d(outputs, filters, kernel_si... |
def setup_logging(level='INFO', log_file=None):
from logging import basicConfig
from rich.console import Console
from rich.logging import RichHandler
import pkgutil
if (True if pkgutil.find_loader('tensorflow') else False):
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(t... |
def render_comparison_continous(itmdt: Intermediate, cfg: Config) -> Dict[(str, Any)]:
plot_width = (cfg.plot.width if (cfg.plot.width is not None) else 450)
plot_height = (cfg.plot.height if (cfg.plot.height is not None) else 400)
df_labels: List[str] = cfg.diff.label
tabs: List[Panel] = []
htgs: D... |
def track_progress(func, tasks, bar_width=50, file=sys.stdout, **kwargs):
if isinstance(tasks, tuple):
assert (len(tasks) == 2)
assert isinstance(tasks[0], Iterable)
assert isinstance(tasks[1], int)
task_num = tasks[1]
tasks = tasks[0]
elif isinstance(tasks, Iterable):
... |
def main(index=0):
parser = argparse.ArgumentParser(add_help=True, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--index', type=int, default=0, help='index of datacube to use')
parser.add_argument('-a', '--all', type=bool, default=False, help='whether to use all extreme ... |
def test_prime_factor_multiplicities():
assert (prime_factor_multiplicities(90) == {Integer(2): 1, Integer(3): 2, Integer(5): 1})
assert (prime_factor_multiplicities(1) == {}) |
class JSONDecoderWithFeatureColumn(json.JSONDecoder):
def __init__(self, *args, **kwargs):
kwargs['object_hook'] = feature_column_json_hook
super(JSONDecoderWithFeatureColumn, self).__init__(*args, **kwargs) |
def printLog(*args, **kwargs):
print(*args, **kwargs)
with open('./test_log/log.txt', 'a') as file:
print(*args, **kwargs, file=file) |
def _check_for_name_clashes(stree: tn.ScheduleTreeNode):
def _traverse(node: tn.ScheduleTreeScope, scopes: List[str]):
for child in node.children:
if isinstance(child, tn.ForScope):
itervar = child.header.itervar
if (itervar in scopes):
raise N... |
def load_pose_data(data_file):
spin = (True if data_file.endswith('.json') else False)
if spin:
data = json.load(open(data_file, 'r'))
if ('rotmat_tuned' in data):
rotmat = np.array(data['rotmat_tuned'])
else:
rotmat = np.array(data['rotmat'])
poses = []
... |
def calculateScore(m):
if (_fscores is None):
readFragmentScores()
fp = rdMolDescriptors.GetMorganFingerprint(m, 2)
fps = fp.GetNonzeroElements()
score1 = 0.0
nf = 0
for (bitId, v) in iteritems(fps):
nf += v
sfp = bitId
score1 += (_fscores.get(sfp, (- 4)) * v)
... |
class GPT2ForSequenceClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class ScaledUpperTriangMaskedSoftmax(torch.autograd.Function):
def forward(ctx, inputs, scale):
scale_t = torch.tensor([scale])
softmax_results = scaled_upper_triang_masked_softmax_forward(inputs, scale_t[0])
ctx.save_for_backward(softmax_results, scale_t)
return softmax_results
... |
.parametrize('observation_shape', [(4, 84, 84), (100,)])
.parametrize('action_size', [2])
.parametrize('batch_size', [32])
.parametrize('encoder_factory', [DefaultEncoderFactory()])
def test_create_normal_policy(observation_shape: Sequence[int], action_size: int, batch_size: int, encoder_factory: EncoderFactory) -> Non... |
class MultiRPN(RPN):
def __init__(self, anchor_num, in_channels, weighted=False, fused='none'):
super(MultiRPN, self).__init__()
self.weighted = weighted
for i in range(len(in_channels)):
self.add_module(('rpn' + str((i + 2))), DepthwiseRPN(anchor_num, in_channels[i], in_channels... |
class PoincareDistance(Function):
def grad(x, v, sqnormx, sqnormv, sqdist, eps):
alpha = (1 - sqnormx)
beta = (1 - sqnormv)
z = (1 + ((2 * sqdist) / (alpha * beta)))
a = (((sqnormv - (2 * th.sum((x * v), dim=(- 1)))) + 1) / th.pow(alpha, 2)).unsqueeze((- 1)).expand_as(x)
a = ... |
class SpatialCorrelationSampler(nn.Module):
def __init__(self, kernel_size=1, patch_size=1, stride=1, padding=0, dilation=1, dilation_patch=1):
super(SpatialCorrelationSampler, self).__init__()
self.kernel_size = kernel_size
self.patch_size = patch_size
self.stride = stride
s... |
def help_documents():
docs = get_documents()
s = 'DOCUMENTs:\n'
s += format_columns(docs)
s += '\n'
if ('reference' in docs):
s += "Other valid document names take the form 'reference/DIR', where\n"
s += 'DIR is a subdirectory of SAGE_DOC_SRC/en/reference/.\n'
s += 'This buil... |
class SEModule(nn.Module):
def __init__(self, channels, reduction):
super(SEModule, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc1 = nn.Conv2d(channels, (channels // reduction), kernel_size=1, padding=0)
self.relu = nn.ReLU(inplace=True)
self.fc2 = nn.Conv2... |
class RandomNavigationAgent(ThorAgent):
def __init__(self, create_model, args, rank, gpu_id):
max_episode_length = args.max_episode_length
episode = BasicEpisode(args, gpu_id, args.strict_done)
super(RandomNavigationAgent, self).__init__(create_model(args), args, rank, episode, max_episode_l... |
class FacadeSets(CategoryWithAxiom):
def example(self, choice='subset'):
import sage.categories.examples.facade_sets as examples
if (choice == 'union'):
return examples.IntegersCompletion()
elif (choice == 'subset'):
return examples.PositiveIntegerMonoid()
els... |
def softmax_check(loader, model, K, device):
save_sm = torch.empty((0, K))
sm = nn.Softmax(dim=1)
model.eval()
with torch.no_grad():
for (images, _, confs) in loader:
(images, confs) = (images.to(device), confs.to(device))
outputs = model(images)
save_sm = tor... |
class Block(Node):
CMD = namedtuple('cmd', ['tiu', 'dma', 'all'])
def __init__(self, subnet: SubNet, indent=0, ctx_addr=0, ctx_size=0):
super().__init__()
self.subnet_id = subnet.id
self.indent = indent
self.operations: List[BaseCmd] = []
bmodel_net = atomic_context.bmode... |
class EisensteinSubmodule_gH_Q(EisensteinSubmodule_params):
def _parameters_character(self):
return self.group()
def _convert_matrix_from_modsyms_eis(self, A):
from .cuspidal_submodule import _convert_matrix_from_modsyms
symbs = self.modular_symbols(sign=0)
d = self.rank()
... |
def ExpectingFunctionArgs(clean_lines, linenum):
line = clean_lines.elided[linenum]
return (Match('^\\s*MOCK_(CONST_)?METHOD\\d+(_T)?\\(', line) or ((linenum >= 2) and (Match('^\\s*MOCK_(?:CONST_)?METHOD\\d+(?:_T)?\\((?:\\S+,)?\\s*$', clean_lines.elided[(linenum - 1)]) or Match('^\\s*MOCK_(?:CONST_)?METHOD\\d+(... |
def dist_init(old_test_method=None, setup_rpc: bool=True, clean_shutdown: bool=True, faulty_messages=None, messages_to_delay=None):
if (old_test_method is None):
return partial(dist_init, setup_rpc=setup_rpc, clean_shutdown=clean_shutdown, faulty_messages=faulty_messages, messages_to_delay=messages_to_delay... |
def OA_11_80():
from sage.rings.finite_rings.finite_field_constructor import FiniteField
A = [[(0, None), (0, None), (0, None), (0, None), (0, None), (0, None), (0, None), (0, None), (0, None), (0, None)], [(0, None), (1, None), (2, 3), (3, None), (4, 3), (2, None), (3, 3), (4, None), (0, 3), (1, 3)], [(0, None... |
def encode_image_text_with_clip(dataset, dir_to_data, num_frames, clip_model='ViT-B/32', image_only=False):
device = ('cuda' if torch.cuda.is_available() else 'cpu')
time_meters = defaultdict(AverageMeter)
tictoc = time.time()
(model, preprocess) = clip.load(clip_model, device=device)
model_text = b... |
def create_argparser():
defaults = dict(root='', schedule_sampler='uniform', lr=0.0001, 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, target='vocals', seq_dur=4.2, samples_p... |
def rotation_loss_class(out_rotation_x, angle_x):
length = out_rotation_x.size((- 1))
label = ((((angle_x.view((- 1)).cuda() + pi) / 2) / np.pi) * length)
label[(label < 0)] += length
label[(label >= length)] -= length
if (out_rotation_x.size((- 1)) == 1):
loss_x = ((out_rotation_x - angle_x... |
class BufferType(BaseType):
is_buffer = 1
writable = True
subtypes = ['dtype']
def __init__(self, base, dtype, ndim, mode, negative_indices, cast):
self.base = base
self.dtype = dtype
self.ndim = ndim
self.buffer_ptr_type = CPtrType(dtype)
self.mode = mode
... |
def overlap_curves(fig, xlabels, avg, std, legend, color, path, title='', x_str='', y_str='', dpi=300, ylimup=None, ylimdown=None, step=10.0):
if (ylimup is None):
ylimup = 105.0
if (ylimdown is None):
ylimdown = 0.0
font_sz = 10
tiks_fsz = 7
plt.figure(fig.number)
x = list(range... |
def p1NFlist(N):
k = N.number_field()
L = [MSymbol(N, k(0), k(1), check=False)]
L = (L + [MSymbol(N, k(1), r, check=False) for r in N.residues()])
from sage.arith.misc import divisors
for D in divisors(N):
if ((not D.is_trivial()) and (D != N)):
if D.is_principal():
... |
def create_entity_cluster_bow_lexical_vec(entity_cluster, model, device, use_char_embeds, requires_grad):
if use_char_embeds:
bow_vec = torch.zeros((model.embedding_dim + model.char_hidden_dim), requires_grad=requires_grad).to(device).view(1, (- 1))
else:
bow_vec = torch.zeros(model.embedding_di... |
.entry
def test_viz_lm():
model_config = Gpt2Config(num_layers=2, num_heads=2, hidden_dim=32, seq_len=32)
with tempfile.TemporaryDirectory() as f:
try:
data_config = tiny_test_corpus.tiny_corpus_config(f)
tok = data_config.the_tokenizer
Vocab = haliax.Axis('vocab', le... |
class Model(nn.Module):
def __init__(self, in_channels, out_channels, latent_size, spiral_indices, down_transform, up_transform, is_vae=False):
super(Model, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.latent_size = latent_size
self.sp... |
def register_types(module):
root_module = module.get_root()
module.add_class('Address', import_from_module='ns.network')
module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network')
module.add_class('AsciiTraceHelper', import_from_module='ns.networ... |
def _fake_quantize_per_channel_affine_grad_reference(dY, X, per_channel_scale, per_channel_zero_point, axis, quant_min, quant_max):
(X, permute_axis_list) = _permute_to_axis_zero(X, axis)
Xq = torch.zeros_like(X)
for i in range(X.size()[0]):
Xq[i] = torch.round(((X[i] * (1.0 / per_channel_scale[i]))... |
class AlgebraicNumber(AlgebraicNumber_base):
def __init__(self, x):
AlgebraicNumber_base.__init__(self, QQbar, x)
def __reduce__(self):
return (AlgebraicNumber, (self._descr,))
def _richcmp_(self, other, op):
if (self is other):
return rich_to_bool(op, 0)
sd = sel... |
def id2label(image):
array = np.array(image)
out_array = np.empty(array.shape, dtype=array.dtype)
for l in labels:
out_array[(array == l.id)] = l.trainId
return Image.fromarray(out_array) |
class ShapeSpec(namedtuple('_ShapeSpec', ['channels', 'height', 'width', 'stride'])):
def __new__(cls, *, channels=None, height=None, width=None, stride=None):
return super().__new__(cls, channels, height, width, stride) |
class RE25():
def __init__(self):
self.problem_name = 'RE25'
self.n_objectives = 2
self.n_variables = 3
self.n_constraints = 0
self.n_original_constraints = 6
self.ubound = np.zeros(self.n_variables)
self.lbound = np.zeros(self.n_variables)
self.lbound... |
class TryFinallyStatNode(StatNode):
child_attrs = ['body', 'finally_clause', 'finally_except_clause']
preserve_exception = 1
handle_error_case = True
func_return_type = None
finally_except_clause = None
is_try_finally_in_nogil = False
in_generator = False
def create_analysed(pos, env, bo... |
class TPredicate(object):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
_snap.TPredicate_swiginit(self, _snap.new_TPredicate(*args))
def GetVariables(self, Variables):
return _s... |
def iterator(model, dataloader, **kwargs):
model.eval()
with torch.no_grad():
for (current_step, input_data) in enumerate(dataloader):
input_data_gpu = {}
for (k, v) in input_data.items():
if isinstance(v, torch.Tensor):
input_data_gpu[k] = v.d... |
class TestConcatenateTrainingData(unittest.TestCase):
def setUp(self):
self.train_sequences = [np.zeros((3, 2)), np.ones((4, 2))]
self.train_cluster_ids = [['a', 'b', 'a'], np.array(['a', 'b', 'c', 'b'])]
def test_noenforce_noshuffle(self):
(concatenated_train_sequence, concatenated_trai... |
def test(model, device, test_loader, epoch):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for (data, target) in test_loader:
(data, target) = (data.to(device), target.to(device))
output = model(data)
output = torch.nn.functional.log_softmax(out... |
def dot(x: tf.Tensor, y: tf.Tensor, sparse: bool=False) -> tf.Tensor:
if sparse:
res = tf.sparse.sparse_dense_matmul(x, y)
else:
res = tf.matmul(x, y)
return res |
def NIR_calc(P, POP):
try:
max_P = max(list(P.values()))
length = POP
return (max_P / length)
except Exception:
return 'None' |
class FileLogger():
def __init__(self, output_dir: str, global_rank: int, local_rank: int, name: str, world_size: int, name_prefix=''):
self.output_dir = output_dir
if (not os.path.exists(self.output_dir)):
os.makedirs(self.output_dir, exist_ok=True)
self.logger = FileLogger.get_... |
class LayoutLMv2Processor():
def __init__(self, feature_extractor, tokenizer):
if (not isinstance(feature_extractor, LayoutLMv2FeatureExtractor)):
raise ValueError(f'`feature_extractor` has to be of type {LayoutLMv2FeatureExtractor.__class__}, but is {type(feature_extractor)}')
if (not i... |
def hard_sigmoid_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes):
dy = grad_inputs[0]
x0 = inputs[0]
m0 = F.greater_scalar(x0, (- 2.5))
m1 = F.less_scalar(x0, 2.5)
m01 = (m0 * m1)
m01 = no_grad(m01)
dx0 = ((dy * 0.2) * m01)
return dx0 |
class FeatureDataset(IterableDataset):
def __init__(self, args, shards_path, all_shards_path, node_selection=identity, shard_shuffle=identity, is_train=True):
self.shards_path = shards_path
self.all_shards_path = all_shards_path
if is_train:
if isinstance(args.computation.num_gpu... |
def get_b16s_config():
config = ml_collections.ConfigDict()
config.patches = ml_collections.ConfigDict({'size': (16, 16)})
config.hidden_size = 128
config.transformer = ml_collections.ConfigDict()
config.transformer.mlp_dim = 512
config.transformer.num_heads = 8
config.transformer.num_layers... |
class Checkpointer(object):
def __init__(self, model, optimizer=None, scheduler=None, save_dir='', save_to_disk=None, logger=None):
self.model = model
self.optimizer = optimizer
self.scheduler = scheduler
self.save_dir = save_dir
self.save_to_disk = save_to_disk
if (l... |
def deconv3(in_planes, out_planes, kernel_size=4, stride=2, padding=1):
return nn.Sequential(torch.nn.ConvTranspose2d(in_channels=in_planes, out_channels=out_planes, kernel_size=4, stride=2, padding=1, bias=True), nn.PReLU(out_planes), nn.Conv2d(out_planes, out_planes, 3, 1, 1), nn.PReLU(out_planes), nn.Conv2d(out_... |
class StochasticScriptAgent(BaseScriptAgent):
def __init__(self):
super().__init__()
def reset(self, mdp, state, player_idx):
pass
def step(self, mdp, state, player_idx):
action = np.random.choice(Action.ALL_ACTIONS)
return action |
class ConstantPad2d(_ConstantPadNd):
__constants__ = ['padding', 'value']
padding: _size_4_t
def __init__(self, padding: _size_4_t, value: float) -> None:
super(ConstantPad2d, self).__init__(value)
self.padding = _quadruple(padding) |
def convert_boolean_value(var, default_value):
if (var.strip().lower() == 'y'):
converted_var = True
elif (var.strip().lower() == 'n'):
converted_var = False
else:
converted_var = default_value
return converted_var |
class InputStream(object):
def __init__(self, stream):
self._stream = stream
def read(self, *args):
if (len(args) == 0):
warn("WSGI does not guarantee an EOF marker on the input stream, thus making calls to 'wsgi.input.read()' unsafe. Conforming servers may never return from this cal... |
class Encoder(nn.Module):
def __init__(self, input_size, embedding_size, hidden_size, num_layers, p):
super(Encoder, self).__init__()
self.dropout = nn.Dropout(p)
self.hidden_size = hidden_size
self.num_layers = num_layers
self.embedding = nn.Embedding(input_size, embedding_s... |
def test_parametrized_fixture(testdir, openapi3_base_url, is_older_subtests):
testdir.make_test(f'''
schema.base_url = "{openapi3_base_url}"
(params=["a", "b"])
def parametrized_lazy_schema(request):
return schema
lazy_schema = schemathesis.from_pytest_fixture("parametrized_lazy_schema")
_schema.parametrize()
d... |
class UnaryOpSparseFuzzer(Fuzzer):
def __init__(self, seed, dtype=torch.float32, cuda=False):
super().__init__(parameters=[FuzzedParameter('dim_parameter', distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True), FuzzedParameter(name='sparse_dim', distribution={1: 0.4, 2: 0.4, 3: 0.2}, strict=True), [FuzzedPara... |
def load_tr_te_data(csv_file_tr, csv_file_te):
tp_tr = pd.read_csv(csv_file_tr)
tp_te = pd.read_csv(csv_file_te)
start_idx = min(tp_tr['uid'].min(), tp_te['uid'].min())
end_idx = max(tp_tr['uid'].max(), tp_te['uid'].max())
(rows_tr, cols_tr) = ((tp_tr['uid'] - start_idx), tp_tr['sid'])
(rows_te,... |
def JDUTC_to_BJDTDB(JDUTC, starname='', hip_id=None, ra=None, dec=None, epoch=None, pmra=None, pmdec=None, px=None, rv=None, obsname='', lat=0.0, longi=0.0, alt=0.0, ephemeris='de430', leap_dir=os.path.join(os.path.dirname(__file__), 'data'), leap_update=True):
corr_time = []
warning = []
error = []
sta... |
class DropPath(nn.ModuleDict):
def __init__(self, drop_prob=None):
super(DropPath, self).__init__()
self.drop_prob = drop_prob
def forward(self, x):
return drop_path(x, self.drop_prob, self.training) |
class NoSuchTileError(Exception):
def __init__(self, lat, lon):
Exception.__init__()
self.lat = lat
self.lon = lon
def __str__(self):
return ('No SRTM tile for %d, %d available!' % (self.lat, self.lon)) |
def to_graphics_array(graph_list, **kwds):
from sage.graphs import graph
plist = []
for graph_i in graph_list:
if isinstance(graph_i, graph.GenericGraph):
pos = graph_i.get_pos()
if (pos is None):
if ('layout' not in kwds):
kwds['layout'] =... |
def _build_model(args):
inp = Input(shape=args['input_dimention'], name='input')
model = cred2(nb_filters=[8, 16, 16, 32, 32, 64, 64], kernel_size=[11, 9, 7, 7, 5, 5, 3], padding=args['padding'], activationf=args['activation'], cnn_blocks=args['cnn_blocks'], BiLSTM_blocks=args['lstm_blocks'], drop_rate=args['dr... |
def save_model(model, epoch, update_best=False, **kwargs):
save_dir = os.path.join(kwargs['save_dir'], 'checkpoints', '{:s}_{:s}_{:s}'.format(kwargs['model_name'].lower(), kwargs.get('page_retrieval', '').lower(), kwargs['dataset_name'].lower()))
model.model.save_pretrained(os.path.join(save_dir, 'model__{:d}.c... |
def test_ast_resolver_alias():
import taichi
taichi.init()
node = ast.parse('taichi.kernel', mode='eval').body
assert ASTResolver.resolve_to(node, taichi.kernel, locals())
import taichi as tc
node = ast.parse('tc.kernel', mode='eval').body
assert ASTResolver.resolve_to(node, tc.kernel, local... |
def user_config_dir(appname=None, appauthor=None, version=None, roaming=False):
if (system in ['win32', 'darwin']):
path = user_data_dir(appname, appauthor, None, roaming)
else:
path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
if appname:
path = os.path.jo... |
def _get_dataloaders(params):
batch_size = params.batch_size
labeled_source_bs = batch_size
unlabeled_source_bs = batch_size
unlabeled_target_bs = batch_size
if (params.us and params.ut):
unlabeled_source_bs //= 2
unlabeled_target_bs //= 2
(ls, us, ut) = (None, None, None)
if... |
def GenerateSM90_TensorOp_1684_symm(manifest, cuda_version):
if (not CudaToolkitVersionSatisfies(cuda_version, 11, 8)):
return
layouts = [(LayoutType.ColumnMajor, LayoutType.ColumnMajor)]
side_modes = [SideMode.Left, SideMode.Right]
fill_modes = [FillMode.Lower, FillMode.Upper]
math_inst = M... |
class TestRMSNormOp(hu.HypothesisTestCase):
(M=st.integers(0, 8), N=st.integers(1, 16), eps=st.floats(0, 0.001), dtype=st.sampled_from([np.float32, np.float64]), **hu.gcs)
(deadline=None)
def test_rms_norm(self, M, N, eps, dtype, gc, dc):
X = ((np.random.randn(M, N) * 2.0) + 1.0).astype(dtype)
... |
class ModularCorrespondenceDatabase(ModularPolynomialDatabase):
def _dbpath(self, level):
(Nlevel, crrlevel) = level
return ('PolMod/%s/crr.%02d.%03d.dbz' % (self.model, Nlevel, crrlevel)) |
def test_MultiProcDataset_exception_at_init():
with timeout():
mp_dataset = MultiProcDataset(dataset={'class': 'MapDatasetWrapper', 'map_dataset': _MyCustomMapDatasetThrowingExceptionAtInit}, num_workers=1, buffer_size=1)
try:
mp_dataset.initialize()
except Exception as exc:
... |
def get_task(model: str, use_auth_token: Optional[str]=None) -> str:
if is_offline_mode():
raise RuntimeError('You cannot infer task automatically within `pipeline` when using offline mode')
try:
info = model_info(model, token=use_auth_token)
except Exception as e:
raise RuntimeError... |
class ResLayer(nn.Sequential):
def __init__(self, block, num_blocks, in_channels, out_channels, expansion=None, stride=1, avg_down=False, conv_cfg=None, norm_cfg=dict(type='BN'), act_cfg=dict(type='ReLU', inplace=True), conv_cfg_inv=None, norm_cfg_inv=None, act_cfg_inv=None, **kwargs):
self.block = block
... |
def _exact_inf_norm(A):
if scipy.sparse.isspmatrix(A):
return max(abs(A).sum(axis=1).flat)
elif is_pydata_spmatrix(A):
return max(abs(A).sum(axis=1))
else:
return np.linalg.norm(A, np.inf) |
def CyclicCover(r, f, names=None, check_smooth=True):
if (not isinstance(f, Polynomial)):
raise TypeError(('Arguments f (= %s) must be a polynomial' % (f,)))
P = f.parent()
f = P(f)
if check_smooth:
if (P(r) == 0):
raise ValueError('As the characteristic divides the order of ... |
class Gpt2Transformer(StateDictSerializationMixin, eqx.Module):
config: Gpt2Config = eqx.static_field()
blocks: Stacked[Gpt2Block]
ln_f: hnn.LayerNorm
def init(config: Gpt2Config, *, key):
blocks = Stacked.init(config.Layers, Gpt2Block, gradient_checkpointing=config.gradient_checkpointing)(confi... |
def MI_loss(mus, sigmas, i_c, alpha=1e-08):
kl_divergence = (0.5 * torch.sum(((((mus ** 2) + (sigmas ** 2)) - torch.log(((sigmas ** 2) + alpha))) - 1), dim=1))
MI_loss = (torch.mean(kl_divergence) - i_c)
return MI_loss |
class TdmTwinSAC(TemporalDifferenceModel, TwinSAC):
def __init__(self, env, qf1, qf2, vf, twin_sac_kwargs, tdm_kwargs, base_kwargs, policy=None, eval_policy=None, replay_buffer=None, dense_log_pi=True, optimizer_class=optim.Adam, **kwargs):
TwinSAC.__init__(self, env=env, qf1=qf1, qf2=qf2, vf=vf, policy=pol... |
def unstack_lstm(lstm):
device = next(iter(lstm.parameters())).device
in_size = lstm.input_size
hidden_dim = lstm.hidden_size
layers = []
for i in range(lstm.num_layers):
layer = nn.LSTM(in_size, hidden_dim, batch_first=True, bidirectional=True)
layer.to(device)
attributes = ... |
_function(pre=[square])
def fp(x: DataPoint) -> int:
return (0 if (x.num_squared > 42) else (- 1)) |
(arg_at(0, assert_tensor))
def _reduce(mat, fun: template()):
shape = static(mat.get_shape())
if static((len(shape) == 1)):
result = mat[0]
for i in static(range(1, shape[0])):
result = fun(result, mat[i])
return result
result = mat[(0, 0)]
for i in static(range(shape... |
class BottomLeftPoolFunction(Function):
def forward(ctx, input, guide):
(output, maxout) = _C.bl_pool_forward(input, guide)
ctx.save_for_backward(input, output, guide, maxout)
return output
def backward(ctx, grad_output):
(input, output, guide, maxout) = ctx.saved_variables
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.