code stringlengths 101 5.91M |
|---|
class FlaxDistilBertPreTrainedModel(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
def pretty_eta(seconds_left):
minutes_left = (seconds_left // 60)
seconds_left %= 60
hours_left = (minutes_left // 60)
minutes_left %= 60
days_left = (hours_left // 24)
hours_left %= 24
def helper(cnt, name):
return '{} {}{}'.format(str(cnt), name, ('s' if (cnt > 1) else ''))
if ... |
def save_figure(destination, obj=None):
plt.tight_layout()
plt.savefig(destination)
plt.close() |
class FeatureExtractor(ch.nn.Module):
def __init__(self, submod, layers):
super(FeatureExtractor, self).__init__()
self.submod = submod
self.layers = layers
self.n = 0
for layer_func in layers:
layer = layer_func(self.submod)
def hook(module, _, output... |
class install_lib(orig.install_lib):
def run(self):
self.build()
outfiles = self.install()
if (outfiles is not None):
self.byte_compile(outfiles)
def get_exclusions(self):
all_packages = (pkg for ns_pkg in self._get_SVEM_NSPs() for pkg in self._all_packages(ns_pkg))
... |
class MarioDataset(Dataset):
def __init__(self, tokenizer: Optional[PreTrainedTokenizer]=None, level_string: Optional[str]=None, context_len: int=700, height: int=14, remove_start_end_tokens: bool=False, sample_all_indices: bool=False):
if (level_string is None):
print('No level string specified... |
def get_cgroup_path(private=True):
if private:
return '/'
p = None
with open('/proc/1/cpuset', 'r') as f:
p = f.read().strip()
assert p
return p |
class LabeledPatients(MutableMapping[(int, List[Label])]):
def __init__(self, patients_to_labels: Dict[(int, List[Label])], labeler_type: LabelType):
self.patients_to_labels: Dict[(int, List[Label])] = patients_to_labels
self.labeler_type: LabelType = labeler_type
def save(self, target_filename)... |
class TensorflowImporter():
def __init__(self, *args, **kwargs):
self._tf_file = args[0]
self._tf_format = kwargs.get('tf_format')
self._outputs = kwargs.get('outputs')
self._inputs = kwargs.get('inputs')
def convert_to_onnx(self, graph_def, inputs, outputs):
with tf.Grap... |
.skip
def test_lambda_nested_call():
def lamb2(A, B, C, f):
A[:] = f(B, C)
def lamb1(A: dace.float64[20], B: dace.float64[20], C: dace.float64[20]):
f = (lambda a, b: (a + b))
lamb2(A, B, C, f)
A = np.random.rand(20)
B = np.random.rand(20)
C = np.random.rand(20)
lamb1(A, ... |
class UnboundedMemory(BaseMemory):
def __init__(self, **kwargs):
super(UnboundedMemory, self).__init__(**kwargs)
def initialize_memory(self):
mem = torch.zeros(1, self.mem_size).to(self.device)
ent_counter = torch.tensor([0.0]).to(self.device)
last_mention_idx = torch.zeros(1).lo... |
def test_clean_up_not_old(nparray, tensor_key):
db = TensorDB()
db.cache_tensor({tensor_key: nparray})
db.clean_up()
cached_nparray = db.get_tensor_from_cache(tensor_key)
assert np.array_equal(nparray, cached_nparray) |
def is_integer(s):
try:
s = int(s)
return True
except Exception:
return False |
class TestLocalProjectCheckout():
def setup(self):
self.shell = Shell()
self.temp_dir = mkdtemp(prefix='mubench-checkout-local_')
self.local_url = join(self.temp_dir, 'origin')
os.makedirs(self.local_url)
open(join(self.local_url, 'some.file'), 'w').close()
self.check... |
(frozen=True)
class CritiqueTaskTemplate():
name: str
instructions: str
num_respondents: int
questions: List[CritiqueQuestionTemplate] |
class SerializationMixin(object):
def save_instance(self, filepath):
save_dict = dict(auto_fix_time_shifts=self._state_data.auto_fix_time_shifts, power_signals_d=self._state_data.power_signals_d.tolist(), rank_k=self._state_data.rank_k, matrix_l0=self._state_data.matrix_l0.tolist(), matrix_r0=self._state_da... |
('prefix')
class PrefixFactory(SingleFeatureFactory):
def feature_name(self):
return ('prefix_%s' % self.prefix_size)
def prefix_size(self):
return self.args['prefix_size']
def compute_feature(self, tokens, token_index):
return get_word_chunk(normalize_token(tokens[token_index]), sel... |
class _VisibleDeprecationTestCase(_DeprecationTestCase):
warning_cls = np.VisibleDeprecationWarning |
def getProductions(code):
stream = antlr4.InputStream(code)
lexer = JavaLexer(stream)
toks = antlr4.CommonTokenStream(lexer)
parser = JavaParserModified(toks)
tree = parser.memberDeclaration()
st = []
st.append(tree)
rule_seq = []
while (len(st) > 0):
top = st.pop()
(... |
def convert_to_color(arr_2d, palette):
arr_3d = np.zeros((arr_2d.shape[0], arr_2d.shape[1], 3), dtype=np.uint8)
for (c, i) in palette.items():
m = (arr_2d == c)
arr_3d[m] = i
return arr_3d |
def get_noise(data, dist='G', noise_std=(float(25) / 255.0), mode='S', min_noise=(float(5) / 255.0), max_noise=(float(55) / 255.0)):
if (dist == 'G'):
noise_std /= 255.0
min_noise /= 255.0
max_noise /= 255.0
noise = torch.randn_like(data)
if (mode == 'B'):
n = noi... |
class GaloisGroup_v2(GaloisGroup_perm):
def __init__(self, number_field, algorithm='pari', names=None, gc_numbering=None, _type=None):
if (not number_field.is_absolute()):
deprecation(28782, 'Use .absolute_field().galois_group() if you want the Galois group of the absolute field')
if (gc... |
def add_comm_rewrites(ctx: LeanGenContext, expr: Expression) -> List[str]:
return [((('add_comm ' + a_expr) + ' ') + b_expr) for (a_expr, b_expr) in get_reversed_add_exprs(expr=expr, simplifier=ctx.simplifier)] |
def create_wham_whamr_csv(datapath, savepath, fs, version='min', savename='whamr_', set_types=['tr', 'cv', 'tt'], add_reverb=True, task='separation', dereverberate=True):
if (fs == 8000):
sample_rate = '8k'
elif (fs == 16000):
sample_rate = '16k'
else:
raise ValueError('Unsupported s... |
class AutoTokenCounter(TokenCounter):
def __init__(self, huggingface_tokenizer: HuggingFaceTokenizer):
self.token_counters: Dict[(str, TokenCounter)] = {}
self.huggingface_tokenizer: HuggingFaceTokenizer = huggingface_tokenizer
def get_token_counter(self, organization: str) -> TokenCounter:
... |
class RandomDataset(data.Dataset):
def __init__(self, num_random=10000, shape=(3, 224, 224)):
self.size = num_random
self.shape = shape
def __len__(self):
return self.size
def __repr__(self):
return self.__class__.__name__
def __getitem__(self, index):
img = torch... |
def new_query(table: Table, ncols) -> Query:
return Query(predicates=OrderedDict.fromkeys(table.data.columns, None), ncols=ncols) |
def read_from_hdf5(fd, group, cache=None):
if (cache is None):
cache = {}
from sfepy.discrete.iga.domain import IGDomain
from sfepy.discrete.fem.meshio import HDF5MeshIO
types = {b'True': True, b'False': False, b'None': None}
def _read_from_hdf5(group):
while isinstance(group, pt.lin... |
def batch_transformer(U, thetas, out_size, name='BatchSpatialTransformer'):
with tf.variable_scope(name):
(num_batch, num_transforms) = map(int, thetas.get_shape().as_list()[:2])
indices = [([i] * num_transforms) for i in xrange(num_batch)]
input_repeated = tf.gather(U, tf.reshape(indices, [... |
def Jacobian(C):
try:
return C.jacobian()
except AttributeError:
return Jacobian_generic(C) |
def sum_task(mixture_or_task_name, dataset_split='train', add_percentiles=True):
sequence_length = {'inputs': 512, 'targets': 512}
df_packing = analyze_packing(mixture_or_task_name=mixture_or_task_name, sequence_length=sequence_length, dataset_split=dataset_split)
df_padding = analyze_padding(mixture_or_tas... |
def test_phi_plus_phi_plus():
for i in range(400):
(k1, k2, k3, k4, a3) = create_scenario(phi_plus, phi_plus, i)
state = correct_order(k1.state, k1.keys)
assert numpy.array_equal(state, phi_plus) |
def read_relation_from_id(filename='./data/WN18RR/relation2id.txt'):
relation2id = {}
with open(filename, 'r') as f:
for line in f:
if (len(line.strip().split()) > 1):
(relation, relation_id) = (line.strip().split()[0].strip(), line.strip().split()[1].strip())
... |
def __lagrange_bounds_phc(n, m, a, tmpfile=None):
S = coefficients_to_power_sums(n, m, a)
(fi, fo) = os.popen2('which phc')
find_phc = fo.readlines()
fi.close()
fo.close()
if (find_phc == []):
raise RuntimeError('PHCpack not installed.')
if (tmpfile is None):
tmpfile = sage.m... |
def _nls_subproblem(X, W, H, tol, max_iter, alpha=0.0, l1_ratio=0.0, sigma=0.01, beta=0.1):
WtX = safe_sparse_dot(W.T, X)
WtW = np.dot(W.T, W)
gamma = 1
for n_iter in range(1, (max_iter + 1)):
grad = (np.dot(WtW, H) - WtX)
if ((alpha > 0) and (l1_ratio == 1.0)):
grad += alpha... |
class PathScaleCCompiler(UnixCCompiler):
compiler_type = 'pathcc'
cc_exe = 'pathcc'
cxx_exe = 'pathCC'
def __init__(self, verbose=0, dry_run=0, force=0):
UnixCCompiler.__init__(self, verbose, dry_run, force)
cc_compiler = self.cc_exe
cxx_compiler = self.cxx_exe
self.set_e... |
def load_checkpoint(step, model, optimizer, scheduler):
global global_step
global global_epoch
checkpoint_path = os.path.join(args.save, args.model_name, 'checkpoint_step{:09d}.pth'.format(step))
print('Load checkpoint from: {}'.format(checkpoint_path))
checkpoint = torch.load(checkpoint_path)
t... |
def save_args(original_args):
reversed_trainer_log_levels = {v: k for (k, v) in trainer_log_levels.items()}
original_args['log_level'] = reversed_trainer_log_levels[original_args['log_level']]
original_args['log_level_replica'] = reversed_trainer_log_levels[original_args['log_level_replica']]
for arg in... |
def get_from_to_our_keys(model_name: str) -> Dict[(str, str)]:
our_config = RegNetConfig(depths=[2, 7, 17, 1], hidden_sizes=[8, 8, 8, 8], groups_width=8)
if ('in1k' in model_name):
our_model = RegNetForImageClassification(our_config)
else:
our_model = RegNetModel(our_config)
from_model =... |
class TransductiveFinetuning(Finetune):
def __init__(self, *args, fine_tuning_steps: int=25, fine_tuning_lr: float=5e-05, temperature: float=1.0, **kwargs):
super().__init__(*args, fine_tuning_steps=fine_tuning_steps, fine_tuning_lr=fine_tuning_lr, temperature=temperature, **kwargs)
def forward(self, qu... |
def test_argcombinations():
array = ak.Array([[0.0, 1.1, 2.2, 3.3], [], [4.4, 5.5, 6.6], [7.7], [8.8, 9.9, 10.0, 11.1, 12.2]])
assert (to_list(ak.operations.argcombinations(array, 2, replacement=False)) == [[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)], [], [(0, 1), (0, 2), (1, 2)], [], [(0, 1), (0, 2), (0, ... |
class AI21TokenCostEstimator(TokenCostEstimator):
def estimate_tokens(self, request: Request, metric_service: MetricService) -> int:
return (request.num_completions * request.max_tokens) |
class CosineClassifier(_Classifier):
def __init__(self, feat_dim=None, num_classes=None, dtype=None, scale=30, **kwargs):
super().__init__(feat_dim, num_classes, dtype)
self.scale = scale
def forward(self, x):
x = F.normalize(x, dim=(- 1))
weight = F.normalize(self.weight, dim=(-... |
class BQCorpusBertPipe(MatchingBertPipe):
def __init__(self, tokenizer='cn-char'):
super().__init__(tokenizer=tokenizer)
def process_from_file(self, paths=None):
data_bundle = BQCorpusLoader().load(paths)
data_bundle = RenamePipe(task='cn-nli-bert').process(data_bundle)
data_bund... |
class Action(Enum):
opened = 'opened'
reopened = 'reopened'
closed = 'closed'
labeled = 'labeled'
unlabeled = 'unlabeled'
ready_for_review = 'ready_for_review'
synchronize = 'synchronize'
review_requested = 'review_requested'
converted_to_draft = 'converted_to_draft'
submitted = ... |
def train(args, trainer, task, epoch_itr):
update_freq = (args.update_freq[(epoch_itr.epoch - 1)] if (epoch_itr.epoch <= len(args.update_freq)) else args.update_freq[(- 1)])
itr = epoch_itr.next_epoch_itr(fix_batches_to_gpus=args.fix_batches_to_gpus, shuffle=(epoch_itr.epoch >= args.curriculum))
itr = itera... |
def register_Ns3DsrDsrMaintainBuffEntry_methods(root_module, cls):
cls.add_constructor([param('ns3::dsr::DsrMaintainBuffEntry const &', 'arg0')])
cls.add_constructor([param('ns3::Ptr< ns3::Packet const >', 'pa', default_value='0'), param('ns3::Ipv4Address', 'us', default_value='ns3::Ipv4Address()'), param('ns3:... |
def keypoint_rcnn(model):
logger.warn('Deprecated: use `MODEL.TYPE: generalized_rcnn` with `MODEL.KEYPOINTS_ON: True`')
return generalized_rcnn(model) |
class Attention(nn.Module):
def __init__(self, input_dim, hidden_dim, attn_channel, kernel_size):
super(Attention, self).__init__()
self.kernel_size = kernel_size
self.padding = (kernel_size // 2)
self.H = nn.Conv2d(in_channels=hidden_dim, out_channels=attn_channel, kernel_size=kerne... |
def main():
data = load_pickle(args.data_path)
query_cam = data['query_cam']
query_label = data['query_label']
gallery_cam = data['gallery_cam']
gallery_label = data['gallery_label']
gallery_feature = torch.FloatTensor(data['gallery_f'])
query_feature = torch.FloatTensor(data['query_f'])
... |
((not workspace.C.has_mkldnn), 'Skipping as we do not have mkldnn.')
class MKLReluTest(hu.HypothesisTestCase):
(size=st.integers(8, 20), input_channels=st.integers(1, 3), batch_size=st.integers(1, 3), inplace=st.booleans(), **mu.gcs)
def test_mkl_relu(self, size, input_channels, batch_size, inplace, gc, dc):
... |
def dag2pag(dag, islatent):
udg = nx.Graph()
nodes = dag.get_nodes()
nodes_ids = {node: i for (i, node) in enumerate(nodes)}
n = len(nodes)
for (x, y) in combinations(range(n), 2):
if dag.get_edge(nodes[x], nodes[y]):
udg.add_edge(x, y)
observed_nodes = list((set(nodes) - set... |
def list_s3_objects(bucket, name):
s3_client = boto3.client('s3', aws_access_key_id=access_key, aws_secret_access_key=secret_key)
res = s3_client.list_objects(Bucket=bucket, Prefix=name, MaxKeys=1)
return res |
def make_beta_schedule(schedule, n_timestep, linear_start=0.0001, linear_end=0.02, cosine_s=0.008):
if (schedule == 'linear'):
betas = (torch.linspace((linear_start ** 0.5), (linear_end ** 0.5), n_timestep, dtype=torch.float64) ** 2)
elif (schedule == 'cosine'):
timesteps = ((torch.arange((n_tim... |
def __getattr__(name):
if (name == 'load_boston'):
msg = textwrap.dedent('\n `load_boston` has been removed from scikit-learn since version 1.2.\n\n The Boston housing prices dataset has an ethical problem: as\n investigated in [1], the authors of this dataset engineered a\n... |
class model():
def __init__(self, curr_param):
self.sess = tf.Session()
self.training_step = 0
self.par = curr_param
def load_data(self, mode):
if (mode == 'train'):
file_name = self.par.train_file
self.training_data = []
else:
file_nam... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--train_corpus', default=None, type=str, required=True, help='The input train corpus, each line contains numbers that are the roberta tokenized indices.')
parser.add_argument('--train_eval_corpus', default=None, type=str, required=False, he... |
def weights_init_kaiming(m):
classname = m.__class__.__name__
if (classname.find('Linear') != (- 1)):
nn.init.normal_(m.weight, 0, 0.01)
if (m.bias is not None):
nn.init.constant_(m.bias, 0.0)
elif (classname.find('Conv') != (- 1)):
nn.init.kaiming_normal_(m.weight, mode=... |
class Mlp3Layer256UnitLongerTrainingDecreaseBatchSize(NeuralNetworkTrainingDecreaseBatchSize, Mlp3Layer256Unit):
pass |
class TestGradients(TestCase):
exact_dtype = True
def _get_safe_inplace(self, inplace_variant):
(inplace_variant)
def _fn(t, *args, **kwargs):
return inplace_variant(t.clone(), *args, **kwargs)
return _fn
def _check_helper(self, device, dtype, op, variant, check):
... |
def quantize_linear_modules(module, dtype=torch.int8):
warnings.warn('quantize_linear_modules function has been deprecated. Please use torch.quantization.quantize_dynamic API instead.')
reassign = {}
for (name, mod) in module.named_modules():
if (mod is module):
continue
new_mod ... |
def env_desc_gen(**config):
env = MDPEnvironment(**config)
env_desc = {'creator': MDPEnvironment, 'possible_agents': env.possible_agents, 'action_spaces': env.action_spaces, 'observation_spaces': env.observation_spaces, 'config': config}
env.close()
return env_desc |
class SingleTaskSVGP(BaseGPSurrogate, SingleTaskVariationalGP):
def __init__(self, feature_dim, out_dim, num_inducing_points, encoder, noise_constraint=None, lengthscale_prior=None, outcome_transform=None, input_transform=None, learn_inducing_points=True, mll_beta=1.0, *args, **kwargs):
BaseGPSurrogate.__in... |
def clip_grad_by_value_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes):
dy = grad_inputs[0]
x0 = inputs[0]
assert False, 'This function is not called since the function is the composite of other functions.' |
class StepOff(BaseVRMWaveform):
def __init__(self, t0=0.0):
self.t0 = t0
def t0(self):
return self._t0
.setter
def t0(self, value):
self._t0 = validate_float('t0', value)
def getCharDecay(self, fieldType, times):
fieldType = validate_string('fieldType', fieldType, ['d... |
_grad()
def concat_all_gather(tensor):
tensors_gather = [torch.ones_like(tensor) for _ in range(torch.distributed.get_world_size())]
torch.distributed.all_gather(tensors_gather, tensor, async_op=False)
output = torch.cat(tensors_gather, dim=0)
return output |
def register(target: Target) -> Target:
from . import cli
global ALL_TARGETS
ALL_TARGETS += (target,)
cli.TARGETS_TYPE.choices += (target.__name__,)
return target |
def _frobenius_shift(K, generators, check_only=False):
if (len(generators) == 1):
return generators
p = K.characteristic()
n = K.degree()
compatible = {}
from .integer_mod import mod
for m in n.divisors():
compatible[m] = {}
for (q, x) in generators.items():
for m in ... |
def changeContagion(G, A, i):
delta = 0
for u in G.neighbourIterator(i):
if (A[u] == 1):
delta += 1
return delta |
def download_a_url(dl_folder, url):
(url, filename) = get_downloaded_file(dl_folder, url)
if os.path.exists(filename):
print(f'{filename} has already been downloaded so skip')
return filename
print(f'downloading {url} to {filename}')
if (isinstance(url, list) or isinstance(url, tuple)):
... |
def test_queryrequest4():
url = (brokerIp + '/ngsi10/queryContext')
headers = {'Content-Type': 'appliction/json'}
r = requests.post(url, data=json.dumps(data_ngsi10.subdata45), headers=headers)
assert (r.status_code == 200) |
class AggregatorGRPCClient():
def __init__(self, agg_addr, agg_port, tls, disable_client_auth, root_certificate, certificate, private_key, aggregator_uuid=None, federation_uuid=None, single_col_cert_common_name=None, **kwargs):
self.uri = f'{agg_addr}:{agg_port}'
self.tls = tls
self.disable_... |
_warnings(category=sklearn.exceptions.ConvergenceWarning)
.filterwarnings('ignore:The SAMME.R algorithm')
.parametrize('name, Estimator', all_estimators())
def test_fit_docstring_attributes(name, Estimator):
pytest.importorskip('numpydoc')
from numpydoc import docscrape
doc = docscrape.ClassDoc(Estimator)
... |
class Decoder(nn.Module):
def __init__(self, x_dim, z_dim):
super(Decoder, self).__init__()
self.model = nn.Sequential(nn.Linear(z_dim, 512), nn.ReLU(), nn.Linear(512, x_dim))
def forward(self, z):
img = self.model(z)
return img |
class ImageGPTConfig(PretrainedConfig):
model_type = 'imagegpt'
keys_to_ignore_at_inference = ['past_key_values']
attribute_map = {'hidden_size': 'n_embd', 'max_position_embeddings': 'n_positions', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer'}
def __init__(self, vocab_size=(512 + 1), ... |
class _fasterRCNN(nn.Module):
def __init__(self, classes, class_agnostic):
super(_fasterRCNN, self).__init__()
self.classes = classes
self.n_classes = len(classes)
self.class_agnostic = class_agnostic
self.RCNN_loss_cls = 0
self.RCNN_loss_bbox = 0
self.RCNN_rp... |
class SawyerDoorEnvV2(SawyerXYZEnv):
def __init__(self):
hand_low = ((- 0.5), 0.4, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = (0.0, 0.85, 0.15)
obj_high = (0.1, 0.95, 0.15)
goal_low = ((- 0.3), 0.4, 0.1499)
goal_high = ((- 0.2), 0.5, 0.1501)
super().__init__(se... |
def hide_rename_eval_setting(eval_setting_name):
setting = m_repo.get_evaluation_setting(name=eval_setting_name, load_evaluations=True)
for e in m_repo.get_evaluations([x.uuid for x in setting.evaluations]):
m_repo.hide_evaluation(e.uuid)
new_name = (eval_setting_name + f'_hidden_{random.randint(0, ... |
def find_all(a_str, sub):
start = 0
while True:
start = a_str.find(sub, start)
if (start == (- 1)):
return
(yield start)
start += len(sub) |
def build_voxel_generator(voxel_config):
voxel_generator = VoxelGenerator(voxel_size=voxel_config.VOXEL_SIZE, point_cloud_range=voxel_config.RANGE, max_num_points=voxel_config.MAX_POINTS_NUM_PER_VOXEL, max_voxels=20000)
return voxel_generator |
class TestFromCTypes(object):
def check(ctype, dtype):
dtype = np.dtype(dtype)
assert_equal(np.dtype(ctype), dtype)
assert_equal(np.dtype(ctype()), dtype)
def test_array(self):
c8 = ctypes.c_uint8
self.check((3 * c8), (np.uint8, (3,)))
self.check((1 * c8), (np.uin... |
def _named_idx(idx):
if ((idx < 0) or (idx > 2)):
raise ValueError(('idx must be between 0 and 2, got %d' % idx))
return ('x', 'y', 'z')[idx] |
def build_transform(is_train, args):
resize_im = (args.input_size > 32)
if is_train:
transform = create_transform(input_size=args.input_size, is_training=True, color_jitter=args.color_jitter, auto_augment=args.aa, interpolation=args.train_interpolation, re_prob=args.reprob, re_mode=args.remode, re_count... |
class LinformerEncoder(RobertaEncoder):
def __init__(self, args, dictionary):
super().__init__(args, dictionary)
self.register_buffer('version', torch.tensor(2))
def build_encoder(self, args, dictionary, embed_tokens):
encoder = LinformerTransformerEncoder(args, dictionary, embed_tokens)... |
def write_predictions_extended(all_examples, all_features, all_results, n_best_size, max_answer_length, output_prediction_file, output_nbest_file, output_null_log_odds_file, orig_data_file, start_n_top, end_n_top, version_2_with_negative, tokenizer, verbose_logging):
_PrelimPrediction = collections.namedtuple('Prel... |
def get_statistics(args, datasource):
scaler = sklearn.preprocessing.StandardScaler()
pbar = tqdm.tqdm(range(len(datasource.mus.tracks)))
for ind in pbar:
x = datasource.mus.tracks[ind].audio.T
audio = nn.NdArray.from_numpy_array(x[(None, ...)])
target_spec = get_spectogram(*get_stft... |
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 dataset(test_dataset):
if (test_dataset == ''):
return None
elif (test_dataset not in soundata.DATASETS):
raise ValueError('{} is not a dataset in soundata'.format(test_dataset))
data_home = os.path.join('tests/resources/sound_datasets_full', test_dataset)
return soundata.initiali... |
class BandGapsConf(Struct):
def __init__(self, filename, approx, region_selects, mat_pars, options, evp_options, eigenmomenta_options, band_gaps_options, coefs_save_name='coefs', corrs_save_names=None, incwd=None, output_dir=None, **kwargs):
Struct.__init__(self, approx=approx, region_selects=region_selects... |
class GAN(object):
def __init__(self, z_dim, crop_image_size, resized_image_size, batch_size, data_dir):
celebA_dataset = celebA.read_dataset(data_dir)
self.z_dim = z_dim
self.crop_image_size = crop_image_size
self.resized_image_size = resized_image_size
self.batch_size = bat... |
def RatVal(a, b, ctx=None):
if z3_debug():
_z3_assert((_is_int(a) or isinstance(a, str)), 'First argument cannot be converted into an integer')
_z3_assert((_is_int(b) or isinstance(b, str)), 'Second argument cannot be converted into an integer')
return simplify((RealVal(a, ctx) / RealVal(b, ctx)... |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=(1, 1), residual=True):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride, padding=dilation[0], dilation=dilation[0])
self.bn1 = BatchNorm(pl... |
def fused_bn(x, mean, var, gain=None, bias=None, eps=1e-05):
scale = torch.rsqrt((var + eps))
if (gain is not None):
scale = (scale * gain)
shift = (mean * scale)
if (bias is not None):
shift = (shift - bias)
return ((x * scale) - shift) |
class _DecreasingVarianceModel(QuadraticMeanAndRBFKernel, TrainableProbabilisticModel):
def __init__(self, data: Dataset):
super().__init__()
self._data = data
_check_shapes
def predict(self, query_points: TensorType) -> tuple[(TensorType, TensorType)]:
(mean, var) = super().predict(... |
class UniqueSinglingOutQueries():
def __init__(self):
self._set: Set[str] = set()
self._list: List[str] = []
def check_and_append(self, query: str, df: pd.DataFrame):
sorted_query = ''.join(sorted(query))
if (sorted_query not in self._set):
counts = safe_query_counts(... |
def import_fsspec(name: str) -> ModuleType:
try:
import fsspec
except ModuleNotFoundError as err:
raise ImportError(f'''to use {name}, you must install fsspec:
pip install fsspec
or
conda install -c conda-forge fsspec
''') from err
import_pyarrow_parquet(name)
return fsspec |
def transform_params(params, params_tf, num_classes):
params['root_block']['conv_root']['kernel'] = params_tf['resnet/root_block/standardized_conv2d/kernel']
for block in ['block1', 'block2', 'block3', 'block4']:
units = set([re.findall('unit\\d+', p)[0] for p in params_tf.keys() if (p.find(block) >= 0)... |
class ArgMaxParameter(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _ARGMAXPARAMETER |
def _fake_quantize_per_tensor_affine_grad_reference(dY, X, scale, zero_point, quant_min, quant_max):
Xq = torch.round(((X * (1.0 / scale)) + zero_point))
mask = ((Xq >= quant_min) * (Xq <= quant_max))
res = torch.zeros_like(dY)
res[mask] = dY[mask]
return res |
def make_square(img_size=(64, 64), num_points_per_cluster=8, cluster_radius=1):
is_square = False
while (not is_square):
point_1_x = random.randint((0 + cluster_radius), (img_size[0] - cluster_radius))
point_1_y = random.randint((0 + cluster_radius), (img_size[1] - cluster_radius))
point... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.