code stringlengths 101 5.91M |
|---|
def process_log(log_file, job_types):
jobs = {}
with open(log_file, 'r') as f:
for line in f:
if ('[Job dispatched]' in line):
dispatch_time = float(line.split(']')[0])
job_id = int(line.strip().split('Job ID:')[(- 1)])
jobs[job_id] = Job(job_i... |
def test_lw_tree(dataset: str, version: str, workload: str, params: Dict[(str, Any)], overwrite: bool) -> None:
model_file = ((MODEL_ROOT / dataset) / f"{params['model']}.pkl")
L.info(f'Load model from {model_file} ...')
with open(model_file, 'rb') as f:
state = pickle.load(f)
table = load_table... |
class MetaLinear(nn.Linear, MetaModule):
__doc__ = nn.Linear.__doc__
def forward(self, input, params=None):
if (params is None):
params = OrderedDict(self.named_parameters())
bias = params.get('bias', None)
return F.linear(input, params['weight'], bias) |
class GripperJointPosition(GripperActionMode):
def __init__(self, attach_grasped_objects: bool=True, detach_before_open: bool=True, absolute_mode: bool=True):
self._attach_grasped_objects = attach_grasped_objects
self._detach_before_open = detach_before_open
self._absolute_mode = absolute_mo... |
def rle2bmask(rle):
bm = cocomask.decode(rle)
if (len(bm.shape) == 3):
bm = np.sum(bm, axis=2)
bm = bm.astype(np.uint8)
return bm |
class LibrispeechLm(datasets.GeneratorBasedBuilder):
VERSION = datasets.Version('0.1.0')
BUILDER_CONFIG_CLASS = LibrispeechLmConfig
def _info(self):
return datasets.DatasetInfo(description=_DESCRIPTION, features=datasets.Features({'text': datasets.Value('string')}), supervised_keys=('text', 'text'),... |
class DepthwiseSeparableConvModule(nn.Module):
def __init__(self, in_channels: int, out_channels: int, kernel_size: Union[(int, Tuple[(int, int)])], stride: Union[(int, Tuple[(int, int)])]=1, padding: Union[(int, Tuple[(int, int)])]=0, dilation: Union[(int, Tuple[(int, int)])]=1, norm_cfg: Optional[Dict]=None, act_... |
def _set_wrap_both(padded, axis, width_pair):
(left_pad, right_pad) = width_pair
period = ((padded.shape[axis] - right_pad) - left_pad)
new_left_pad = 0
new_right_pad = 0
if (left_pad > 0):
right_slice = _slice_at_axis(slice(((- right_pad) - min(period, left_pad)), ((- right_pad) if (right_p... |
class PlusInfinity(_uniq, AnInfinity, InfinityElement):
_sign = 1
_sign_char = '+'
def __init__(self):
InfinityElement.__init__(self, InfinityRing)
def __hash__(self):
return maxsize
def _richcmp_(self, other, op):
if isinstance(other, PlusInfinity):
return rich_t... |
.parametrize('hidden_units,activation', [(hidden_units, activation) for hidden_units in [(), (10,)] for activation in ['sigmoid', Dice, PReLU]])
def test_LocalActivationUnit(hidden_units, activation):
if ((tf.__version__ >= '1.13.0') and (activation != 'sigmoid')):
return
with CustomObjectScope({'LocalA... |
class GCDataset():
dataset: Dataset
p_randomgoal: float
p_trajgoal: float
p_currgoal: float
geom_sample: int
discount: float
terminal_key: str = 'dones_float'
reward_scale: float = 1.0
reward_shift: float = (- 1.0)
terminal: bool = True
def get_default_config():
retur... |
def plot_column_per_patient(df_demo: pd.DataFrame, path_to_output_dir: str, column: str, x_label: str, title: str, max_clamp: int=None):
(fig, axes) = plt.subplots(1, 3, figsize=(20, 5))
for (idx, split) in enumerate(['train', 'val', 'test']):
df_ = df_demo[(df_demo['split'] == split)]
counts = ... |
def test_pipeline_with_dependencies():
class PassA(MyPass):
def depends_on(self):
return {MyPass}
def apply_pass(self, sdfg, pipeline_results):
res = super().apply_pass(sdfg, pipeline_results)
return (pipeline_results['MyPass'] + res)
p = PassA()
pipe = pp... |
class _MyFormatter(logging.Formatter):
def format(self, record):
date = colored('[%(asctime)s %(filename)s:%(lineno)d]', 'green')
msg = '%(message)s'
if (record.levelno == logging.WARNING):
fmt = ((((date + ' ') + colored('WRN', 'red', attrs=['blink'])) + ' ') + msg)
elif... |
class staggered_object_creation(object):
def __init__(self, local_rank: int, world_size: int):
super().__init__()
self.local_rank = local_rank
self.world_size = world_size
def __enter__(self, *args, **kwargs):
del args, kwargs
if ((self.world_size > 1) and ((self.local_ra... |
def run_single_experiment(dataset: str, savedir: str, named_configs: List, config_updates: Dict[(str, Any)]):
from tape.__main__ import proteins
config_updates.update({'training': {'learning_rate': 0.0001, 'use_memory_saving_gradients': True}, 'num_epochs': 1000, 'steps_per_epoch': 200, 'tasks': dataset})
i... |
def DoWhile(name, condition_blob_or_net, nets_or_steps):
(condition_not_net, stop_blob) = NotNet(condition_blob_or_net)
if isinstance(condition_blob_or_net, core.Net):
nets_or_steps = _AppendNets(nets_or_steps, condition_blob_or_net, condition_not_net)
else:
nets_or_steps = _AppendNets(nets_... |
_utils.test()
def test_floor_div_pythonic():
z = ti.field(ti.i32, shape=())
def func(x: ti.i32, y: ti.i32):
z[None] = (x // y)
for i in range((- 10), 11):
for j in range((- 10), 11):
if (j != 0):
func(i, j)
assert (z[None] == (i // j)) |
class MultiplicativeNCSymBases(Category_realization_of_parent):
def super_categories(self):
return [NCSymBases(self.base())]
def _repr_(self):
return 'Category of multiplicative bases of symmetric functions in non-commuting variables over the {}'.format(self.base().base_ring())
class ParentM... |
('revnet-56')
class RevNet56Config(ResNet50Config):
def __init__(self):
super(RevNet56Config, self).__init__()
self.model_class = 'revnet'
self.manual_gradients = True
self.num_residual_units = [2, 2, 3, 2]
self.filters = [128, 128, 256, 512, 832] |
def main():
parser = argparse.ArgumentParser('Interface for DE-GNN framework')
parser.add_argument('--dataset', type=str, default='celegans', help='dataset name')
parser.add_argument('--test_ratio', type=float, default=0.1, help='ratio of the test against whole')
parser.add_argument('--model', type=str,... |
class ClientComm():
def __init__(self, agentName):
self.TOKEN_SEP = '#'
self.io = IOSocket(CompetitionParameters.SOCKET_PORT)
self.sso = SerializableStateObservation()
self.agentName = agentName
self.lastMessageId = 0
self.LOG = False
self.player = None
... |
def certificate_matches(certificate, known_hash):
try:
cert_pem = certificate.exportKey()
cert_bin = cert_pem.replace('-----BEGIN CERTIFICATE-----', '')
cert_bin = cert_bin.replace('-----END CERTIFICATE-----', '')
cert_bin = cert_bin.replace(' ', '')
cert_bin = cert_bin.repla... |
class TestToeplitz():
def setup_method(self, method):
if ((os.getenv('UNLOCK_SEED') is None) or (os.getenv('UNLOCK_SEED').lower() == 'false')):
self.rng_state = torch.get_rng_state()
torch.manual_seed(0)
if torch.cuda.is_available():
torch.cuda.manual_seed... |
def block_inception_c(input):
if (K.image_dim_ordering() == 'th'):
channel_axis = 1
else:
channel_axis = (- 1)
branch_0 = conv2d_bn(input, 256, 1, 1)
branch_1 = conv2d_bn(input, 384, 1, 1)
branch_10 = conv2d_bn(branch_1, 256, 1, 3)
branch_11 = conv2d_bn(branch_1, 256, 3, 1)
b... |
class ProtoGraphGenerator():
def __init__(self, names, params):
if (names is not None):
self.names = {v.data: k for (k, v) in names.items()}
else:
self.names = {}
self.names.update(params)
self.params = params
self.variables = {}
def __enter__(self... |
class ValidationScorerBase():
def evaluate(self, model):
raise NotImplementedError()
def __call__(self, model):
model.feature_extractor.eval()
with torch.no_grad():
val_loss = self.evaluate(model)
model.feature_extractor.train()
return val_loss |
def forward(x, is_training=True, update_batch_stats=True, seed=1234):
if is_training:
return logit(x, is_training=True, update_batch_stats=update_batch_stats, stochastic=True, seed=seed)
else:
return logit(x, is_training=False, update_batch_stats=update_batch_stats, stochastic=False, seed=seed) |
def eval(source, target):
targets = ((Path('targets') / target) / 'task23.csv')
targets = pd.read_csv(targets)
targets = targets[(targets['phase_label'] == 'P')]
dataset = data.get_dataset_by_name(data_aliases[target])(sampling_rate=100, component_order='Z', dimension_order='NCW', cache=None)
model_... |
def test_fit_2():
X = [1, 2, 3]
y = ['a', 'b', 'c']
classifier = ConstantClassifier()
with pytest.raises(ValueError):
classifier.fit(X, y) |
def isomers_c9h10n2o2pf2cl(mean_function='geometric', n_samples=250) -> GoalDirectedBenchmark:
specification = uniform_specification(n_samples)
return GoalDirectedBenchmark(name='C9H10N2O2PF2Cl', objective=IsomerScoringFunction('C9H10N2O2PF2Cl', mean_function=mean_function), contribution_specification=specifica... |
def populate_node_menu(viz, node, menu, statistics_collector):
menu_item = Gtk.MenuItem('Show Interface Statistics')
menu_item.show()
def _show_it(dummy_menu_item):
ShowInterfaceStatistics(viz, node.node_index, statistics_collector)
menu_item.connect('activate', _show_it)
menu.add(menu_item) |
def list_datasets():
dataset_list = filter_english_datasets()
dataset_list.sort(key=(lambda x: x.lower()))
return dataset_list |
def test_bytemasked_concatenate():
one = ak.contents.ByteMaskedArray(ak.index.Index8([True, True, False, True, False, True]), ak.highlevel.Array([1, 2, 3, 4, 5, 6]).layout, valid_when=True)
two = ak.contents.ByteMaskedArray(ak.index.Index8([True, False, False, True, True]), ak.highlevel.Array([7, 99, 999, 8, 9]... |
def euler_to_vec(yaw, pitch):
v = Vector([0.0, 0.0, 0.0])
v[0] = (sin(yaw) * cos(pitch))
v[1] = sin(pitch)
v[2] = (cos(yaw) * cos(pitch))
return v |
def attention_bias_ignore_padding(tokens_to_keep):
mask = (tf.cast((1 - tokens_to_keep), tf.float32) * constants.VERY_SMALL)
return tf.expand_dims(tf.expand_dims(mask, axis=1), axis=1) |
class StretchAudio(object):
def __init__(self, max_scale=0.2):
self.max_scale = max_scale
def __call__(self, data):
if (not should_apply_transform()):
return data
scale = random.uniform((- self.max_scale), self.max_scale)
data = librosa.effects.time_stretch(data, (1 +... |
def hecke_operator_on_basis(B, n, k, eps=None, already_echelonized=False):
if (not isinstance(B, (list, tuple))):
raise TypeError(('B (=%s) must be a list or tuple' % B))
if (len(B) == 0):
if (eps is None):
R = CyclotomicField(1)
else:
R = eps.base_ring()
... |
def load_successes_from_disk(succ_dir, succ_traj, prune_trials, target_count, cap_count=None, min_count=None):
tuple_counts = {}
for (root, dirs, files) in os.walk(succ_dir):
for d in dirs:
if (d.count('-') == 4):
(goal, pickup, movable, receptacle, scene_num) = d.split('-')
... |
_numpy_output(check_dtype=True)
def test_ufunc_less_ff(A: dace.float32[10], B: dace.float32[10]):
return np.less(A, B) |
class Test_LinkEmbedding(object):
d = 100
d_out = 10
def test_ip(self):
(x_src, x_dst) = make_orthonormal_vectors(self.d)
x_src = tf.constant(x_src, shape=(1, self.d), dtype='float64')
x_dst = tf.constant(x_dst, shape=(1, self.d), dtype='float64')
li = LinkEmbedding(method='i... |
def diff_prod(f_derivs, u, g, X, interval, end, uderivs, atc):
from sage.symbolic.relation import solve
for l in interval:
D = {}
rhs = []
lhs = []
new_vars = []
for t in combinations_with_replacement(X, l):
t = list(t)
s = (t + end)
lh... |
class CCTest(ClassifierBaseTest):
def test_if_sparse_classification_works_on_non_dense_base_classifier(self):
classifier = ClassifierChain(classifier=SVC(probability=True), require_dense=[False, True])
self.assertClassifierWorksWithSparsity(classifier, 'sparse')
self.assertClassifierPredicts... |
def main(N, family, bc):
SD = FunctionSpace(N, family=family, bc=bcs[bc], domain=domain, alpha=1, beta=1)
K1 = FunctionSpace(N, family='F', dtype='D')
K2 = FunctionSpace(N, family='F', dtype='d')
subcomms = Subcomm(comm, [0, 0, 1])
T = TensorProductSpace(subcomms, (K1, SD, K2), axes=(1, 0, 2))
B... |
def _new_process_group_helper(world_size, rank, group_ranks, in_group, group_name, timeout=_default_pg_timeout):
global _pg_map
global _group_count
global _pg_names
if (not group_name):
group_name = str(_group_count)
_group_count += 1
if (group_name in _pg_names.values()):
ra... |
def get_data(path_wikisql, args, online_setup=None):
(train_data, train_table, dev_data, dev_table, _, _) = load_wikisql(path_wikisql, args.toy_model, args.toy_size, no_w2i=True, no_hs_tok=True)
if (online_setup is not None):
train_data = [item for (idx, item) in enumerate(train_data) if (idx in set(onl... |
def _assign_variables(formula_node, var_dict):
tester = (lambda node: (isinstance(node, FormulaNode) and node.is_leaf() and (node.signature in var_dict)))
getter = (lambda node: var_dict[node.signature])
if (not isinstance(formula_node, FormulaNode)):
raise Exception(('%s: %r' % (formula_node.__clas... |
def main(args, config):
utils.init_distributed_mode(args)
device = torch.device(args.device)
seed = (args.seed + utils.get_rank())
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
cudnn.benchmark = True
start_epoch = 0
max_epoch = config['schedular']['epochs']
warmu... |
def _find_root_python_package(full_path):
p = len(full_path)
while True:
p = full_path.rfind('/', 0, p)
assert (p > 0)
d = full_path[:p]
assert os.path.isdir(d)
if (not os.path.exists((d + '/__init__.py'))):
return d |
def normalize_profile(profile, precision=None, truncation_type='auto', p=2, generic=None):
from sage.rings.infinity import Infinity
if (truncation_type == 'zero'):
truncation_type = 0
if (truncation_type == 'infinity'):
truncation_type = Infinity
if (generic is None):
generic = (... |
class BQQmat(SpectralMatrix):
def assemble(self, method):
(test, trial) = (self.testfunction, self.trialfunction)
assert isinstance(test[0], Q)
assert isinstance(trial[0], Q)
return {0: get_norm_sq(test[0], trial[0], method)} |
def ism_from_django_qs(qs, bounds_class=Bounds3D, bounds_schema={}, with_payload=None, progress=None):
def django_accessor(row, field):
fields = field.split('.')
output = row
for field in fields:
output = attrgetter_accessor(output, field)
return output
final_schema =... |
.script
def recurrent_scaleshift(x, scale, shift):
y = x
for i in range(64):
y = ((scale * y) + shift)
return y |
def lex_groebner_basis_points(points, variables):
leads = variety_lex_leading_terms(points, variables)
return [(nf_lex_points(l, points) + l) for l in leads] |
def run_with_reloader(main_func, extra_files=None, interval=1, reloader_type='auto'):
import signal
reloader = reloader_loops[reloader_type](extra_files, interval)
signal.signal(signal.SIGTERM, (lambda *args: sys.exit(0)))
try:
if (os.environ.get('WERKZEUG_RUN_MAIN') == 'true'):
ensu... |
def main(unused_argv):
encoded_params = GetEncodedParams()
output_results_file = os.path.join(FLAGS.results_dir, (encoded_params + '.json'))
output_model_file = os.path.join(FLAGS.train_dir, (encoded_params + '.pkl'))
if (os.path.exists(output_results_file) and (not FLAGS.retrain)):
print(('Exit... |
class BiTemperedLogisticLoss(nn.Module):
def __init__(self, t1: float, t2: float, smoothing=0.0, ignore_index=None, reduction: str='mean'):
super(BiTemperedLogisticLoss, self).__init__()
self.t1 = t1
self.t2 = t2
self.smoothing = smoothing
self.reduction = reduction
s... |
class SomicDataset(Dataset):
def __init__(self, cfg: T.DictConfig, augs_dict: T.Dict[(str, T.Compose)], data_type: str):
self.base = Path(cfg.dataset.base)
self.augs = augs_dict[data_type]
self.stem_list = []
df = pd.read_csv((self.base / 'info.csv'))
for query in cfg.dataset... |
class SimpleScrapingLocator(Locator):
decoders = {'deflate': zlib.decompress, 'gzip': (lambda b: gzip.GzipFile(fileobj=BytesIO(d)).read()), 'none': (lambda b: b)}
def __init__(self, url, timeout=None, num_workers=10, **kwargs):
super(SimpleScrapingLocator, self).__init__(**kwargs)
self.base_url ... |
def perturb_single(img: torch.FloatTensor, eps: float, min_pixel=(- 1.0), max_pixel=1.0) -> torch.Tensor:
r = (max_pixel - min_pixel)
b = (r * torch.rand(img.shape))
b += min_pixel
noise = (eps * b)
noise = noise.cuda()
return torch.clamp((img + noise), min_pixel, max_pixel) |
.sm70
_utils.test(arch=[ti.cpu, ti.cuda])
def test_atomic_add_f16():
f = ti.field(dtype=ti.f16, shape=2)
def foo():
for i in range(1000):
f[0] += 1.12
for _ in range(1):
for i in range(1000):
f[1] = (f[1] + 1.12)
foo()
assert (f[0] == test_utils.ap... |
def test_kwargs_validate():
modelc = ModelC({'int_field': 3, 'string_field': 'hi'})
modelc.validate() |
def _check_errors(ret, func, args):
if (ret <= 0):
raise RuntimeError(('FMFT returned error code %d for the given arguments' % ret))
return ret |
.parametrize('extensionarray', [False, True])
def test_numpyarray(tmp_path, extensionarray):
akarray = ak.contents.NumpyArray(np.array([1.1, 2.2, 3.3]), parameters={'which': 'inner'})
paarray = akarray.to_arrow(extensionarray=extensionarray)
arrow_round_trip(akarray, paarray, extensionarray)
parquet_rou... |
_grad()
def evaluate(model, data_loader, tokenizer, device, config, info='None'):
model.eval()
metric_logger = utils.MetricLogger(delimiter=' ')
header = f'{info} Evaluation:'
print_freq = 50
for (images, text, targets) in metric_logger.log_every(data_loader, print_freq, header):
(images, t... |
class AdaptiveMaxPool2d(_AdaptiveMaxPoolNd):
output_size: _size_2_t
def forward(self, input: Tensor) -> Tensor:
return cF.complex_fcaller(F.adaptive_max_pool2d, input, self.output_size, self.return_indices) |
class DummyDumpDB(DumpDB):
language = None
def __init__(self):
pass
def get_paragraphs(self, page_title: str):
return SAMPLE_PARAGRAPHS[page_title]
def is_disambiguation(self, title: str):
return False
def is_redirect(self, title: str):
return False
def resolve_re... |
_model_architecture('transformer_encoder_model', 'transformer_encoder_model_6l_16h_1024')
def transformer_encoder_model_6l_16h_1024(args):
args.encoder_layers = getattr(args, 'encoder_layers', 6)
args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024)
args.encoder_ffn_embed_dim = getattr(args, 'en... |
def v_packet_initialize_line_id(v_packet, opacity_state, numba_model):
inverse_line_list_nu = opacity_state.line_list_nu[::(- 1)]
doppler_factor = get_doppler_factor(v_packet.r, v_packet.mu, numba_model.time_explosion)
comov_nu = (v_packet.nu * doppler_factor)
next_line_id = (len(opacity_state.line_list... |
.parametrize(['mu', 'r', 'time_explosion'], [(1, C_SPEED_OF_LIGHT, 1)])
def test_angle_ab_LF_to_CMF_diverge(mu, r, time_explosion):
nu = 0.4
energy = 0.9
packet = r_packet.RPacket(r, mu, nu, energy)
with pytest.raises(ZeroDivisionError):
obtained = r_packet.angle_aberration_LF_to_CMF(packet, tim... |
def test_no_join_tokenizer():
if True:
sql = 'SELECT avg(age) FROM Student WHERE StuID IN ( SELECT T1.StuID FROM Has_allergy AS T1 JOIN Allergy_Type AS T2 ON T1.Allergy = T2.Allergy WHERE T2.allergytype = "food" INTERSECT SELECT T1.StuID FROM Has_allergy AS T1 JOIN Allergy_Type AS T2 ON T1.Allergy = T... |
class MikNeumann(CompositeBase):
def __init__(self, N, quad='GC', bc=(0, 0), domain=((- 1), 1), dtype=float, padding_factor=1, dealias_direct=False, coordinates=None, **kw):
if isinstance(bc, (tuple, list)):
bc = BoundaryConditions({'left': {'N': bc[0]}, 'right': {'N': bc[1]}}, domain=domain)
... |
class MobileNetV1ForImageClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def test_get_caller_tls(insecure_director):
insecure_director.tls = True
context = mock.Mock()
client_id = 'client_id'
context.auth_context = mock.Mock(return_value={'x509_common_name': [client_id.encode('utf-8')]})
result = insecure_director.get_caller(context)
assert (result == client_id) |
def _get_valid_min_max(qparams):
(scale, zero_point, quantized_type) = qparams
adjustment = (1 + torch.finfo(torch.float).eps)
_long_type_info = torch.iinfo(torch.long)
(long_min, long_max) = ((_long_type_info.min / adjustment), (_long_type_info.max / adjustment))
min_value = max(((long_min - zero_p... |
class SAGE(torch.nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels, num_layers, dropout):
super(SAGE, self).__init__()
self.convs = torch.nn.ModuleList()
self.convs.append(SAGEConv(in_channels, hidden_channels))
for _ in range((num_layers - 2)):
se... |
def test_set_params_passes_all_parameters():
class TestDecisionTree(DecisionTreeClassifier):
def set_params(self, **kwargs):
super().set_params(**kwargs)
assert (kwargs == expected_kwargs)
return self
expected_kwargs = {'max_depth': 5, 'min_samples_leaf': 2}
for e... |
def test_gammaincc_neg_x_scalar():
with pytest.raises(ValueError):
gammaincc(0.5, (- 1.0)) |
def general_cases(channel_last):
inspec_and_axis = []
batch = 16
base_ch = 192
ch_mul = [1, 1, 2, 2, 4, 4]
channels = [(base_ch * factor) for factor in ch_mul]
resolutions = [256, 128, 64, 32, 16, 8]
axis = (3 if channel_last else 1)
for (ch, res) in zip(channels, resolutions):
i... |
def random_crop(image):
image = tf.image.resize_with_crop_or_pad(image, 260, 260)
image = tf.image.random_crop(image, size=[224, 224, 3])
return image |
_module()
class TextLoggerHook(LoggerHook):
def __init__(self, by_epoch=True, interval=10, ignore_last=True, reset_flag=False, interval_exp_name=1000, out_dir=None, out_suffix=('.log.json', '.log', '.py'), keep_local=True, file_client_args=None):
super(TextLoggerHook, self).__init__(interval, ignore_last, r... |
class PhysicsInformedGNConv(nn.Module):
def __init__(self, edge_block_model, node_block_model, global_block_model, use_edge_block=True, use_node_block=True, use_global_block=False):
super(PhysicsInformedGNConv, self).__init__()
self.a = ((5 * random.random()) - 2.5)
self.b = ((5 * random.ran... |
def extract_archive(from_path: str, to_path: Optional[str]=None, remove_finished: bool=False) -> None:
if (to_path is None):
to_path = os.path.dirname(from_path)
if _is_tar(from_path):
with tarfile.open(from_path, 'r') as tar:
tar.extractall(path=to_path)
elif (_is_targz(from_pat... |
_pipeline_test
class TranslationPipelineTests(unittest.TestCase, metaclass=PipelineTestCaseMeta):
model_mapping = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
tf_model_mapping = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
def get_test_pipeline(self, model, tokenizer, feature_extractor):
if isinstance(model.... |
def plot_digraph(dot_string, format='png'):
try:
import graphviz
except ImportError as excep:
raise ImportError('graphviz needs to be available to plot_digraph') from excep
from graphviz import Source
if (format == 'html'):
return _GVPlotter(dot_string)
return Source(dot_stri... |
class GreedyContinuousThompsonSampling(SingleModelGreedyAcquisitionBuilder[HasTrajectorySampler]):
def __init__(self, select_output: Callable[([TensorType], TensorType)]=select_nth_output):
self._select_output = select_output
def __repr__(self) -> str:
return f'GreedyContinuousThompsonSampling({... |
def _tuple_to_symexpr(val):
return (symbolic.SymExpr(val[0], val[1]) if isinstance(val, tuple) else symbolic.pystr_to_symbolic(val)) |
def serialize_remote_homology_sequence(sequence: str, seq_id: str, class_label: int, fold_label: int, superfamily_label: int, family_label: int, pssm: List[List[int]], secondary_structure: List[int], solvent_accessibility: List[int], vocab: Dict[(str, int)]):
int_sequence = []
for aa in sequence:
if (aa... |
def onehot_from_logits(logits, dim=1):
return (logits == logits.max(dim, keepdim=True)[0]).float() |
class OIM(autograd.Function):
def forward(ctx, inputs, targets, lut, cq, header, momentum):
ctx.save_for_backward(inputs, targets, lut, cq, header, momentum)
outputs_labeled = inputs.mm(lut.t())
outputs_unlabeled = inputs.mm(cq.t())
return torch.cat([outputs_labeled, outputs_unlabele... |
_module()
class CGNet(nn.Module):
def __init__(self, in_channels=3, num_channels=(32, 64, 128), num_blocks=(3, 21), dilations=(2, 4), reductions=(8, 16), conv_cfg=None, norm_cfg=dict(type='BN', requires_grad=True), act_cfg=dict(type='PReLU'), norm_eval=False, with_cp=False):
super(CGNet, self).__init__()
... |
class EMT(nn.Module):
def __init__(self, dim, depth, heads, num_modality, learnable_pos_emb=False, emb_dropout=0.0, attn_dropout=0.0, ff_dropout=0.0, ff_expansion=4, max_seq_len=1024, mpu_share=False, modality_share=False, layer_share=False, attn_act_fn='tanh'):
super().__init__()
assert ((dim % hea... |
def get_sample_images(dataset, n):
n_data = len(dataset)
ans = []
if (n < n_data):
indexes = np.random.choice(n_data, n, replace=False)
else:
indexes = list(range(n_data))
for index in indexes:
(sample, _) = dataset[index]
ans.append(tensor_to_img(sample, normalize=Tr... |
def load_mnist(path, kind='train'):
import os
import gzip
import numpy as np
labels_path = os.path.join(path, ('%s-labels-idx1-ubyte.gz' % kind))
images_path = os.path.join(path, ('%s-images-idx3-ubyte.gz' % kind))
with gzip.open(labels_path, 'rb') as lbpath:
labels = np.frombuffer(lbpat... |
def prepare_dataset():
((train_images, train_labels), (test_images, test_labels)) = load_svhn()
dirpath = os.path.join(FLAGS.data_dir, ('seed' + str(FLAGS.dataset_seed)))
if (not os.path.exists(dirpath)):
os.makedirs(dirpath)
rng = np.random.RandomState(FLAGS.dataset_seed)
rand_ix = rng.perm... |
def assert_reproducible(func, num_iter=1):
model = func()
for i in range(num_iter):
model_new = func()
models_equals(model, model_new)
tf.keras.backend.clear_session() |
def remove_weight(bmodel):
bmodel.kernel_module.has = False
bmodel.net[0].parameter[0].coeff_mem.has = False
return |
def resblock_up(x_init, channels, use_bias=True, is_training=True, sn=False, scope='resblock_up'):
with tf.variable_scope(scope):
with tf.variable_scope('res1'):
x = batch_norm(x_init, is_training)
x = relu(x)
x = deconv(x, channels, kernel=3, stride=2, use_bias=use_bias,... |
def reproduce(parent_a, parent_b, mutation_rate):
(parent_a, parent_b) = (Chem.MolFromSmiles(parent_a), Chem.MolFromSmiles(parent_b))
new_child = crossover(parent_a, parent_b)
if (new_child is not None):
new_child = mutate(new_child, mutation_rate)
smis = (Chem.MolToSmiles(new_child, isomericSmi... |
class GaloisGroup_ab(_GaloisMixin, AbelianGroup_class):
def __init__(self, field, generator_orders, algorithm=None, gen_names='sigma'):
self._field = field
self._default_algorithm = algorithm
AbelianGroup_class.__init__(self, generator_orders, gen_names)
def is_galois(self):
retu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.