code stringlengths 101 5.91M |
|---|
class CacheStats():
def __init__(self):
self.num_queries: Dict[(str, int)] = defaultdict(int)
self.num_computes: Dict[(str, int)] = defaultdict(int)
self.lock = threading.Lock()
def reset(self):
with self.lock:
self.num_queries.clear()
self.num_computes.cl... |
def should_build_for_install_command(req, check_binary_allowed):
return _should_build(req, need_wheel=False, check_binary_allowed=check_binary_allowed) |
class GCSObject(ObjectStoreObject):
def full_path(self):
return os.path.join(f'gs://{self.bucket}', self.key) |
_module()
class FusedSemanticHead(nn.Module):
def __init__(self, num_ins, fusion_level, num_convs=4, in_channels=256, conv_out_channels=256, num_classes=183, ignore_label=255, loss_weight=0.2, conv_cfg=None, norm_cfg=None):
super(FusedSemanticHead, self).__init__()
self.num_ins = num_ins
sel... |
def may_build_model_ema(cfg, model):
if (not cfg.MODEL_EMA.ENABLED):
return
model = _remove_ddp(model)
assert (not hasattr(model, 'ema_state')), 'Name `ema_state` is reserved for model ema.'
model.ema_state = EMAState()
logger.info('Using Model EMA.') |
def bin_op_out_template(backend: Type[Backend], a: Union[(Tensor[T], int, float, numpy.number)], b: Union[(Tensor[T], int, float, numpy.number)], *, name: str, copy_sparse_dim: bool=True, allow_broadcast_all_sources: Optional[bool]=None, dim_order: Optional[Sequence[Dim]]=None, allow_scalar: bool=True) -> Tuple[(Tensor... |
class AnomalibDataset(Dataset, ABC):
def __init__(self, task: TaskType, transform: A.Compose) -> None:
super().__init__()
self.task = task
self.transform = transform
self._samples: DataFrame
def __len__(self) -> int:
return len(self.samples)
def subsample(self, indice... |
class HardSigmoidChannel(PiecewiseLinearChannel):
def __init__(self):
L = 2.5
neg = dict(zmin=(- np.inf), zmax=(- L), slope=0, x0=0)
mid = dict(zmin=(- L), zmax=(+ L), slope=(1 / (2 * L)), x0=0.5)
pos = dict(zmin=L, zmax=np.inf, slope=0, x0=1)
super().__init__(name='h-sigm', ... |
def is_args_coref(arg_i, arg_j, topic):
global non_coref_args_count, checked_args_count
cluster_i = topic.entity_mention_id_to_gold[arg_i]
cluster_j = topic.entity_mention_id_to_gold[arg_j]
checked_args_count += 1
if (cluster_i == cluster_j):
return True
else:
non_coref_args_coun... |
def adjust_learning_rate(optimizer, learning_rate, i_iter, max_iter, power):
lr = lr_poly(learning_rate, i_iter, max_iter, power)
optimizer.param_groups[0]['lr'] = lr
return lr |
_task('cross_lingual_lm')
class CrossLingualLMTask(FairseqTask):
def add_args(parser):
parser.add_argument('data', help='colon separated path to data directories list, will be iterated upon during epochs in round-robin manner')
parser.add_argument('--tokens-per-sample', d... |
def show_performance(distortion_name):
errs = []
for severity in range(1, 6):
distorted_dataset = dset.ImageFolder(root=((('imagenet2012_corrupted/' + distortion_name) + '/') + str(severity)), transform=trn.Compose([trn.CenterCrop(224), trn.ToTensor(), trn.Normalize(mean, std)]))
distorted_datas... |
class FasterBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super(FasterBlock, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.stride = stride
self._conv1 = nn.Conv2d(self.in_channels, self.out_channels, kernel_... |
def get_placeholder(name, dtype, shape):
if (name in _PLACEHOLDER_CACHE):
(out, dtype1, shape1) = _PLACEHOLDER_CACHE[name]
assert ((dtype1 == dtype) and (shape1 == shape))
return out
else:
out = tf.placeholder(dtype=dtype, shape=shape, name=name)
_PLACEHOLDER_CACHE[name] ... |
_utils.test(arch=ti.cuda)
def test_gpu_sparse_solver():
from scipy.sparse import coo_matrix
def init_b(b: ti.types.ndarray(), nrows: ti.i32):
for i in range(nrows):
b[i] = (1.0 + (i / nrows))
n = 10
A = np.random.rand(n, n)
A_psd = (np.dot(A, A.transpose()) + np.eye(n)).astype(np... |
class TransformerEncoder(nn.Module):
def __init__(self, args):
super().__init__()
self.dropout = args.dropout
self.embedding_dim = args.encoder_embed_dim
self.pos_conv = nn.Conv1d(self.embedding_dim, self.embedding_dim, kernel_size=args.conv_pos, padding=(args.conv_pos // 2), groups=... |
def get_relations_by_type(data_dir, relation_index_path):
with open(os.path.join(data_dir, 'raw.kb')) as f:
triples = list(f.readlines())
with open(os.path.join(data_dir, 'train.triples')) as f:
triples += list(f.readlines())
triples = list(set(triples))
query_answers = dict()
theta_... |
class RepVGGConvModule(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, activation='ReLU', padding_mode='zeros', deploy=False):
super(RepVGGConvModule, self).__init__()
assert ((activation is None) or isinstance(activation, str))
... |
def head_tail(sequence: S[T]) -> tuple[((T | type(NO_HEAD)), S[T])]:
if (len(sequence) == 0):
return (NO_HEAD, ())
else:
return (sequence[0], sequence[1:]) |
def evaluate_data(data: (T | Callable[([], T)])) -> T:
return (data() if callable(data) else data) |
def test_meanshift_all_orphans():
ms = MeanShift(bandwidth=0.1, seeds=[[(- 9), (- 9)], [(- 10), (- 10)]])
msg = 'No point was within bandwidth=0.1'
with pytest.raises(ValueError, match=msg):
ms.fit(X) |
def create_vocabulary_lookup_table(filename, default_value=None):
if (not gfile.Exists(filename)):
raise ValueError('File does not exist: {}'.format(filename))
with gfile.GFile(filename) as file:
vocab = list((line.strip('\n') for line in file))
vocab_size = len(vocab)
has_counts = (len(... |
class TestTensorBoardPytorchGraph(BaseTestCase):
def test_pytorch_graph(self):
dummy_input = (torch.zeros(1, 3),)
class myLinear(torch.nn.Module):
def __init__(self):
super(myLinear, self).__init__()
self.l = torch.nn.Linear(3, 5)
def forward(s... |
class Representation_abstract(CombinatorialFreeModule):
def __init__(self, semigroup, base_ring, *args, **opts):
self._semigroup = semigroup
self._semigroup_algebra = semigroup.algebra(base_ring)
CombinatorialFreeModule.__init__(self, base_ring, *args, **opts)
def semigroup(self):
... |
def save_checkpoint(state, is_best, filedir, filepre, filename='_checkpoint.pth.tar'):
torch.save(state, os.path.join(filedir, (filepre + filename)))
if is_best:
shutil.copyfile(os.path.join(filedir, (filepre + filename)), os.path.join(filedir, 'model_best.pth.tar')) |
class SageDocTestRunner(doctest.DocTestRunner):
def __init__(self, *args, **kwds):
O = kwds.pop('outtmpfile', None)
self.msgfile = kwds.pop('msgfile', None)
self.options = kwds.pop('sage_options')
doctest.DocTestRunner.__init__(self, *args, **kwds)
self._fakeout = SageSpoofIn... |
class DcxImageFile(PcxImageFile):
format = 'DCX'
format_description = 'Intel DCX'
_close_exclusive_fp_after_loading = False
def _open(self):
s = self.fp.read(4)
if (i32(s) != MAGIC):
raise SyntaxError('not a DCX file')
self._offset = []
for i in range(1024):
... |
class MoE(torch.nn.Module):
def __init__(self, args: Arguments):
super(MoE, self).__init__()
self.router = router.LearnedRouter(args)
self.experts = ParallelMLP(args)
def forward(self, x):
x = common.cast_if_autocast_enabled(x)
(scores, expert_weights, top_experts) = self... |
def add_graff_ms_train_args(parser):
parser.add_argument('--debug', default=False, action='store_true')
parser.add_argument('--debug-overfit', default=False, action='store_true')
parser.add_argument('--gpu', default=False, action='store_true')
parser.add_argument('--seed', default=42, action='store', ty... |
def _average_with_log_weights(x, logweights):
x = np.asarray(x)
logweights = np.asarray(logweights)
maxlogw = logweights.max()
weights = np.exp((logweights - maxlogw))
return np.average(x, weights=weights) |
class LJspeechDataset(Dataset):
def __init__(self, data_root, train=True, test_size=0.05):
self.data_root = data_root
self.lengths = []
self.train = train
self.test_size = test_size
self.paths = [self.collect_files(0), self.collect_files(1)]
def __len__(self):
ret... |
class DistributedTimeoutWrapper(nn.Module):
def __init__(self, module: nn.Module, timeout: int, signal=signal.SIGINT):
super().__init__()
self.module = module
self.timeout = timeout
self.signal = signal
if (timeout > 0):
self._heartbeat = threading.Event()
... |
def init(output_file, flags=None, output_mode='key_value'):
flags = (DEFAULT_FLAGS if (flags is None) else flags)
output_mode = cudaOutputMode.for_key(output_mode)
with tempfile.NamedTemporaryFile(delete=True) as f:
f.write(b'\n'.join(map((lambda f: f.encode('ascii')), flags)))
f.flush()
... |
class Trainer(object):
def __init__(self, cfg: FairseqConfig, task, model, criterion, quantizer=None):
if isinstance(cfg, Namespace):
logger.warning('argparse.Namespace configuration is deprecated! Automatically converting to OmegaConf')
cfg = convert_namespace_to_omegaconf(cfg)
... |
def test(args):
time_taken = []
img_save_id = 0
(losses, psnrs, ssims) = myutils.init_meters(args.loss)
model.eval()
psnr_list = []
with torch.no_grad():
for (i, (images, name)) in enumerate(test_loader):
if (name[0] not in folderList):
continue
im... |
def insert_node_between_two_nodes(graph: Graph, node_to_insert: BaseNode, first_node: BaseNode, last_node: BaseNode):
graph.add_node(node_to_insert)
e_attr = graph.get_edge_data(first_node, last_node)
assert (len(list(e_attr.values())) == 1)
e_attr = list(e_attr.values())[0]
graph.add_edge(first_nod... |
class TfEnv(GarageEnv):
def __init__(self, env=None, env_name=''):
super().__init__(env, env_name)
self.action_space = akro.from_gym(self.env.action_space)
self.observation_space = akro.from_gym(self.env.observation_space)
_property
def max_episode_steps(self):
return self.en... |
def read_tsv(path, corpus_root, language, accent=None, hours=(- 1)):
with open(path, 'r') as fp:
rows = csv.reader(fp, delimiter='\t')
data_list = []
total_len = 0
iterator = tqdm(enumerate(rows))
for (i, row) in iterator:
if (i == 0):
continue
... |
def _load_local(hubconf_dir, model, *args, **kwargs):
sys.path.insert(0, hubconf_dir)
hubconf_path = os.path.join(hubconf_dir, MODULE_HUBCONF)
hub_module = import_module(MODULE_HUBCONF, hubconf_path)
entry = _load_entry_from_hubconf(hub_module, model)
model = entry(*args, **kwargs)
sys.path.remo... |
class MPNetTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
model_input_names = ['input_ids', 'att... |
class TUCh(object):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TUCh_Val_get, _snap.TUCh_Val_set)
def __init__(self, *args):
_snap.TUCh_swiginit(self, _snap.new_TUCh(*args))
def S... |
class IndexScore():
def __init__(self, index, score):
self.index = index
self.score = score
def __lt__(self, other):
return (self.score < other.score)
def __repr__(self):
return ('(%d, %.3f)' % (self.index, self.score))
def __str__(self):
return ('(index: %d, scor... |
class ToImageCA(ToImage):
def __init__(self, game, name, cfg: Config):
super().__init__(game, name, cfg)
def step(self, action, **kwargs):
action = action.reshape((self.dim, self.w, self.h))
(obs, reward, done, truncated, info) = self.env.step(action, **kwargs)
obs = self.transfo... |
class MarkdownTableLinearize(TableLinearize):
def process_table(self, table_content: Dict):
assert (('header' in table_content) and ('rows' in table_content)), self.PROMPT_MESSAGE
_table_str = (self.process_header(table_content['header']) + ' ')
for (i, row_example) in enumerate(table_conten... |
def format_timestamp(seconds: float, always_include_hours: bool=False, decimal_marker: str='.'):
if (seconds is not None):
milliseconds = round((seconds * 1000.0))
hours = (milliseconds // 3600000)
milliseconds -= (hours * 3600000)
minutes = (milliseconds // 60000)
millisecon... |
def _preprocess_reader_samples_chunk(samples: List, out_file_prefix: str, gold_passages_file: str, tensorizer: Tensorizer, is_train_set: bool) -> str:
(chunk_id, samples) = samples
logger.info('Start batch %d', len(samples))
iterator = preprocess_retriever_data(samples, gold_passages_file, tensorizer, is_tr... |
class ImageNet12(object):
def __init__(self, trainFolder, testFolder, num_workers=8, pin_memory=True, size_images=224, scaled_size=256, type_of_data_augmentation='rand_scale', data_config=None):
self.data_config = data_config
self.trainFolder = trainFolder
self.testFolder = testFolder
... |
def main(args):
cfg = setup(args)
PathManager.set_strict_kwargs_checking(False)
if args.eval_only:
model = Trainer.build_model(cfg)
DensePoseCheckpointer(model, save_dir=cfg.OUTPUT_DIR).resume_or_load(cfg.MODEL.WEIGHTS, resume=args.resume)
res = Trainer.test(cfg, model)
if cf... |
def yaml_dump(data, Dumper=None, allow_unicode: bool=True, **kwargs):
if (Dumper is None):
Dumper = OrderedDumper
return yaml.dump(data, Dumper=Dumper, allow_unicode=allow_unicode, **kwargs) |
def _macosx_vers(_cache=[]):
if (not _cache):
version = platform.mac_ver()[0]
if (version == ''):
plist = '/System/Library/CoreServices/SystemVersion.plist'
if os.path.exists(plist):
if hasattr(plistlib, 'readPlist'):
plist_content = plistl... |
class GeneratedPaths():
output_dir: Path
lcm_type_dir: Path
function_dir: Path
python_types_dir: Path
cpp_types_dir: Path
generated_files: T.List[Path] |
def validate_ar_dni(df: Union[(str, pd.Series, dd.Series, pd.DataFrame, dd.DataFrame)], column: str='') -> Union[(bool, pd.Series, pd.DataFrame)]:
if isinstance(df, (pd.Series, dd.Series)):
return df.apply(dni.is_valid)
elif isinstance(df, (pd.DataFrame, dd.DataFrame)):
if (column != ''):
... |
def latex_env(env, text, titleline, counter, format):
(label, titleline) = get_label(titleline)
titleline = titleline.strip()
template = '\n\\begin{${env}}\n% if label:\nlabel{${label}}\n% endif\n% if titleline:\n\\noindent\\emph{${titleline}}.\n%endif\n${text}\n\\end{${env}}\n'
return Template(template... |
class NumericalVarField(NumericalDataFrameField):
def __init__(self, *args, **kwargs):
super().__init__(*args, field_type='var', **kwargs) |
def sftw(A: dace.float64[20]):
B = dace.define_local([20], dace.float64)
C = dace.define_local([20], dace.float64)
D = dace.define_local([20], dace.float64)
E = dace.define_local([20], dace.float64)
dup = dace.define_local([20], dace.float64)
for i in dace.map[0:20]:
with dace.tasklet:
... |
.parametrize(['current_shell_id', 'delta_shell', 'no_of_shells'], [(132, (- 1), 199), (132, 0, 132), (132, 20, 154)])
def test_move_packet_across_shell_boundary_increment(packet, current_shell_id, delta_shell, no_of_shells):
packet.current_shell_id = current_shell_id
r_packet_transport.move_packet_across_shell_... |
def optimizer_kwargs(parsed_args):
return {'optim': parsed_args.optim, 'lr': parsed_args.lr, 'weight_decay': parsed_args.weight_decay, 'momentum': parsed_args.momentum, 'sgd_dampening': parsed_args.sgd_dampening, 'sgd_nesterov': parsed_args.sgd_nesterov, 'rmsprop_alpha': parsed_args.rmsprop_alpha, 'adam_beta1': par... |
def python_app_auth(python_app_type):
if (python_app_type == 'wsgi'):
return '\nimport werkzeug\n\()\nclass Auth:\n\n def get(self, case, context):\n client = werkzeug.Client(context.app)\n response = client.post("/auth/token/", json={"username": "test", "password": "pass"})\n return... |
class TestSctypeDict(object):
def test_longdouble(self):
assert_((np.sctypeDict['f8'] is not np.longdouble))
assert_((np.sctypeDict['c16'] is not np.clongdouble)) |
_module()
class DMHead(BaseDecodeHead):
def __init__(self, filter_sizes=(1, 3, 5, 7), fusion=False, **kwargs):
super(DMHead, self).__init__(**kwargs)
assert isinstance(filter_sizes, (list, tuple))
self.filter_sizes = filter_sizes
self.fusion = fusion
dcm_modules = []
... |
def sja_to_aa(sja: Union[(torch.Tensor, numpy.ndarray)], R_t: Union[(torch.Tensor, numpy.ndarray)]=TRANSFORMATION_AA_TO_SJA, R_t_inv: Union[(torch.Tensor, numpy.ndarray)]=TRANSFORMATION_SJA_TO_AA) -> Union[(torch.Tensor, numpy.ndarray)]:
def _sja_to_aa(sja, R_t, R_t_inv):
R_sja = euler_angles_to_matrix(sja,... |
(name='save')
('-n', '--name', required=False, help='Name of the Federated learning plan', default='default', type=str)
def save_(name):
from os import makedirs
from shutil import copyfile
echo(f'Saving plan to {name}')
makedirs(f'plan/plans/{name}', exist_ok=True)
copyfile('plan/plan.yaml', f'plan/... |
def gen_line_dict_file(out_path, imgid2imgname, imgid2anno):
lines = []
for (key, value) in imgid2imgname.items():
if (key in imgid2anno):
anno = imgid2anno[key]
line_dict = {}
line_dict['file_name'] = value['file_name']
line_dict['height'] = value['height... |
class Conv1D(nn.Module):
def __init__(self, nf, nx):
super().__init__()
self.nf = nf
self.weight = nn.Parameter(torch.empty(nx, nf))
self.bias = nn.Parameter(torch.zeros(nf))
nn.init.normal_(self.weight, std=0.02)
def forward(self, x):
size_out = (x.size()[:(- 1)]... |
class MockOpen(object):
def __init__(self, test_dir):
self.files = {}
self.old_open = open
self.test_dir = test_dir
def __call__(self, filename, mode, *args, **kwargs):
if filename.startswith(self.test_dir):
if ((filename not in self.files) or (mode in ('w', 'w+'))):
... |
def _impl(array, n, replacement, axis, fields, parameters, with_name, highlevel, behavior, attrs):
axis = regularize_axis(axis)
if (with_name is None):
pass
elif (parameters is None):
parameters = {'__record__': with_name}
else:
parameters = {**parameters, '__record__': with_name... |
def register_Ns3LteAnrSapUser_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::LteAnrSapUser const &', 'arg0')])
cls.add_method('AddUeMeasReportConfigForAnr', 'uint8_t', [param('ns3::LteRrcSap::ReportConfigEutra', 'reportConfig')], is_pure_virtual=True, is_virtual=True)
... |
def import_tf_params(tf_mdl_dir, sess):
print('\nLoading tensorflow model\n')
if callable(tf_mdl_dir):
tf_mdl_dir(sess)
else:
facenet.load_model(tf_mdl_dir)
print('\nGetting model weights\n')
tf_layers = tf.trainable_variables()
tf_params = sess.run(tf_layers)
tf_shapes = [p.... |
.parametrize('length,max_seq_length,eos_token_id,expected', [(3, None, None, '[(0, 0) (1, -1) (2, -2)]')])
def test_str(tokenized_line: TokenizedLine, expected: str):
assert (str(tokenized_line) == repr(tokenized_line) == expected) |
def dataset(mode, input_Dir, motifReqs):
beta = 25
number_of_clusters = CLUSTER_NUMBER
oldAssignName = ('%s/old/assign.out' % input_Dir)
input_name = ('%s/data.out' % input_Dir)
if (mode == 1):
return runHyperParameterTests(input_name, input_Dir, number_of_clusters, beta, oldAssignName, moti... |
(Output('pattern-time-series', 'figure'), [Input('summary-scatter', 'clickData'), Input('time-interval', 'value')], prevent_initial_call=True)
def update_y_timeseries(data, interval):
print(data)
interval_map = {0: '1s', 1: '1min', 2: '1h', 3: '1d'}
pattern = data['points'][0]['customdata']
freq = inter... |
def chat_to_worker_id(cursor, code_to_wid):
d = {}
cursor.execute('SELECT chat_id, agent_ids FROM chat')
for (chat_id, agent_uids) in cursor.fetchall():
agent_wid = {}
agent_uids = eval(agent_uids)
for (agent_id, agent_uid) in agent_uids.iteritems():
if (not isinstance(ag... |
class SawyerPickOutOfHoleEnv(SawyerXYZEnv):
def __init__(self):
liftThresh = 0.11
hand_low = ((- 0.5), 0.4, (- 0.05))
hand_high = (0.5, 1, 0.5)
obj_low = (0, 0.84, (- 0.03))
obj_high = (0, 0.84, (- 0.03))
goal_low = ((- 0.1), 0.6, 0.15)
goal_high = (0.1, 0.7, ... |
_numpy_output(check_dtype=True)
def test_ufunc_heaviside_ff(A: dace.float32[10], B: dace.float32[10]):
return np.heaviside(A, B) |
def intermediate_name(filename, epoch, dev_scoring, score):
(root, ext) = os.path.splitext(filename)
return ((root + '.E{epoch:04d}-{score_type}{acc:05.2f}'.format(**{'epoch': epoch, 'score_type': dev_scoring.value, 'acc': (score * 100)})) + ext) |
class RunBenchmarkExperiment(TaskConfiguration):
ID = 'ex3'
def mode() -> str:
return 'run {}'.format(RunBenchmarkExperiment.ID)
def tasks(self, config) -> List:
compile_version = CompileVersionTask(config.compiles_path, config.run_timestamp, config.force_compile, config.use_tmp_wrkdir)
... |
def test_constructor_goals_parameter():
goals = {MagicMock(ff.FitnessFunction), MagicMock(ff.FitnessFunction)}
comparator = dc.DominanceComparator(goals=goals)
assert (comparator._objectives == goals) |
def crop_and_resize(image, height, width):
bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4])
aspect_ratio = (width / height)
image = distorted_bounding_box_crop(image, bbox, min_object_covered=0.1, aspect_ratio_range=(((3.0 / 4) * aspect_ratio), ((4.0 / 3.0) * aspect_ratio)), area_... |
class pAdicModuleIsomorphism(Map):
def _repr_type(self):
return 'Isomorphism'
def is_injective(self):
return True
def is_surjective(self):
return True
def _richcmp_(self, other, op):
if isinstance(other, pAdicModuleIsomorphism):
return rich_to_bool(op, 0)
... |
def create_spinner(repetitions: int) -> Generator[(str, None, None)]:
assert (repetitions > 0), 'The number of repetitions should be greater than zero'
while True:
for ch in '':
for _ in range(repetitions):
(yield ch) |
class GaussianMLPPolicy(StochasticPolicy, LasagnePowered):
def __init__(self, env_spec, hidden_sizes=(32, 32), learn_std=True, init_std=1.0, adaptive_std=False, std_share_network=False, std_hidden_sizes=(32, 32), min_std=1e-06, std_hidden_nonlinearity=NL.tanh, hidden_nonlinearity=NL.tanh, output_nonlinearity=None, ... |
def convert_conv_layer(conv, prefix, out):
convert_conv2d(conv.conv2d_1x3, (prefix + '.conv1'), out)
convert_layernorm(conv.BN_1x3, (prefix + '.ln1'), out)
convert_conv2d(conv.conv2d_3x1, (prefix + '.conv2'), out)
convert_layernorm(conv.BN_3x1, (prefix + '.ln2'), out)
return (conv.conv2d_1x3.strides... |
def train_model(model, criterion, optimizer, scheduler, num_epochs=25, device='cpu'):
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
for epoch in range(num_epochs):
print('Epoch {}/{}'.format(epoch, (num_epochs - 1)))
print(('-' * 10))
for p... |
def prove_BSD(E, verbosity=0, two_desc='mwrank', proof=None, secs_hi=5, return_BSD=False):
if (proof is None):
from sage.structure.proof.proof import get_flag
proof = get_flag(proof, 'elliptic_curve')
else:
proof = bool(proof)
if (not proof):
return []
from copy import co... |
def test_write_data_csv_backend(tmpdir):
statistics_dir = (tmpdir / 'statistics')
Path(statistics_dir).mkdir(parents=True, exist_ok=True)
config.configuration.statistics_output.report_dir = statistics_dir
data_1 = {'module': OutputVariable('module', 'foo'), 'value': OutputVariable('value', 'bar')}
d... |
def send_message(messages):
access_token = os.environ.get('SCRIBE_GRAPHQL_ACCESS_TOKEN')
if (not access_token):
raise ValueError("Can't find access token from environment variable")
url = '
r = requests.post(url, data={'access_token': access_token, 'logs': json.dumps([{'category': 'perfpipe_pyto... |
def check_ggui_availability():
if _ti_core.GGUI_AVAILABLE:
return
try:
import taichi
wheel_tag = try_get_wheel_tag(taichi)
if ((platform.system() == 'Linux') and wheel_tag and ('manylinux2014' in wheel_tag)):
raise GGUINotAvailableException('GGUI is not available sinc... |
class TStrPool64(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.TStrPool64_swiginit(self, _snap.new_TStrPool64(*args))
__swig_destroy__ = _snap.delete_TStrPool64
def S... |
def test_loadarff_dataframe():
contents = ''.join(EXPECTED_NO_QUOTES)
with StringIO(contents) as fp:
actual_df = loadarff(fp)
expected_df = pd.DataFrame.from_dict(OrderedDict([('attr_nominal', pd.Series(pd.Categorical.from_codes([1, 2, 0, (- 1), 2, 1], ['beer', 'water', 'wine']))), ('attr_nominal_sp... |
class DecoderLayer(nn.Module):
def __init__(self, config):
super(DecoderLayer, self).__init__()
self.slf_attn = DecoderAttention(config)
self.enc_attn = DecoderAttention(config)
self.intermediate = BertIntermediate(config)
self.output = BertOutput(config)
def forward(self... |
def sage_include_directories(use_sources=False):
if use_sources:
dirs = [SAGE_SRC]
else:
import sage
dirs = [os.path.dirname(directory) for directory in sage.__path__]
try:
import numpy
dirs.append(numpy.get_include())
except ModuleNotFoundError:
pass
... |
class VocabFromText(VocabDict):
DEFAULT_TOKENS = [VocabDict.PAD_TOKEN, VocabDict.UNK_TOKEN, VocabDict.START_TOKEN, VocabDict.END_TOKEN]
def __init__(self, sentences, min_count=1, regex=SENTENCE_SPLIT_REGEX, keep=None, remove=None, only_unk_extra=False):
if (keep is None):
keep = []
i... |
class AutoModelForMultipleChoice(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def test_fpn_extra_convs_outputs():
outs = fpn_neck_config('fpn_extra_convs_outputs')
ort_validate(*outs) |
def assert_omp_single_thread():
omp_num_threads = os.environ.get('OMP_NUM_THREADS', None)
if (omp_num_threads != '1'):
logging.getLogger('replay').warning('Environment variable "OMP_NUM_THREADS" is set to "%s". Set it to 1 if the working process freezes.', omp_num_threads) |
def eval_words(args, target, data_test):
if (args.data == 'yelp'):
bounds = {'Upper': load_result('results/res_model_yelp_1_discrete_2_1.json'), 'Ours': load_result('results/res_model_yelp_1_baf_2_1.json')}
else:
bounds = {'Upper': load_result('res_model_sst_1_discrete_2_1_100s.json'), 'Ours': l... |
.parametrize('packing_boundary,ext_type,prompt_prefix,prompt_postfix,articles,gold_tokenized_sequences,gold_unfinished_sequence', [(BoundaryType.JSONL, FileExtension.TXT, None, None, ['hi bye', 'hi bye', 'hi hi'], [[], [], [get_tokenized_seq([Token(1, COMP), Token(2, COMP), Token(0, SEP), Token(1, COMP), Token(2, COMP)... |
def _type_is_enforceable(layout: ak.contents.Content, type_: ak.types.Type) -> _TypeEnforceableResult:
if layout.is_unknown:
return _TypeEnforceableResult(is_enforceable=True, requires_packing=False)
elif isinstance(type_, ak.types.UnknownType):
return _TypeEnforceableResult(is_enforceable=False... |
def to_ordered_dict(obj: Base, skip_missing: bool=True, deepcopy: bool=True) -> OrderedDict:
return obj.to_ordered_dict(skip_missing=skip_missing, deepcopy=deepcopy) |
def test_abs_complex():
time_dim = Dim(Tensor('time', [batch_dim], dtype='int32'))
in_dim = Dim(7, name='in')
extern_data = TensorDict({'data': Tensor('data', [batch_dim, time_dim, in_dim], dtype='complex64')})
class _Net(rf.Module):
def __call__(self, x: Tensor) -> Tensor:
return rf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.