code stringlengths 101 5.91M |
|---|
_function_dispatch(_around_dispatcher)
def round_(a, decimals=0, out=None):
return around(a, decimals=decimals, out=out) |
.parametrize('numeric,subtypes', [(complex, [complex, float, int, bool]), (float, [float, int, bool]), (int, [int, bool]), (bool, [bool])])
def test_numeric_tower(type_system, numeric, subtypes):
assert (type_system.numeric_tower[type_system.convert_type_hint(numeric)] == [type_system.convert_type_hint(typ) for typ... |
class EM1D_FD_Jacobian_Test_CircularLoop(unittest.TestCase):
def setUp(self):
nearthick = np.logspace((- 1), 1, 5)
deepthick = np.logspace(1, 2, 10)
thicknesses = np.r_[(nearthick, deepthick)]
topo = np.r_[(0.0, 0.0, 100.0)]
height = 1e-05
src_location = np.array([0.0... |
class PyTorchBenchmark(Benchmark):
args: PyTorchBenchmarkArguments
configs: PretrainedConfig
framework: str = 'PyTorch'
def framework_version(self):
return torch.__version__
def _inference_speed(self, model_name: str, batch_size: int, sequence_length: int) -> float:
_inference = self... |
class DecisionNet(nn.Module):
def __init__(self, init_weights=True):
super(DecisionNet, self).__init__()
self.layer1 = nn.Sequential(nn.MaxPool2d(2), nn.Conv2d(1025, 8, 5, stride=1, padding=2), nn.BatchNorm2d(8), nn.ReLU(inplace=True), nn.MaxPool2d(2), nn.Conv2d(8, 16, 5, stride=1, padding=2), nn.Ba... |
def monomials(v, n):
if (len(v) != len(n)):
raise ValueError('inputs must be of the same length.')
if (len(v) == 0):
return []
v = Sequence(v)
R = v.universe()
return _monomials(v, R, n, 0) |
def test_full_like_types():
array = ak.highlevel.Array(np.array(['2020-07-27T10:41:11', '2019-01-01', '2020-01-01'], 'datetime64[s]'))
assert (ak.operations.full_like(array, '2020-07-27T10:41:11').to_list() == [datetime.datetime(2020, 7, 27, 10, 41, 11), datetime.datetime(2020, 7, 27, 10, 41, 11), datetime.date... |
(frozen=True, eq=True)
class MetricName():
name: str
split: Optional[str] = None
sub_split: Optional[str] = None
perturbation: Optional[PerturbationDescription] = None |
class OfflineTests(TestCasePlus):
_torch
def test_offline_mode(self):
load = '\nfrom transformers import BertConfig, BertModel, BertTokenizer\n '
run = '\nmname = "lysandre/tiny-bert-random"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretraine... |
def test_torch_summer():
model_with_sum = Summer(PositionalEncoding2D(125))
model_wo_sum = PositionalEncoding2D(125)
z = torch.rand(3, 5, 6, 125)
assert (np.sum(np.abs(((model_wo_sum(z) + z).numpy() - model_with_sum(z).numpy()))) < 0.0001), 'The summer is not working properly!' |
def get_env_info():
run_lambda = run
(pip_version, pip_list_output) = get_pip_packages(run_lambda)
if TORCH_AVAILABLE:
version_str = torch.__version__
debug_mode_str = str(torch.version.debug)
cuda_available_str = str(torch.cuda.is_available())
cuda_version_str = torch.versio... |
_REGISTRY.register()
class SingleImageDataset(data.Dataset):
def __init__(self, opt):
super(SingleImageDataset, self).__init__()
self.opt = opt
self.file_client = None
self.io_backend_opt = opt['io_backend']
self.mean = (opt['mean'] if ('mean' in opt) else None)
self.... |
.parametrize('seed', [311])
.parametrize('clear_buffer', [True, False])
def test_graph_rewire(seed, clear_buffer):
nn.clear_parameters()
def mlp2(x, scope):
with nn.parameter_scope(scope):
h = F.tanh(PF.affine(x, 10, name='a1'))
h = F.tanh(PF.affine(h, 10, name='a1'))
... |
def test_inconsistent_dimensions():
m = 2
n = 4
c = [1, 2, 3, 4]
Agood = np.random.rand(m, n)
Abad = np.random.rand(m, (n + 1))
bgood = np.random.rand(m)
bbad = np.random.rand((m + 1))
boundsbad = ([(0, 1)] * (n + 1))
assert_raises(ValueError, _clean_inputs, c=c, A_ub=Abad, b_ub=bgoo... |
def load_remote_uri(uri: str) -> Any:
response = requests.get(uri, timeout=(DEFAULT_RESPONSE_TIMEOUT / 1000))
return load_yaml(response.content) |
def save_model(args, model):
model_to_save = (model.module if hasattr(model, 'module') else model)
client_name = os.path.basename(args.single_client).split('.')[0]
model_checkpoint = os.path.join(args.output_dir, ('%s_%s_checkpoint.bin' % (args.name, client_name)))
torch.save(model_to_save.state_dict(),... |
def decode_jpeg(image_buffer, scope=None):
with tf.name_scope(values=[image_buffer], name=scope, default_name='decode_jpeg'):
image = tf.image.decode_jpeg(image_buffer, channels=3)
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
return image |
class _EstimatorPrettyPrinter(pprint.PrettyPrinter):
def __init__(self, indent=1, width=80, depth=None, stream=None, *, compact=False, indent_at_name=True, n_max_elements_to_show=None):
super().__init__(indent, width, depth, stream, compact=compact)
self._indent_at_name = indent_at_name
if s... |
def get_static_parameters_from_examples(operation: APIOperation, examples_field: str) -> list[dict[(str, Any)]]:
operation_definition = fast_deepcopy(operation.definition.resolved)
for parameter in operation.definition.parameters:
parameters = operation_definition.setdefault('parameters', [])
if... |
class TapasConfig(PretrainedConfig):
model_type = 'tapas'
def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=1024, type_vocab_sizes=[3, 2... |
class DilatedParllelResidualBlockB1(nn.Module):
def __init__(self, nIn, nOut, prob=0.03):
super().__init__()
n = int((nOut / 4))
n1 = (nOut - (3 * n))
self.c1 = C(nIn, n, 3, 1)
self.d1 = CDilated(n, n1, 3, 1, 1)
self.d2 = CDilated(n, n, 3, 1, 2)
self.d4 = CDil... |
def is_taichi_class(rhs):
taichi_class = False
try:
if rhs._is_taichi_class:
taichi_class = True
except:
pass
return taichi_class |
def prd_uncertainty(mu_mcs):
return (np.mean(np.square(mu_mcs), 0) - np.square(np.mean(mu_mcs, 0))) |
class Runner(object):
def __init__(self, model, batch_processor, optimizer=None, work_dir=None, log_level=logging.INFO, logger=None, meta=None):
assert callable(batch_processor)
self.model = model
if (optimizer is not None):
self.optimizer = self.init_optimizer(optimizer)
... |
class CmdLineParserTest(TestCase):
def setUp(self):
backup = {}
for (name, value) in vars(Options).items():
backup[name] = value
self._options_backup = backup
def tearDown(self):
no_value = object()
for (name, orig_value) in self._options_backup.items():
... |
_utils.test()
def test_mod_scan():
z = ti.field(ti.i32, shape=())
w = ti.field(ti.i32, shape=())
def func(x: ti.i32, y: ti.i32):
z[None] = (x % y)
w[None] = ti.raw_mod(x, y)
for i in range((- 10), 11):
for j in range((- 10), 11):
if (j != 0):
func(i, j... |
class FlaubertForTokenClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def max_dict(myDict, byValue=False):
if byValue:
skey = (lambda x: x[1])
else:
skey = (lambda x: x[0])
return max(myDict.items(), key=skey) |
def choose_optimiser(optimiser_name=ADAM):
if (optimiser_name == ADAM):
return torch.optim.Adam
elif (optimiser_name == SGD):
return torch.optim.SGD
elif (optimiser_name == RMSPROP):
return torch.optim.RMSprop |
def test_predict_with_predict_params():
pipe = Pipeline([('transf', Transf()), ('clf', DummyEstimatorParams())])
pipe.fit(None, None)
pipe.predict(X=None, got_attribute=True)
assert pipe.named_steps['clf'].got_attribute |
class Gen():
def __init__(self, gen):
self._gen = gen
def __call__(self):
for case in self._gen:
source_ints = case['inputs']
target_ints = case['targets']
(yield generator_utils.to_example({'inputs': source_ints, 'targets': target_ints})) |
class SymmetricFunctionAlgebra_multiplicative(classical.SymmetricFunctionAlgebra_classical):
def product_on_basis(self, left, right):
m = (list(left) + list(right))
m.sort(reverse=True)
return self.monomial(sage.combinat.partition.Partition(m))
def coproduct_on_basis(self, mu):
T... |
class AggregateMetric(BaseMetric):
def __init__(self, func, method='jackknife', name=None, **kwargs):
allowed_methods = ('jackknife',)
if (method not in allowed_methods):
raise NotImplementedError(f'Provided method is not implemented yet. Currently only: {allowed_methods} are implemented... |
def save_as_json(filename, data):
with open(fix_filetype(filename, '.json'), 'w') as outfile:
json.dump(data, outfile) |
class MMFSubset(Subset):
def __init__(self, dataset, indices):
super().__init__(dataset, indices)
self._dir_representation = dir(self)
def __getattr__(self, name):
if (('_dir_representation' in self.__dict__) and (name in self._dir_representation)):
return getattr(self, name)... |
def create_key_pair():
key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())
return key |
def mobilecrnn_v1(inputdim=64, outputdim=527, pretrained=True):
model = MobileCRNN(inputdim, outputdim)
if pretrained:
state = torch.load((Path(__file__).parent / 'mobilecrnn_v1.pth'))
model.load_state_dict(state, strict=False)
return model |
class MLPDropout(object):
def __init__(self, rng, input, layer_sizes, dropout_rates, activations, use_bias=True):
self.weight_matrix_sizes = zip(layer_sizes, layer_sizes[1:])
self.layers = []
self.dropout_layers = []
self.activations = activations
next_layer_input = input
... |
class resnetv1(Network):
def __init__(self, num_layers=50):
Network.__init__(self)
self._feat_stride = [16]
self._feat_compress = [(1.0 / float(self._feat_stride[0]))]
self._num_layers = num_layers
self._net_conv_channels = 1024
self._fc7_channels = 2048
def _crop... |
_model_architecture('s2t_transformer', 's2t_transformer_sp')
def s2t_transformer_sp(args):
args.encoder_layers = getattr(args, 'encoder_layers', 16)
s2t_transformer_s(args) |
class CheckCommand(Command):
usage = '\n %prog [options]'
def run(self, options, args):
(package_set, parsing_probs) = create_package_set_from_installed()
(missing, conflicting) = check_package_set(package_set)
for project_name in missing:
version = package_set[project_n... |
def extract_gold_corefs(document):
gold_links = defaultdict(list)
gold_mentions = set([coref['span'] for coref in document.corefs])
total_mentions = len(gold_mentions)
for coref_entry in document.corefs:
(label, span_idx) = (coref_entry['label'], coref_entry['span'])
gold_links[label].ap... |
class AEGenerator(object):
def __init__(self, segan):
self.segan = segan
def __call__(self, noisy_w, is_ref, spk=None, z_on=True, do_prelu=False):
segan = self.segan
def make_z(shape, mean=0.0, std=1.0, name='z'):
if is_ref:
with tf.variable_scope(name) as sco... |
def int_var_cuda(x, requires_grad=False):
return Variable(x, requires_grad=requires_grad).long().cuda() |
def test_identities2():
x = np.array([(- 99.5), (- 9.5), (- 0.5), 0.5, 9.5, 99.5])
y = x.copy()
(x, y) = np.meshgrid(x, y)
z = (x + (1j * y)).flatten()
dataset = np.vstack((z, (np.log(z) + loggamma(z)))).T
def f(z):
return loggamma((z + 1))
FuncData(f, dataset, 0, 1, rtol=1e-14, atol... |
def register_Ns3TcpWestwood_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::TcpWestwood const &', 'sock')])
cls.add_method('Fork', 'ns3::Ptr< ns3::TcpCongestionOps >', [], is_virtual=True)
cls.add_method('GetSsThresh', 'uint32_t', [param('ns3::Ptr< ns3::TcpSocketState... |
def evaluate(model, data):
model.eval()
with torch.no_grad():
logits = model(data)
outs = {}
for key in ['train', 'val', 'test']:
mask = data['{}_mask'.format(key)]
loss = F.nll_loss(logits[mask], data.y[mask]).item()
pred = logits[mask].max(1)[1]
acc = (pred.eq(d... |
def parse_args():
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--prot_file', '-p', required=True, help='input protein file (pdb)')
parser.add_argument('--model_path', '-mp', required=True, help='directory of models')
parser.add_argument('-... |
class ConditionedBatchNorm2d(Module):
def __init__(self, num_features, cond_features, *args, **kwargs):
super(ConditionedBatchNorm2d, self).__init__()
self.cond_features = cond_features
self.bn = BatchNorm2d(num_features, *args, affine=False, **kwargs)
self.mlp_gamma = Sequential(Lin... |
class SubPolicy(object):
def __init__(self, p1, operation1, magnitude_idx1, p2, operation2, magnitude_idx2, fillcolor=(128, 128, 128)):
ranges = {'shearX': np.linspace(0, 0.3, 10), 'shearY': np.linspace(0, 0.3, 10), 'translateX': np.linspace(0, (150 / 331), 10), 'translateY': np.linspace(0, (150 / 331), 10)... |
def test_input_is_not_empty_list():
with pytest.raises(ValueError, match='Empty list was given as input, list should not be empty!'):
manager_test.add_solution([], model_test) |
class InceptionV1Test(tf.test.TestCase):
def testBuildClassificationNetwork(self):
batch_size = 5
(height, width) = (224, 224)
num_classes = 1000
inputs = tf.random_uniform((batch_size, height, width, 3))
(logits, end_points) = inception.inception_v1(inputs, num_classes)
... |
def log_specific_params(scope=None):
logging.info(('=' * 30))
scope = (scope or tf.get_variable_scope().name)
logging.info('In {}:'.format(scope))
tvars = tf.trainable_variables(scope)
all_params_num = 0
for elem in tvars:
params_num = 1
for l in elem.get_shape().as_list():
... |
class AbstractLabelledClonableTree(AbstractLabelledTree, AbstractClonableTree):
def set_root_label(self, label):
self._require_mutable()
self._label = label
def set_label(self, path, label):
self._require_mutable()
path = tuple(path)
if (path == ()):
self._lab... |
def divide_by_square_root(data, scale):
output = np.copy(data)
num_examples = len(scale)
assert (num_examples == data.shape[0])
assert (len(data.shape) == 2)
for i in range(0, num_examples):
if (scale[i] > 0):
output[i] = np.multiply(data[i], (1 / math.sqrt(scale[i])))
return... |
_grad()
def init_prompt(prompt, pipeline):
uncond_input = pipeline.tokenizer([''], padding='max_length', max_length=pipeline.tokenizer.model_max_length, return_tensors='pt')
uncond_embeddings = pipeline.text_encoder(uncond_input.input_ids.to(pipeline.device))[0]
text_input = pipeline.tokenizer([prompt], pad... |
def bi_sru_recurrent_network(rep_tensor, rep_mask, is_train=None, keep_prob=1.0, wd=0.0, scope=None):
(bs, sl, vec) = (tf.shape(rep_tensor)[0], tf.shape(rep_tensor)[1], tf.shape(rep_tensor)[2])
ivec = rep_tensor.get_shape().as_list()[2]
with tf.variable_scope((scope or 'bi_sru_recurrent_network')):
... |
def idx2word(idx, i2w, pad_idx):
sent_str = ([str()] * len(idx))
for (i, sent) in enumerate(idx):
for word_id in sent:
if (word_id == pad_idx):
break
sent_str[i] += (i2w[str(word_id.item())] + ' ')
sent_str[i] = sent_str[i].strip()
return sent_str |
def test_exists():
board = make_test_boad()
assert _exists(board, 19)
assert _exists(board, 20)
assert (not _exists(board, 4))
board = _flip_board(board)
assert _exists(board, 19)
assert _exists(board, 20)
assert (not _exists(board, 2)) |
def _synth_regression_sparse_dataset(n_samples=10000, n_features=10000, density=0.01, dtype=np.float32):
X = sp.random(m=n_samples, n=n_features, density=density, format='csr', random_state=0)
X.data = np.random.RandomState(0).randn(X.getnnz())
X = X.astype(dtype, copy=False)
coefs = sp.random(m=n_featu... |
def is_prod_appengine():
return (('APPENGINE_RUNTIME' in os.environ) and ('Google App Engine/' in os.environ['SERVER_SOFTWARE']) and (not is_prod_appengine_mvms())) |
def filter_glove_embedding(word_dict, glove_path):
vectors = np.zeros(shape=[len(word_dict), 300], dtype=np.float32)
with codecs.open(glove_path, mode='r', encoding='utf-8') as f:
for line in tqdm(f, total=2196018, desc='load glove embeddings'):
line = line.lstrip().rstrip().split(' ')
... |
def build_network(config):
implemented_networks = 'merlion'
assert (config.net_name in implemented_networks)
net = None
if (config.net_name == 'merlion'):
net = Merlion_MLP(config)
return net |
def _l2_project(next_distr_v, rewards_v, dones_mask_t, gamma, delta_z, n_atoms, v_min, v_max):
print('next_distr_v', next_distr_v.shape)
print('rewards_v', rewards_v.shape)
print('dones_mask_t', dones_mask_t.shape)
print('delta_z', delta_z.shape)
next_distr = next_distr_v.data.cpu().numpy()
rewa... |
_grad()
def run(selected_batch_, config, model, autoencoder, text_encoder, diffusion, condition_null_generator_dict, idx, NULL_CONDITION, SAVE_NAME, seed):
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
starting_noise = torch.randn(1, 4, 64, 64).to(device)
selected_batch = deepcopy(selected_batch_... |
def _find_c_source(base_path):
file_exists = os.path.exists
for ext in C_FILE_EXTENSIONS:
file_name = (base_path + ext)
if file_exists(file_name):
return file_name
return None |
def to_membership_vector(partition):
return {member: partition_id for (partition_id, members) in enumerate(partition) for member in members} |
class Blip2Processor(ProcessorMixin):
attributes = ['image_processor', 'tokenizer']
image_processor_class = 'BlipImageProcessor'
tokenizer_class = 'AutoTokenizer'
def __init__(self, image_processor, tokenizer):
tokenizer.return_token_type_ids = False
super().__init__(image_processor, tok... |
class _ColorfulFormatter(logging.Formatter):
def __init__(self, *args, **kwargs):
self._root_name = (kwargs.pop('root_name') + '.')
self._abbrev_name = kwargs.pop('abbrev_name', '')
if len(self._abbrev_name):
self._abbrev_name = (self._abbrev_name + '.')
super(_ColorfulFo... |
def linearity_cutoff_test(fluorescence_counts, prediction_counts, start_threshold=500, increment=1, p_cutoff=1e-05, n_neighbors=5):
for test_threshold in range(start_threshold, int(nc_flat.max()), increment):
below_test_threshold = (fluorescence_counts < test_threshold)
y = fluorescence_counts[below... |
def rgb2ycbcr(img, y_only=False):
img_type = img.dtype
img = _convert_input_type_range(img)
if y_only:
out_img = (np.dot(img, [65.481, 128.553, 24.966]) + 16.0)
else:
out_img = (np.matmul(img, [[65.481, (- 37.797), 112.0], [128.553, (- 74.203), (- 93.786)], [24.966, 112.0, (- 18.214)]]) ... |
def _find_python_module_path(module):
proc = os.popen(('python -c "import %s;print(%s.__path__[0])"' % (module, module)))
output = proc.readline()
return output.strip() |
def create_pipeline_configuration(DEBUG=False, batch_size=4):
config = {'batch_dim': 0, 'depth': 10000, 'basic_blocks': (T5LayerNorm, CrossEntropyLoss, T5Block, Dropout, StatelessEmbedding, Linear), 'model_inputs': {'attention_mask': {'shape': torch.Size([4, 1, 1, 512]), 'dtype': torch.float32, 'is_batched': True, ... |
def test_shortest_path():
dist_matrix = generate_graph(20)
dist_matrix[(dist_matrix != 0)] = 1
for directed in (True, False):
if (not directed):
dist_matrix = np.minimum(dist_matrix, dist_matrix.T)
graph_py = floyd_warshall_slow(dist_matrix.copy(), directed)
for i in rang... |
def fused_batch_normalization_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, axes=(1,), decay_rate=0.9, eps=1e-05, batch_stat=True, nonlinearity='relu'):
if (nonlinearity not in ['', 'relu']):
raise ValueError("nonlinearity must be either '' or 'relu'.")
ctx = nn.get_current_context... |
def get_combined_args(parser: ArgumentParser):
cmdlne_string = sys.argv[1:]
cfgfile_string = 'Namespace()'
args_cmdline = parser.parse_args(cmdlne_string)
try:
cfgfilepath = os.path.join(args_cmdline.model_path, 'cfg_args')
print('Looking for config file in', cfgfilepath)
with op... |
class JoinFeature(Feature):
def __init__(self, name, features, spkg=None, url=None, description=None, type=None, **kwds):
if (spkg is None):
spkgs = set((f.spkg for f in features if f.spkg))
if (len(spkgs) > 1):
raise ValueError('given features have more than one spkg... |
class ComplexMultiply(Benchmark):
def __init__(self, bits_prec, times):
self.__bits_prec = bits_prec
self.__times = times
self.repr_str = ('List of multiplies of two complex numbers with %s bits of precision %s times' % (self.__bits_prec, self.__times))
def sage(self):
CC = Compl... |
def dendrogram_coords(leaf_positions, partition_tree):
xout = []
yout = []
_dendrogram_coords_rec((partition_tree.shape[0] - 1), leaf_positions, partition_tree, xout, yout)
return (np.array(xout), np.array(yout)) |
class Solver(object):
def __init__(self, data, models, optimizers, args):
self.tr_loader = data['tr_loader']
self.cv_loader = data['cv_loader']
self.tt_loader = data['tt_loader']
self.args = args
self.adversarial_mode = (('adversarial' in args.experiment) and args.experiment.... |
def bruhat_lequal(p1, p2):
n1 = len(p1)
if (n1 == 0):
return True
if ((p1[0] > p2[0]) or (p1[(n1 - 1)] < p2[(n1 - 1)])):
return False
for i in range(n1):
c = 0
for j in range(n1):
if (p2[j] > (i + 1)):
c += 1
if (p1[j] > (i + 1)):
... |
def prepare_fx(graph_module, qconfig_dict, inplace=False):
return _prepare_fx(graph_module, qconfig_dict, inplace, is_dynamic_quant=False) |
class CustomFactorGenerationExampleCodegenTest(TestCase, SymforceTestCaseMixin):
_only
def test_generate_factors(self) -> None:
output_dir = self.make_output_dir(BASE_DIRNAME)
generate_factors.generate(output_dir=output_dir)
self.compare_or_update_directory(actual_dir=output_dir, expecte... |
(scope='module')
def source_1bin_shapesys():
with open('validation/data/1bin_example1.json', encoding='utf-8') as read_json:
return json.load(read_json) |
def split_s3_path(url):
parsed = urlparse(url)
if ((not parsed.netloc) or (not parsed.path)):
raise ValueError('bad s3 path {}'.format(url))
bucket_name = parsed.netloc
s3_path = parsed.path
if s3_path.startswith('/'):
s3_path = s3_path[1:]
return (bucket_name, s3_path) |
def execute_graph(model: nn.Module, graph: Graph, model_args=(), model_kwargs=None, pre_hook: Optional[PreHook]=None, post_hook: Optional[PostHook]=None, enforce_out_of_place=True):
if (model_kwargs is None):
model_kwargs = dict()
if (not isinstance(model_args, tuple)):
model_args = (model_args,... |
class BleuMetricSpec(TextMetricSpec):
def __init__(self, params):
super(BleuMetricSpec, self).__init__(params, 'bleu')
def metric_fn(self, hypotheses, references):
return bleu.moses_multi_bleu(hypotheses, references, lowercase=False) |
def discriminator(images, num_classes, bottleneck_size=512, keep_prob=1.0, phase_train=True, weight_decay=0.0, reuse=None, scope='Discriminator'):
with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), activation_fn=leaky_relu, normalizer_fn=None, normalizer_... |
class BlockReference(object):
def __init__(self, name, context, stack, depth):
self.name = name
self._context = context
self._stack = stack
self._depth = depth
def super(self):
if ((self._depth + 1) >= len(self._stack)):
return self._context.environment.undefi... |
class TimeFeature(ABC):
def __init__(self, normalise: bool, a: float, b: float):
self.normalise = normalise
self.a = a
self.b = b
def __call__(self, idx: pd.DatetimeIndex) -> np.ndarray:
...
def _max_val(self) -> float:
...
def max_val(self) -> float:
retu... |
def _possible_normalizers(E, SA):
if E.has_cm():
raise ValueError('The curve E should not have CM.')
E = _over_numberfield(E)
K = E.base_field()
SA = [K.ideal(I.gens()) for I in SA]
selmer_gens = K.selmer_generators(SA, 2)
if (not selmer_gens):
return []
V = VectorSpace(GF(2)... |
class MyConcatDataset(ConcatDataset):
def __getattr__(self, k):
return getattr(self.datasets[0], k) |
def get_default_quantization_config_options() -> QuantizationConfigOptions:
return get_current_tp_model().default_qco |
class InMemoryDatasetProvider(td.InMemoryDataset):
def __init__(self, dataset):
super().__init__()
self.data_list = list(dataset)
self._num_classes = dataset.num_classes
self._num_features = dataset.num_features
self._to_sparse = ToSparseTensor(remove_edge_index=True, fill_ca... |
def rand_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, low=0, high=1, shape=[], seed=(- 1)):
return ([None] * (len(grad_inputs) + len(inputs))) |
def filter_formulas(formulas, criteria=None):
if (criteria is None):
criteria = CRITERIA
out = []
for formula in formulas:
if (not (formula.signature.id in criteria)):
out.append(formula)
return out |
def GetNodeEcc_PDirNet(Graph, NId, IsDir=False):
return _snap.GetNodeEcc_PDirNet(Graph, NId, IsDir) |
.lower_builtin('end_list', ArrayBuilderType)
def lower_endlist(context, builder, sig, args):
(arraybuildertype,) = sig.args
(arraybuilderval,) = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
call(context, builder, libawkward.ArrayBuilder_endlist, (proxyin.rawptr,))
r... |
def make_agent(obs_spec, action_spec, cfg):
cfg.obs_shape = obs_spec[cfg.obs_type].shape
try:
cfg.action_shape = action_spec.shape
except:
pass
return hydra.utils.instantiate(cfg) |
.parametrize('ctx, func_name', ctxs)
.parametrize('seed', [100])
.parametrize('num_layers', [1, 2])
.parametrize('dropout', [0.0])
.parametrize('bidirectional', [True, False])
.parametrize('training', [True])
.parametrize('seq_len', [2, 5])
.parametrize('batch_size', [3])
.parametrize('input_size', [2])
.parametrize('h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.