code stringlengths 101 5.91M |
|---|
def test_regulartype_numpytype():
t = RegularType(NumpyType('int32'), 5)
assert (str(ak.types.from_datashape(str(t), highlevel=False)) == str(t)) |
(eq=False)
class Thread(RefObj):
lib_list: Table = dc.field(repr=False, hash=None, compare=False)
name: str
processType: str
processStartupTime: float
registerTime: float
isMainThread: bool
processName: str
pid: int
tid: int
markers: Table = dc.field(default_factory=Table)
sa... |
def premul_lstm_cell_no_bias(igates, hidden, w_hh, b_hh):
(hx, cx) = hidden
gates = ((igates + torch.mm(hx, w_hh.t())) + b_hh)
(ingate, forgetgate, cellgate, outgate) = gates.chunk(4, 1)
ingate = torch.sigmoid(ingate)
forgetgate = torch.sigmoid(forgetgate)
cellgate = torch.tanh(cellgate)
out... |
def plot(dfs, anomalies=[]):
if isinstance(dfs, pd.DataFrame):
dfs = [dfs]
if (not isinstance(anomalies, list)):
anomalies = [anomalies]
df = dfs[0]
time = convert_date(df['timestamp'])
months = mdates.MonthLocator()
days = mdates.DayLocator()
month_fmt = mdates.DateFormatter... |
def _rebuild_tensor(storage, storage_offset, size, stride):
class_name = storage.__class__.__name__.replace('Storage', 'Tensor')
module = importlib.import_module(storage.__module__)
tensor_class = getattr(module, class_name)
return tensor_class().set_(storage, storage_offset, size, stride) |
class MLP(nn.Module):
def __init__(self, feat_len, num_class, hidden=[64, 32], dropout=[0]):
super().__init__()
(self.feat_len, self.hidden) = (feat_len, num_class)
self.tran1 = nn.Linear(feat_len, hidden[0], bias=False)
self.tran2 = nn.Linear(hidden[0], hidden[1], bias=False)
... |
def test_record_array_with_object_field():
y = ma.masked_array([(1, '2'), (3, '4')], mask=[(0, 0), (0, 1)], dtype=[('a', int), ('b', object)])
y[1] |
class MultiscaleDiscrSingleInput(SingleToMultiScaleInputMixin, DiscriminatorMultiToSingleOutputStackedMixin, MultiscaleDiscriminatorSimple):
pass |
def remove_if_exists(path: Path) -> None:
if (not path.exists()):
logger.debug(f"Doesn't exist: {path}")
return
elif path.is_dir():
logger.debug(f'Removing directory: {path}')
shutil.rmtree(path)
else:
logger.debug(f'Removing file: {path}')
path.unlink() |
def register_types(module):
root_module = module.get_root()
module.add_enum('PbbAddressLength', ['IPV4', 'IPV6'], import_from_module='ns.network')
module.add_enum('ethernet_header_t', ['LENGTH', 'VLAN', 'QINQ'], import_from_module='ns.network')
module.add_enum('LogLevel', ['LOG_NONE', 'LOG_ERROR', 'LOG_... |
.parametrize('inspec_and_axis', (general_cases(False) + large_reduction_cases_for_layer_norm()))
def test_layer_normalization(inspec_and_axis, nnabla_opts):
(inspec, axis) = inspec_and_axis
fb = FunctionBenchmark(PF.layer_normalization, inspec, [], dict(), nnabla_opts.ext, nnabla_opts.ext_kwargs)
fb.benchma... |
class BatchNorm2dSyncFunc(Function):
def forward(ctx, x, weight, bias, running_mean, running_var, extra, compute_stats=True, momentum=0.1, eps=1e-05):
def _parse_extra(ctx, extra):
ctx.is_master = extra['is_master']
if ctx.is_master:
ctx.master_queue = extra['master_q... |
class UnsupportedNodeError(NotSupportedError):
def __init__(self, ctx, offending_node):
node_type = type(offending_node)
range_len = len(node_start_tokens.get(node_type, ' '))
source_range = ctx.make_range(offending_node.lineno, offending_node.col_offset, (offending_node.col_offset + range_l... |
def get_score(weights, model, cache, example_dataset, batch_size, get_loss, get_regular):
final_state_dict = {}
lora_module_list = list(cache.keys())
keys = cache[lora_module_list[0]].keys()
for (i, peft_model_id) in enumerate(lora_module_list):
lora_state_dict = cache[peft_model_id]
if ... |
class TestInputPipelineDef(tf.test.TestCase):
def test_without_extra_args(self):
pipeline_def = yaml.load('\n class: ParallelTextInputPipeline\n params:\n source_files: ["file1"]\n target_files: ["file2"]\n num_epochs: 1\n shuffle: True\n ')
pipeline = input_... |
def plot_detections(rois, id, obj_id, imagePath, targetPath='vis_detections'):
img = cv2.imread(os.path.join(imagePath, ('%05d.jpg' % id)))
for i in range(rois.shape[0]):
roi = rois[i]
cv2.rectangle(img, pt1=(roi[1], roi[0]), pt2=(roi[3], roi[2]), color=(0, 255, 0), thickness=2)
img = cv... |
_model('nacrf_transformer')
class NACRFTransformerModel(NATransformerModel):
def __init__(self, args, encoder, decoder):
super().__init__(args, encoder, decoder)
self.crf_layer = DynamicCRF(num_embedding=len(self.tgt_dict), low_rank=args.crf_lowrank_approx, beam_size=args.crf_beam_approx)
def al... |
def restoration_inference(model, img, ref=None):
cfg = model.cfg
device = next(model.parameters()).device
keys_to_remove = ['gt', 'gt_path']
for key in keys_to_remove:
for pipeline in list(cfg.test_pipeline):
if (('key' in pipeline) and (key == pipeline['key'])):
cfg.... |
class SagePackageTestCase(unittest.TestCase):
def run_command(self, *args, **kwds):
env = dict(os.environ)
env.update(kwds.get('env', {}))
env['PATH'] = ((PATH + os.pathsep) + env['PATH'])
kwds.update(stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
log.de... |
class NeuralSpectralKernel(gpflow.kernels.Kernel):
def __init__(self, input_dim, active_dims=None, Q=1, hidden_sizes=None):
super().__init__(input_dim, active_dims=active_dims)
self.Q = Q
if (hidden_sizes is None):
hidden_sizes = (32, 32)
self.num_hidden = len(hidden_size... |
class TestScenarios(unittest.TestCase):
def compare_times(self, evaluator, h_idx=0):
trajectory_hr = evaluator.evaluate_one_optimal_one_greedy_human(h_idx=h_idx, display=DISPLAY)
time_taken_hr = trajectory_hr['ep_lengths'][0]
print(('\n' * 5), '\n', ('-' * 50))
trajectory_rr = evalua... |
def main():
configs = collect_configurations()
statistics_file = eval(configs)
make_plots(statistics_file) |
_function_dispatch(_apply_along_axis_dispatcher)
def apply_along_axis(func1d, axis, arr, *args, **kwargs):
arr = asanyarray(arr)
nd = arr.ndim
axis = normalize_axis_index(axis, nd)
in_dims = list(range(nd))
inarr_view = transpose(arr, ((in_dims[:axis] + in_dims[(axis + 1):]) + [axis]))
inds = nd... |
class PromptDataSetClass(Dataset):
def __init__(self, dataframe, tokenizer, source_len, target_len, source_text, target_text, return_dict=False):
self.tokenizer = tokenizer
self.data = dataframe
self.source_len = source_len
self.summ_len = target_len
self.target_text = self.d... |
def test_capture_tuple():
program = 'def f(x):\n try:\n risky()\n except (a.AError, b.BError):\n raise\n'
__assert_found(program, 'a.AError', 'b.BError') |
def list_to_string(x):
if x:
s = str(x).replace('[', '').replace(']', '').replace(',', '')
else:
s = '-'
return s |
def register_methods(root_module):
register_Ns3Address_methods(root_module, root_module['ns3::Address'])
register_Ns3ApplicationContainer_methods(root_module, root_module['ns3::ApplicationContainer'])
register_Ns3AsciiTraceHelper_methods(root_module, root_module['ns3::AsciiTraceHelper'])
register_Ns3Asc... |
def batchnorm3d_to_instancenorm3d(model):
conversion_count = 0
for (name, module) in reversed(model._modules.items()):
if (len(list(module.children())) > 0):
(model._modules[name], num_converted) = batchnorm3d_to_instancenorm3d(module)
conversion_count += num_converted
if... |
def run_batch(cur_batch, model):
mean = np.array([0.485, 0.456, 0.406]).reshape(1, 3, 1, 1)
std = np.array([0.229, 0.224, 0.224]).reshape(1, 3, 1, 1)
image_batch = np.concatenate(cur_batch, 0).astype(np.float32)
image_batch = (((image_batch / 255.0) - mean) / std)
image_batch = torch.FloatTensor(ima... |
def test_interpolate_as():
source = torch.rand((1, 5, 4, 4))
target = torch.rand((1, 1, 16, 16))
result = interpolate_as(source, target)
assert (result.shape == torch.Size((1, 5, 16, 16)))
result = interpolate_as(source, target.squeeze(0))
assert (result.shape == torch.Size((1, 5, 16, 16)))
... |
(for_each_device=True)
def cunnex(strFunction):
return cupy.cuda.compile_with_cache(globals()[strFunction]).get_function(strFunction) |
class DatasetJsonifier(ABC):
input_dir: str
name: str
split: str
data: Sequence[Any] = None
def load_raw_data(self):
raise
def export_to_json(self, output_dir, examples_per_shard: Optional[int]=None):
if (not self.data):
print('[WARNING] no data to write; returning.')... |
def hessian_vector_product(f, params):
g = flat_grad(f, params)
x = tf.placeholder(tf.float32, shape=g.shape)
return (x, flat_grad(tf.reduce_sum((g * x)), params)) |
def test_get_n_splits_BlockBootstrap() -> None:
cv = BlockBootstrap(n_resamplings=3)
assert (cv.get_n_splits() == 3) |
def project(bipartite):
nodes_papers = {n for (n, d) in bipartite.nodes(data=True) if (d['bipartite'] == 0)}
nodes_authors = (set(bipartite) - nodes_papers)
graph_papers = nxb.weighted_projected_graph(bipartite, nodes_papers)
graph_authors = nxb.weighted_projected_graph(bipartite, nodes_authors)
pri... |
_utils.test(require=ti.extension.sparse)
def test_pointer_is_active():
x = ti.field(ti.f32)
s = ti.field(ti.i32)
n = 128
ptr = ti.root.pointer(ti.i, n)
ptr.dense(ti.i, n).place(x)
ti.root.place(s)
def func():
for i in range((n * n)):
s[None] += ti.is_active(ptr, ti.rescal... |
def load_model(model_path, gpuid=None):
model = load(os.path.join(model_path, 'outer_model.est'))
if (gpuid == None):
gpuid = model.gpuid
else:
gpuid = str(gpuid)
os.environ['CUDA_VISIBLE_DEVICES'] = gpuid
model.gpuid = gpuid
model._model = load_tf_model(os.path.join(model_path, ... |
def setUpModule():
if (not (CAFFE_FOUND and os.path.exists('data/testdata/caffe_translator'))):
return
caffenet = caffe_pb2.NetParameter()
caffenet_pretrained = caffe_pb2.NetParameter()
with open('data/testdata/caffe_translator/deploy.prototxt') as f:
text_format.Merge(f.read(), caffenet... |
def _make_timedelta(value):
if (not isinstance(value, timedelta)):
return timedelta(seconds=value)
return value |
def resolve(module_name, dotted_path):
if (module_name in sys.modules):
mod = sys.modules[module_name]
else:
mod = __import__(module_name)
if (dotted_path is None):
result = mod
else:
parts = dotted_path.split('.')
result = getattr(mod, parts.pop(0))
for p... |
class TestCodeWriter(CythonTest):
def t(self, codestr):
self.assertCode(codestr, self.fragment(codestr).root)
def test_print(self):
self.t(u'\n print x, y\n print x + y ** 2\n print x, y, z,\n ')
def test_if(self):
... |
def power_spectrum_multipoles(input_array, kbins=10, box_dims=None, los_axis=0, output=['P0', 'P2', 'P4', 'nmodes'], exclude_zero_modes=False):
assert ((los_axis >= 0) and (los_axis <= len(input_array.shape)))
box_dims = _get_dims(box_dims, input_array.shape)
ps = power_spectrum_nd(input_array, box_dims)
... |
def dump_metrics(file_path: str, metrics, log: bool=False) -> None:
metrics_json = json.dumps(metrics, indent=2)
with open(file_path, 'w') as metrics_file:
metrics_file.write(metrics_json)
if log:
logger.info('Metrics: %s', metrics_json) |
class CSharp4Listener(ParseTreeListener):
def enterNamespace_name(self, ctx):
pass
def exitNamespace_name(self, ctx):
pass
def enterType121_name(self, ctx):
pass
def exitType121_name(self, ctx):
pass
def enterIdentifier(self, ctx):
pass
def exitIdentifier(... |
class CSVReader(Reader):
def process(self, fp):
r = csv.DictReader(fp)
return [line for line in r] |
def GetKappa(mol):
res = OrderedDict()
for (k, func) in _Kappa.items():
res.update({k: func(mol)})
return res |
def extract_ans_csv(file):
with open(file, 'r') as fin:
out = []
reader = csv.reader(fin)
next(reader)
for line in reader:
(query, ans) = line[:2]
my_query = os.path.splitext(os.path.split(query)[1])[0]
my_ans = os.path.splitext(os.path.split(ans)[... |
def test_seg2boundary():
seg = np.array([[]])
text_repr_type = 'quad'
text_score = None
with pytest.raises(AssertionError):
mask_utils.seg2boundary([[]], text_repr_type, text_score)
with pytest.raises(AssertionError):
mask_utils.seg2boundary(seg, 1, text_score)
with pytest.raises... |
def gelu_fast(x):
x = tf.convert_to_tensor(x)
coeff1 = tf.cast(0.044715, x.dtype)
coeff2 = tf.cast(0., x.dtype)
return ((0.5 * x) * (1.0 + tf.tanh(((x * coeff2) * (1.0 + ((coeff1 * x) * x)))))) |
()
('--batch_size', type=int, default=4000)
_experiment
def ppo_memorize_digits(ctxt=None, seed=1, batch_size=4000):
set_seed(seed)
with LocalTFRunner(ctxt) as runner:
env = GarageEnv(normalize(gym.make('MemorizeDigits-v0')), is_image=True)
policy = CategoricalCNNPolicy(env_spec=env.spec, filter... |
class RPN(nn.Module):
def __init__(self):
super(RPN, self).__init__()
def forward(self, z_f, x_f):
raise NotImplementedError |
def register_Ns3FrameCaptureModel_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::FrameCaptureModel const &', 'arg0')])
cls.add_method('CaptureNewFrame', 'bool', [param('ns3::Ptr< ns3::Event >', 'currentEvent'), param('ns3::Ptr< ns3::Event >', 'newEvent')], is_pure_virtua... |
class MultiSimilarityLoss(nn.Module):
def __init__(self, thresh=0.5, _margin=0.1, scale_pos=2.0, scale_neg=40.0, **kwargs):
super(MultiSimilarityLoss, self).__init__()
self.thresh = thresh
self.margin = _margin
self.scale_pos = scale_pos
self.scale_neg = scale_neg
sel... |
def get_with_answers(recieved):
answers = []
for (_, _, src) in recieved:
tokens = src.split(' ')
answer = []
for token in tokens:
features = token.split('')
word = features[0]
ans_tag = features[1]
if ((ans_tag == 'B') or (ans_tag == 'I'))... |
def merge_states(x):
x_shape = shape_list(x)
new_x_shape = (x_shape[:(- 2)] + [np.prod(x_shape[(- 2):])])
return tf.reshape(x, new_x_shape) |
.parametrize('num_models', [1, 3])
.parametrize('shadow_model_fn,model_serializer', [(keras_shadow_model_fn, None), (torch_shadow_model_fn, None), (torch_shadow_model_fn, pytest.lazy_fixture('torch_shadow_serializer'))])
def test_shadow_models_are_created_and_data_is_transformed(data, shadow_model_fn, model_serializer,... |
class Transformer_NonRecursive(Transformer):
def transform(self, tree):
rev_postfix = []
q = [tree]
while q:
t = q.pop()
rev_postfix.append(t)
if isinstance(t, Tree):
q += t.children
stack = []
for x in reversed(rev_postfix)... |
def extract_melspec(task):
(fps, src_wav, dst_npy) = task
src_wav = src_wav.replace('_left', '').replace('_right', '')
if os.path.exists(dst_npy):
return 1
try:
(y, sr) = librosa.load(src_wav, sr=16000)
hop_length = int(((((1 / 3) * 1) / fps) * 16000))
power = librosa.fea... |
def test():
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../datasets/images/')
img = Resize((256, 256)).transform(Image(PilImage.open((directory + 'dog_cat.png')).convert('RGB')))
test_instance = img.to_numpy()[0]
svc = init_service(model_tag='vision_explainer:latest', tas... |
def add_cwe_class(problem_col):
cwe_classes = []
for p in problem_col:
des = str(p).replace("'", '"')
des = json.loads(des)
for cwes in json_normalize(des)['description']:
if (len(cwes) != 0):
cwe_classes.append([cwe_id for cwe_id in json_normalize(cwes)['valu... |
_decorator(1)
def get_max_num(html):
soup = BeautifulSoup(html, 'lxml')
href_list = soup.find(attrs={'action-type': 'feed_list_page_morelist'}).find_all('a')
return len(href_list) |
class ModelArguments():
model_name_or_path: str = field(default=None, metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'})
config_name: Optional[str] = field(default=None, metadata={'help': 'Pretrained config name or path if not the same as model_name'})
tokenizer_na... |
def train(model, data_loader, optimizer, tokenizer, epoch, warmup_steps, device, scheduler, config):
model.train()
metric_logger = utils.MetricLogger(delimiter=' ')
metric_logger.add_meter('lr', utils.SmoothedValue(window_size=50, fmt='{value:.6f}'))
metric_logger.add_meter('loss_mlm', utils.SmoothedVa... |
def tangent_jacobians_chain_rule(expr: T.Element, args: T.Sequence[T.Element]) -> T.List[sf.Matrix]:
jacobians = []
expr_storage = sf.M(StorageOps.to_storage(expr))
expr_tangent_D_storage = LieGroupOps.tangent_D_storage(expr)
for arg in args:
expr_storage_D_arg_storage = expr_storage.jacobian(St... |
def main():
output_dir = '{}/wav{}/{}/{}'.format(args.tgt_dir, args.sample_rate, args.mode, args.part)
if os.path.exists(output_dir):
raise ValueError('Warning: {} already exists, please check!'.format(output_dir))
else:
os.makedirs(output_dir)
wav_dir = '{}/wav{}/{}/{}'.format(args.src_... |
class AndNode(ASTNode):
def __init__(self, data_type, fields):
super().__init__('AND', 'AND', data_type, fields)
def textual_form_core(self):
if (self.fields[0].depth == 0):
return ' '.join([self.fields[0].textual_form(), 'that', self.fields[1].textual_form()])
else:
... |
def prepare_xlnet_input(args, _, tokenizer, prompt_text):
prompt_text = ((args.padding_text if args.padding_text else PADDING_TEXT) + prompt_text)
return prompt_text |
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('dump_dir')
parser.add_argument('out_dir')
parser.add_argument('ranker_path')
parser.add_argument('--start', default=0, type=int)
parser.add_argument('--end', default=1, type=int)
parser.add_argument('--nfs', default=Fals... |
class GPTSanJapaneseConfig(PretrainedConfig):
model_type = 'gptsan-japanese'
keys_to_ignore_at_inference = ['past_key_values']
attribute_map = {'hidden_size': 'd_model', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'}
def __init__(self, vocab_size=36000, max_position_embeddings=12... |
def load_datasets(sample=0.1, list_params=None, load_t=(0, (- 6)), valid_split=0.2, test_split=0.2, randomseed=47):
if (list_params is None):
list_params = ['r', 'd', 'o3', 'v', 'ciwc', 'q', 'pv', 'z', 'clwc', 't', 'w', 'vo', 'u', 'cc']
X1 = []
X2 = []
Y = []
storm_ids = []
print('loadin... |
def simSetJointInterval(jointHandle, cyclic, interval):
ret = lib.simSetJointInterval(jointHandle, cyclic, interval)
_check_return(ret) |
(('Python' not in caffe.layer_type_list()), 'Caffe built without Python layer support')
class TestLayerWithParam(unittest.TestCase):
def setUp(self):
net_file = python_param_net_file()
self.net = caffe.Net(net_file, caffe.TRAIN)
os.remove(net_file)
def test_forward(self):
x = 8
... |
_grad()
def evaluate_step(model, dataset, task: Tuple[(int, int)], fast: bool=False) -> dict:
(today, tomorrow) = task
assert (tomorrow == (today + 1)), 'Currently support 1 step forword only.'
model.eval()
for t in range(today):
new_batch = get_task_batch(dataset, t, (t + 1), None).clone()
... |
def getdtype(dtype, a=None, default=None):
if (dtype is None):
try:
newdtype = a.dtype
except AttributeError as e:
if (default is not None):
newdtype = np.dtype(default)
else:
raise TypeError('could not interpret data type') from e
... |
def idx_split(idx, ratio, seed=0):
set_seed(seed)
n = len(idx)
cut = int((n * ratio))
idx_idx_shuffle = torch.randperm(n)
(idx1_idx, idx2_idx) = (idx_idx_shuffle[:cut], idx_idx_shuffle[cut:])
(idx1, idx2) = (idx[idx1_idx], idx[idx2_idx])
return (idx1, idx2) |
class CollectionLengthAssertion(ReferenceAssertion):
def __init__(self, source: vr.Reference, length: int):
super().__init__(source)
self._length = length
def length(self) -> int:
return self._length
def accept(self, visitor: AssertionVisitor) -> None:
visitor.visit_collectio... |
def CalculateNormalizedMoreauBrotoAutoResidueASA(ProteinSequence):
result = CalculateEachNormalizedMoreauBrotoAuto(ProteinSequence, _ResidueASA, '_ResidueASA')
return result |
def apply_multiple_times(A: dace.float64[(10, 10, 10)]):
for i in range(10):
for j in range(10):
for k in dace.map[0:10]:
A[(k, i, j)] = (((i * 100) + (j * 10)) + k) |
def version_dict():
v = SAGE_VERSION.split('.')
dict = {}
dict['major'] = int(v[0])
dict['minor'] = int(v[1])
dict['tiny'] = 0
dict['prerelease'] = False
try:
int(v[(- 1)])
except ValueError:
dict['prerelease'] = True
if (((len(v) == 3) and (not dict['prerelease'])) o... |
def test_find_by_status(testdir):
testdir.make_petstore_test('\(endpoint="/pet/findByStatus$")\(max_examples=5, deadline=None)\ndef test_(request, case):\n request.config.HYPOTHESIS_CASES += 1\n assert_list(case.query["status"])\n for item in case.query["status"]:\n assert item in ("available", "pen... |
(scope='session')
def simple_openapi():
return {'openapi': '3.0.2', 'info': {'title': 'Test', 'description': 'Test', 'version': '0.1.0'}, 'paths': {'/query': {'get': {'parameters': [{'name': 'id', 'in': 'query', 'required': True, 'schema': {'type': 'string', 'minLength': 1}}, {'name': 'value', 'in': 'header', 'requ... |
def compute_Ap():
for (i, j, k) in Ap:
Ap[(i, j, k)] = (((((((6.0 * p[(i, j, k)]) - p[((i + 1), j, k)]) - p[((i - 1), j, k)]) - p[(i, (j + 1), k)]) - p[(i, (j - 1), k)]) - p[(i, j, (k + 1))]) - p[(i, j, (k - 1))]) |
class WorkerInfo(object):
__initialized = False
def __init__(self, **kwargs):
for (k, v) in kwargs.items():
setattr(self, k, v)
self.__keys = tuple(kwargs.keys())
self.__initialized = True
def __setattr__(self, key, val):
if self.__initialized:
raise R... |
def setup_devices(args):
main_gpu = 0
if (not args['no_cuda']):
if isinstance(args['devices'], tuple):
main_gpu = args['devices'][0]
elif isinstance(args['devices'], int):
main_gpu = args['devices']
elif isinstance(args['devices'], dict):
main_gpu = ar... |
def compute_hessian(f, params):
h = []
for i in params:
h_i = []
for j in params:
grad = torch.autograd.grad(f, j, create_graph=True)
h_ij = torch.autograd.grad(grad, i, allow_unused=True, retain_graph=True)
h_ij = ((torch.tensor(0.0),) if (h_ij[0] is None) el... |
def setup(app):
app.add_domain(ScipyOptimizeInterfaceDomain)
return {'parallel_read_safe': True} |
def unpickle(file_path):
with open(file_path, 'rb') as f:
data = pk.load(f)
return data |
class QDQBertForSequenceClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class SICETrain(SICE):
def __init__(self, dir_data, **kwargs):
super().__init__(dir_data, split='train', **kwargs) |
def test_cast_to_datetime64():
string_value = '2021-02-02'
list_value = [None, np.nan, '2021-02-02']
series_value = pd.Series(['2021-02-02', None, pd.NaT])
string_out = cast_to_datetime64(string_value)
list_out = cast_to_datetime64(list_value)
series_out = cast_to_datetime64(series_value)
ex... |
.parametrize('context, action, description', invalid_input_of_calc_policy_value)
def test_synthetic_continuous_calc_policy_value_using_invalid_inputs(context, action, description):
dataset = SyntheticContinuousBanditDataset()
with pytest.raises(ValueError, match=f'{description}*'):
_ = dataset.calc_grou... |
class RDB_Conv(nn.Module):
def __init__(self, inChannels, growRate, kSize=3):
super(RDB_Conv, self).__init__()
Cin = inChannels
G = growRate
self.conv = nn.Sequential(*[nn.Conv2d(Cin, G, kSize, padding=((kSize - 1) // 2), stride=1), nn.ReLU()])
def forward(self, x):
out =... |
def valid_loop(net, loader):
net.eval()
epoch_losses = Counter()
with torch.no_grad():
for (iit, batch) in tqdm(enumerate(loader, 1), position=1, total=len(loader)):
for (k, v) in batch.items():
if torch.is_tensor(v):
batch[k] = v.to(device)
... |
class _vq_wav2vec_codeids_wrapper(torch.nn.Module):
def __init__(self, vq_wav2vec):
super().__init__()
self.vq_wav2vec = vq_wav2vec
self.featurizer = _Featurizer(vq_wav2vec, 'codeids', upstream_device='cpu')
def _indices_to_string(self, sentence_idxs):
return (('<s> ' + ' '.join(... |
def get_layer_bytes(layer, is_in):
total_bytes = 0
tensors = (layer.in_tensors if is_in else layer.out_tensors)
for tensor in tensors:
tensor_bytes = get_layer_dtype(tensor.dtype)
for s in tensor.shape:
tensor_bytes *= s
total_bytes += tensor_bytes
return total_bytes |
def test_cnn_fit_resample():
cnn = CondensedNearestNeighbour(random_state=RND_SEED)
(X_resampled, y_resampled) = cnn.fit_resample(X, Y)
X_gt = np.array([[(- 0.), (- 0.)], [0., 0.], [0., 0.], [(- 1.), (- 0.)], [0., 0.], [0., 1.], [(- 0.284881), (- 0.)], [0., 0.], [(- 0.), 0.], [0., 0.]])
y_gt = np.array(... |
def visualize_matrix(writer, matrix_arr, iteration, title_str):
stage = 'valid'
for i in range(len(matrix_arr)):
C = matrix_arr[i].shape[1]
matrix = matrix_arr[i][0].unsqueeze(0)
matrix = torch.clamp(torch.abs(matrix), max=1)
matrix = torch.cat((torch.ones(1, C, C).cuda(), torch.... |
def qexp_eta(ps_ring, prec):
prec = Integer(prec)
if (not (prec > 0)):
raise ValueError('prec must be a positive integer')
v = ([Integer(0)] * prec)
pm = Integer(1)
v[0] = pm
try:
n = 1
while True:
pm = (- pm)
v[((n * ((3 * n) - 1)) // 2)] = pm
... |
def test_import_normfactor_bounds():
parsed_xml = pyhf.readxml.parse('validation/xmlimport_input2/config/example.xml', 'validation/xmlimport_input2')
ws = pyhf.Workspace(parsed_xml)
assert (('SigXsecOverSM', 'normfactor') in ws.modifiers)
parameters = [p for p in ws.get_measurement(measurement_name='Gau... |
def create_argparser():
defaults = dict(num_samples=80000, batch_size=20000, model_path='')
defaults.update(model_and_diffusion_defaults_2d())
parser = argparse.ArgumentParser()
parser.add_argument('--task', type=int, default=0, help='Which dataset to sample from.')
add_dict_to_argparser(parser, def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.