code stringlengths 101 5.91M |
|---|
def read_type_file(type_file):
all_types = set()
for line in type_file:
all_types.add(''.join(line.split()).lower())
return all_types |
def _cast_to_type(data, dtype):
if isinstance(data, pd.Series):
data = data.apply(dtype)
elif isinstance(data, (np.ndarray, list)):
data = np.array([dtype(value) for value in data])
else:
data = dtype(data)
return data |
def postprocess_args(args):
if ((args['retag_method'] is None) and ('lang' in args) and (args['lang'] in RETAG_METHOD)):
args['retag_method'] = RETAG_METHOD[args['lang']]
if (args['retag_method'] is None):
args['retag_method'] = 'xpos'
if (args['retag_method'] == 'xpos'):
args['retag... |
def test_embedding(device):
from speechbrain.nnet.embedding import Embedding
embedding_dim = 39
blank_id = 39
size_dict = 40
emb = Embedding(num_embeddings=size_dict, consider_as_one_hot=True, blank_id=blank_id).to(device)
inputs = torch.Tensor([10, 5, 2, 0, 39]).to(device).long()
output = e... |
def mobilenet_v1(nc, pretrained=False, progress=True, **kwargs):
net = MobileNetV1ImageNet(nc, **kwargs)
if pretrained:
state_dict = torch.load('./models/mobilenet_v1_imagenet.pth', map_location='cpu')
state_dict = state_dict.get('state_dict')
def rename(x):
return x.replace(... |
def get_data_loaders(cfg, args):
(tr_dataset, te_dataset) = get_datasets(cfg, args)
train_loader = data.DataLoader(dataset=tr_dataset, batch_size=cfg.train.batch_size, shuffle=True, num_workers=cfg.num_workers, drop_last=True, worker_init_fn=init_np_seed)
test_loader = data.DataLoader(dataset=te_dataset, ba... |
def insert(conn, test_session):
conn = sqlite3.connect(conn)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
with conn:
if (test_session.type == 'DialogFlow_CX'):
cursor.execute('INSERT INTO bots \n (name, type, descript, status, stage, dev, eval, end_po... |
class ArkReader(object):
def __init__(self, scp_path):
self.scp_position = 0
fin = open(scp_path, 'r')
self.utt_ids = []
self.scp_data = []
line = fin.readline()
while ((line != '') and (line != None)):
(utt_id, path_pos) = line.replace('\n', '').split(' '... |
def test_f1_macro_1d_np_array():
y_true = np.array([1, 2, 3, 4])
y_pred = np.array([1, 2, 3, 4])
assert (1 == f1(y_true, y_pred, 'macro')) |
class SolverCallbackObj(ctypes.c_void_p):
def __init__(self, solver):
self._as_parameter_ = solver
def from_param(obj):
return obj |
def squeeze(input, downscale_factor=2):
(batch_size, in_channels, in_height, in_width) = input.shape
out_channels = (in_channels * (downscale_factor ** 2))
out_height = (in_height // downscale_factor)
out_width = (in_width // downscale_factor)
input_view = input.reshape(batch_size, in_channels, out_... |
class TestTupleConstraintTag():
def instance(self):
return TupleConstraintTag()
def test_no_matching_tuples(self, instance):
target = [['a', 'b'], ['c', 'd']]
prediction = [['x', 'y'], ['z', 'w']]
result = instance.evaluate_single_test_metric(target, prediction)
assert (r... |
def init(variant, ckpt, base='', prefix='', mode=DATASET_MODES.val):
(runner, ckpt_path) = make_runner(variant, ckpt, base, prefix)
return init_by_ckpt(ckpt_path, mode) |
class SLinear(nn.Module):
def __init__(self, in_features, out_features, Q_l, bias=True):
super(SLinear, self).__init__()
self.Q_l = Q_l
self.qlevels = Q_l.size(0)
self.linear = nn.Linear(in_features, (out_features * self.qlevels), bias=bias)
def ucollapse(self, x):
x = x.... |
def normal_kl(mean1, logvar1, mean2, logvar2):
tensor = None
for obj in (mean1, logvar1, mean2, logvar2):
if isinstance(obj, torch.Tensor):
tensor = obj
break
assert (tensor is not None), 'at least one argument must be a Tensor'
(logvar1, logvar2) = [(x if isinstance(x, t... |
class TFMobileBertForNextSentencePrediction():
def __init__(self, *args, **kwargs):
requires_tf(self) |
def check_valid_prior(filename):
from Util import load_txt_vector
v = load_txt_vector(filename)
v = numpy.array(v)
assert (v.ndim == 1)
assert all((v < 0.0)), 'log space assumed'
v = numpy.exp(v)
tot = numpy.sum(v)
assert numpy.isclose(tot, 1.0, atol=0.0001) |
_wrapper
def evaluate(cfg: DictConfig) -> Tuple[(dict, dict)]:
assert cfg.ckpt_path
log.info(f'Instantiating datamodule <{cfg.datamodule._target_}>')
datamodule: LightningDataModule = hydra.utils.instantiate(cfg.datamodule)
log.info(f'Instantiating model <{cfg.model._target_}>')
model: LightningModu... |
def test_error_handling():
def func(a, b):
return (a + b)
deps = wn.causal_graphs.trace_dependencies(func, (1.0, 0.2))
assert (set(deps[0]) == set([0, 1]))
deps = wn.causal_graphs.trace_dependencies(func, (1.0, 2))
assert (set(deps[0]) == set([0, 1]))
a = np.random.rand(3, 3).astype(np.f... |
def my_collate_bert(batch):
(input_ids, word_indexer, input_aspect_ids, aspect_indexer, input_cat_ids, segment_ids, dep_tag_ids, pos_class, text_len, aspect_len, sentiment, dep_rel_ids, dep_heads, aspect_positions, dep_dir_ids) = zip(*batch)
text_len = torch.tensor(text_len)
aspect_len = torch.tensor(aspect... |
def train(train_data, val_data, pro_num, timestamp, timespan, model, optimizer, logger, saver, num_epochs, batch_size, grad_clip):
criterion = nn.BCEWithLogitsLoss()
step = 0
metrics = Metrics()
corr_data = get_corr_data(pro_num)
for epoch in range(num_epochs):
train_batches = prepare_batche... |
class Vimeo90KDataset(data.Dataset):
def __init__(self, opt):
super(Vimeo90KDataset, self).__init__()
self.opt = opt
(self.gt_root, self.lq_root) = (Path(opt['dataroot_gt']), Path(opt['dataroot_lq']))
with open(opt['meta_info_file'], 'r') as fin:
self.keys = [line.split('... |
def Contrast(img, v):
assert (0.1 <= v <= 1.9)
return PIL.ImageEnhance.Contrast(img).enhance(v) |
def restore_source_model(saved_pb_name, grad_dict=None):
print('restoring', saved_pb_name)
with open((saved_pb_name + '.pickle'), 'rb') as f:
info = pickle.load(f)
print(info)
sess = K.get_session()
print('restoring frozen graph def')
with open((saved_pb_name + '.pb'), 'rb') as f:
... |
def line_search_wolfe1(f, fprime, xk, pk, gfk=None, old_fval=None, old_old_fval=None, args=(), c1=0.0001, c2=0.9, amax=50, amin=1e-08, xtol=1e-14):
if (gfk is None):
gfk = fprime(xk)
if isinstance(fprime, tuple):
eps = fprime[1]
fprime = fprime[0]
newargs = ((f, eps) + args)
... |
def test_no_abstract_class():
cluster = generate_test_cluster('tests.fixtures.cluster.abstract')
assert (len(cluster.accessible_objects_under_test) == 1)
assert (len(cluster.generators) == 3)
assert (len(cluster.modifiers) == 1) |
def _iter_module_files():
for module in list(sys.modules.values()):
if (module is None):
continue
filename = getattr(module, '__file__', None)
if filename:
if (os.path.isdir(filename) and os.path.exists(os.path.join(filename, '__init__.py'))):
filename... |
class DeterministicMLPPolicy(Policy, LayersPowered, Serializable):
def __init__(self, name, env_spec, hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.relu, output_nonlinearity=tf.nn.tanh, prob_network=None, bn=False):
Serializable.quick_init(self, locals())
with tf.variable_scope(name):
... |
def cb_sign2map(a, var, index=None):
ret = {'varname': a}
ret['varname_i'] = ret['varname']
ret['ctype'] = getctype(var)
if (ret['ctype'] in c2capi_map):
ret['atype'] = c2capi_map[ret['ctype']]
if (ret['ctype'] in cformat_map):
ret['showvalueformat'] = ('%s' % cformat_map[ret['ctype'... |
class Subsets_s(Parent):
element_class = Set_object_enumerated
def __init__(self, s):
Parent.__init__(self, category=EnumeratedSets().Finite())
if (s not in EnumeratedSets()):
from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
L = list(uniq(s))
s ... |
(Output('outlet-gender-heatmap', 'figure'), [Input('topic-data', 'data')])
def update_gender_heatmap(data):
if (data is None):
return {'data': []}
else:
(dff, y_labels) = construct_outlet_gender_DF(data)
width = ((35 * len(dff.columns.tolist())) + 467)
return {'data': [{'type': '... |
def dot(x, y, sparse=False):
if sparse:
return tf.sparse_tensor_dense_matmul(x, y)
else:
return tf.matmul(x, y) |
class FunctionalLinearReluModel(nn.Module):
def __init__(self):
super().__init__()
self.linear = FunctionalLinear()
def forward(self, x):
x = self.linear(x)
x = F.relu(x)
return x |
class LazyFrames(object):
def __init__(self, frames):
self._frames = frames
self._out = None
def _force(self):
if (self._out is None):
self._out = np.concatenate(self._frames, axis=(- 1))
self._frames = None
return self._out
def __array__(self, dtype=N... |
class Attention_Enhanced_TPS(nn.Module):
def __init__(self, rectified_img_size, point_size):
super().__init__()
self.eps = 1e-06
self.thela = 0.5
self.point_size = point_size
self.point_y = point_size[0]
self.point_x = point_size[1]
self.num_fiducial = (self.p... |
_utils.test(arch=ti.cpu)
def test_init_bad_arg():
with pytest.raises(KeyError):
ti.init(_test_mode=True, debug=True, foo_bar=233) |
class SeedingConfiguration():
seed: int = time.time_ns()
constant_seeding: bool = True
initial_population_seeding: bool = False
initial_population_data: str = ''
seeded_testcases_reuse_probability: float = 0.9
initial_population_mutations: int = 0
dynamic_constant_seeding: bool = True
se... |
def make_spline_knot_matrix(n, order, mode='mirror'):
knot_values = get_spline_knot_values(order)
matrix = np.zeros((n, n))
for (diag, knot_value) in enumerate(knot_values):
indices = np.arange(diag, n)
if (diag == 0):
matrix[(indices, indices)] = knot_value
else:
... |
def layer_config_kwargs(kwargs):
return set_layer_config(scriptable=kwargs.pop('scriptable', None), exportable=kwargs.pop('exportable', None), no_jit=kwargs.pop('no_jit', None)) |
def test_write_to_io():
doc = CoNLL.conll2doc(input_str=ENGLISH_SAMPLE)
output = io.StringIO()
CoNLL.write_doc2conll(doc, output)
output_value = output.getvalue()
assert output_value.endswith('\n\n')
assert (output_value.strip() == ENGLISH_SAMPLE) |
def get_random_uniform_cluster(clustering, nclasses, ntargets_per_class):
views = sorted(list(clustering.keys()))
view_idx_map = {v: i for (i, v) in enumerate(views)}
ncentroids = np.array([clustering[view].ncentroids for (i, view) in enumerate(views)])
argmax_view = ncentroids.argmax()
ncentroids =... |
def register_Ns3MmwaveSpectrumSignalParameters_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::mmwaveSpectrumSignalParameters const &', 'p')])
cls.add_method('Copy', 'ns3::Ptr< ns3::SpectrumSignalParameters >', [], is_virtual=True)
cls.add_instance_attribute('packetBu... |
class ImageNet(ImageFolder):
WNIDS = ['n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n'... |
def decay_nuclides(shell_mass, initial_composition, epoch):
decay_model = Ejecta(shell_mass, initial_composition)
new_fractions = decay_model.decay(epoch)
return new_fractions |
def _make_sdfg_2(succeed: bool=True):
name = ('success' if succeed else 'failure')
sdfg = dace.SDFG(f'redundant_second_array_{name}')
sdfg.add_array('A', [20], dace.int32)
sdfg.add_transient('tmp', [7], dace.int32)
sdfg.add_view('A_0', [8], dace.int32)
sdfg.add_view('A_1', [7], dace.int32)
s... |
_grad()
def extract_feature_from_generator(model, inception, batch_size, n_sample, truncation=1.0):
torch.set_default_tensor_type('torch.cuda.FloatTensor')
n_batch = (n_sample // batch_size)
resid = (n_sample - (n_batch * batch_size))
batch_sizes = ([batch_size] * n_batch)
if (resid > 0):
ba... |
def prepare_images(image_paths):
images = []
labels = []
for image in tqdm(image_paths):
image_pixels = plt.imread(image)
image_pixels = cv2.resize(image_pixels, (224, 224))
image_pixels = (image_pixels / 255.0)
label = image.split('/')[2].split('_')[0]
images.append(... |
def get_linear_schedule_with_warmup(*args, **kwargs):
requires_backends(get_linear_schedule_with_warmup, ['torch']) |
class MobileDet(tf.keras.Model):
_MODEL_FN = {'mobiledet_cpu': mobiledet_cpu_backbone, 'mobiledet_gpu': mobiledet_gpu_backbone, 'mobiledet_edge_tpu': mobiledet_edgetpu_backbone, 'mobiledet_dsp': mobiledet_dsp_backbone}
def __init__(self, input_shape, model_name=None, multiplier=1.0, checkpoint=None, normalizati... |
class DiscriminatorMultiToSingleOutputStackedMixin():
def __init__(self, *args, return_feats_only_levels=None, **kwargs):
super().__init__(*args, **kwargs)
self.return_feats_only_levels = return_feats_only_levels
def forward(self, x):
out_feat_tuples = super().forward(x)
outs = [... |
_model
def ese_vovnet99b_iabn(pretrained=False, **kwargs):
norm_layer = get_norm_act_layer('iabn')
return _vovnet('ese_vovnet99b_iabn', pretrained=pretrained, norm_layer=norm_layer, **kwargs) |
def default_model_params():
params = dict()
params['img_height'] = 128
params['img_width'] = None
params['batch_size'] = 12
params['img_channels'] = 1
params['conv_blocks'] = 4
params['conv_filter_n'] = [32, 64, 128, 256]
params['conv_filter_size'] = [[3, 3], [3, 3], [3, 3], [3, 3]]
... |
class Experiment(object):
def compile(cls, name, exp, configurator):
action = exp.get('action')
description = exp.get('description')
desc = exp.get('desc')
if (action == 'profile'):
data_file = (exp.get('data_file') or (configurator.data_file + '.profiles'))
else:... |
.parametrize('inshape, kernel, divisor, outshape', [((2, 4, 10, 10), (3, 2), 1, (2, 4, 12, 11)), ((2, 4, 10, 10), (3, 2), 2, (2, 2, 12, 11))])
def test_parametric_function_2d(inshape, kernel, divisor, outshape):
base_axis = (len(inshape) - 3)
sample_channels = inshape[base_axis]
outmap_channels = (sample_ch... |
def check_loss_raises(Clf):
clf = Clf(loss='hinge', random_state=0)
assert_raises(ValueError, clf.fit, X, y) |
class TransformerLayer(Layer):
def __init__(self, units: int, activation: Activation=None, **kwargs):
self.units = units
self.activation = activation
super(TransformerLayer, self).__init__(**kwargs)
def transform(self, inputs: tf.Tensor) -> tf.Tensor:
raise NotImplementedError('N... |
def dur2str(ons):
if (ons < 62):
return ('r' + int2char(ons))
return ('R' + int2char((ons - 62))) |
class AnalyticTypeElement(LatticePosetElement):
def _repr_(self):
return self.analytic_name()
def _latex_(self):
from sage.misc.latex import latex
return latex(self.analytic_name())
def analytic_space_name(self):
name = ''
if (self.parent()('quasi') <= self):
... |
def test_named_record_int32():
t = RecordType([NumpyType('int32')], None, {'__record__': 'Name'})
assert (str(parser.parse(str(t))) == str(t)) |
class TensorProductFunctor(CovariantFunctorialConstruction):
_functor_name = 'tensor'
_functor_category = 'TensorProducts'
symbol = ' # '
unicode_symbol = f' {unicode_otimes} ' |
class SNetDS2BN_base_8(Network):
def setup(self):
print('2D SNet with 16 channel output')
base_filter = 8
self.feed('data').conv_bn(3, base_filter, 1, dilation_rate=1, center=True, scale=True, name='sconv0_0').conv_bn(3, (base_filter * 2), 1, dilation_rate=1, center=True, scale=True, name='s... |
def variance_scaling_(tensor, scale=1.0, mode='fan_in', distribution='normal'):
(fan_in, fan_out) = _calculate_fan_in_and_fan_out(tensor)
if (mode == 'fan_in'):
denom = fan_in
elif (mode == 'fan_out'):
denom = fan_out
elif (mode == 'fan_avg'):
denom = ((fan_in + fan_out) / 2)
... |
def test_UnmaskedArray_RecordArray_NumpyArray():
v2a = ak.contents.unmaskedarray.UnmaskedArray(ak.contents.recordarray.RecordArray([ak.contents.numpyarray.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3]))], ['nest']))
roundtrip(v2a)
array = ak.highlevel.Array(v2a)
memoryleak(array, swallow)
memoryleak(arra... |
def _seg_35():
return [(13274, 'M', u'pr'), (13275, 'M', u'sr'), (13276, 'M', u'sv'), (13277, 'M', u'wb'), (13278, 'M', u'vm'), (13279, 'M', u'am'), (13280, 'M', u'1'), (13281, 'M', u'2'), (13282, 'M', u'3'), (13283, 'M', u'4'), (13284, 'M', u'5'), (13285, 'M', u'6'), (13286, 'M', u'7'), (13287, 'M', u'8'), (13288,... |
class LatticePosets(Category):
_method
def super_categories(self):
return [Posets()]
Finite = LazyImport('sage.categories.finite_lattice_posets', 'FiniteLatticePosets')
class ParentMethods():
_method
def meet(self, x, y):
_method
def join(self, x, y): |
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 ResNet(nn.Module):
def __init__(self, depth, num_classes=1000, death_mode='linear', death_rate=0.5):
super(ResNet, self).__init__()
assert (((depth - 2) % 6) == 0), 'depth should be 6n+2'
n = ((depth - 2) // 6)
block = (Bottleneck if (depth >= 44) else BasicBlock)
nbloc... |
def convert_citylabelTo16label():
with open('./synthia2cityscapes_info.json', 'r') as f:
paramdic = json.load(f)
class_ind = paramdic['city2common']
city_gt_dir = '/data/ugui0/ksaito/D_A/image_citiscape/www.cityscapes-dataset.com/file-handling/gtFine'
split_list = ['train', 'test', 'val']
or... |
def format_mnist():
dir_path = os.path.dirname(os.path.realpath(__file__))
mnist_path = (Path(dir_path) / 'data/mnist')
try:
return np.load((mnist_path / 'mnist.npz'))
except Exception:
train_loader = torch.utils.data.DataLoader(datasets.MNIST(mnist_path, train=True, download=True, trans... |
class RRDBNet(nn.Module):
def __init__(self, in_nc, out_nc, nf, nb, gc=32):
super(RRDBNet, self).__init__()
RRDB_block_f = functools.partial(RRDB, nf=nf, gc=gc)
self.conv_first = nn.Conv2d(3, nf, 3, 1, 1, bias=True)
self.RRDB_trunk = mutil.make_layer(RRDB_block_f, nb)
self.tr... |
class BasicUnit(nn.Module):
def forward(self, x):
raise NotImplementedError
def unit_str(self):
raise NotImplementedError
def config(self):
raise NotImplementedError
def build_from_config(config):
raise NotImplementedError
def get_flops(self, x):
raise NotImpl... |
class StudentModelArguments():
student_name_or_path: Optional[str] = field(default='distilbert-base-uncased', metadata={'help': 'The NLI/zero-shot teacher model to be distilled.'}) |
def min_cycles(G, v):
pr = G.neighbors_in(v)
sp = G.shortest_paths(v)
return [sp[i] for i in pr if (i in sp)] |
class CDFCopy(spacepy.datamodel.SpaceData):
def __init__(self, cdf):
super(CDFCopy, self).__init__(((key, var.copy()) for (key, var) in cdf.items()), attrs=cdf.attrs.copy()) |
.operations('success')
def test_do_not_send_incomplete_report_file(file_report_handler, service, openapi3_schema_url):
context = mock.create_autospec(ExecutionContext)
for event in generate_events(openapi3_schema_url):
if isinstance(event, events.Finished):
file_report_handler.handle_event(c... |
def main():
assert (args.num_tasks == len(args.meta_datasets))
(minis, minis_test) = load_meta_dataset(args)
(model, cur_device) = model_builder._construct_model(args)
metalearner = Meta(args, model).to(cur_device)
step_number = min([len(mini) for mini in minis])
test_step_number = len(minis_tes... |
('/get_active_clients', methods=['GET'])
def get_active_clients():
combiner_id = request.args.get('combiner', None)
if (combiner_id is None):
return (jsonify({'success': False, 'message': 'Missing combiner id.'}), 400)
return api.get_active_clients(combiner_id) |
def test_hinsage_save_load(tmpdir):
G = example_hin_1({'A': 8, 'B': 4})
gen = HinSAGENodeGenerator(G, 1, [2, 2], 'A')
hs = HinSAGE(layer_sizes=[2, 2], generator=gen, normalize='none', activations=['relu', 'relu'])
test_utils.model_save_load(tmpdir, hs) |
def load_pretrained_component_from_model(component: Union[(FairseqEncoder, FairseqDecoder)], checkpoint: str):
if (not os.path.exists(checkpoint)):
raise IOError('Model file not found: {}'.format(checkpoint))
state = load_checkpoint_to_cpu(checkpoint)
if isinstance(component, FairseqEncoder):
... |
def _nanmin(X, axis=None):
(xp, _) = get_namespace(X)
if _is_numpy_namespace(xp):
return xp.asarray(numpy.nanmin(X, axis=axis))
else:
mask = xp.isnan(X)
X = xp.min(xp.where(mask, xp.asarray((+ xp.inf), device=device(X)), X), axis=axis)
mask = xp.all(mask, axis=axis)
i... |
def features_sparse():
return csr_matrix([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14], [15, 16]]) |
def knn_graph(x: torch.Tensor, k: int, batch: Optional[torch.Tensor]=None, loop: bool=False, flow: str='source_to_target', cosine: bool=False, num_workers: int=1, batch_size: Optional[int]=None) -> torch.Tensor:
assert (flow in ['source_to_target', 'target_to_source'])
edge_index = knn(x, x, (k if loop else (k ... |
def mwrank_console():
from sage.repl.rich_output.display_manager import get_display_manager
if (not get_display_manager().is_in_terminal()):
raise RuntimeError('Can use the console only in the terminal. Try %%mwrank magics instead.')
os.system('mwrank') |
_tf
class TFT5ModelTest(TFModelTesterMixin, unittest.TestCase):
is_encoder_decoder = True
all_model_classes = ((TFT5Model, TFT5WithLMHeadModel) if is_tf_available() else ())
class TFT5ModelTester(object):
def __init__(self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, ... |
def make_pass_decorator(object_type, ensure=False):
def decorator(f):
def new_func(*args, **kwargs):
ctx = get_current_context()
if ensure:
obj = ctx.ensure_object(object_type)
else:
obj = ctx.find_object(object_type)
if (obj is... |
def get_models_from_hist(hist_idx, hist, input_state, output_state, state_space, model_compile_dict):
model_dict = {}
for idx in hist_idx:
model_state_str = [hist.iloc[idx][('L%i' % (i + 1))] for i in range((hist.shape[1] - 5))]
model_dict[idx] = model_fn.build_sequential_model_from_string(model... |
(ignore_result=True)
def crawl_person_infos_not_in_seed_ids(uid):
if (not uid):
return
get_user_profile(uid) |
class BertIntermediate(nn.Module):
def __init__(self, config):
super(BertIntermediate, self).__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
self.intermediate_act_fn = (ACT2FN[config.hidden_act] if isinstance(config.hidden_act, str) else config.hidden_act)
... |
def check_slate_bandit_feedback(bandit_feedback: BanditFeedback, is_factorizable: bool=False):
pscore_columns: List[str] = []
pscore_candidate_columns = ['pscore_cascade', 'pscore', 'pscore_item_position']
for column in pscore_candidate_columns:
if ((column in bandit_feedback) and (bandit_feedback[c... |
def collate(batch):
batch = list(zip(*batch))
(topic_entity, question, answer, entity_range) = batch
topic_entity = torch.stack(topic_entity)
question = {k: torch.cat([q[k] for q in question], dim=0) for k in question[0]}
answer = torch.stack(answer)
entity_range = torch.stack(entity_range)
... |
def plot_distribution(counter):
import numpy as np
(labels, values) = zip(*counter.items())
indexes = np.arange(len(labels))
import seaborn as sns
sns.set(color_codes=True)
sns.distplot(values)
plt.show() |
class Vggish(nn.Module):
args = {'postprocess': False}
output_dims = 128
model_tag = {'name': 'VGGish', 'dataset': 'YouTube-8M'}
def __init__(self, args):
super().__init__()
torch.hub.set_dir(str(args.data.cache_dir))
self.model = torch.hub.load('harritaylor/torchvggish', 'vggish... |
class TestCloneNet(test_util.TestCase):
def testPartialClone(self):
params = core.Net('params')
p1 = params.ConstantFill([], ['p1'])
workspace.CreateNet(params)
workspace.RunNetOnce(params)
n = core.Net('original')
a1 = n.AddExternalInput('a1')
a2 = n.AddExter... |
class GeneralizedReedSolomonCode(AbstractLinearCode):
_registered_encoders = {}
_registered_decoders = {}
def __init__(self, evaluation_points, dimension, column_multipliers=None):
if column_multipliers:
if (len(evaluation_points) != len(column_multipliers)):
raise ValueE... |
def plot_ls_solution(ax, ls_rmsve, alg, sp):
lbl = f'{alg} $\lambda=$ {sp}'
x = np.arange(ls_rmsve.shape[0])
y = (ls_rmsve[(- 1)] * np.ones(ls_rmsve.shape[0]))
ax.plot(x, y, label=lbl, linewidth=1.0, color=ALG_COLORS[alg], linestyle=':') |
def test_fortranfiles_write():
for filename in iglob(path.join(DATA_PATH, 'fortran-*-*x*x*.dat')):
m = re.search('fortran-([^-]+)-(\\d+)x(\\d+)x(\\d+).dat', filename, re.I)
if (not m):
raise RuntimeError(("Couldn't match %s filename to regex" % filename))
dims = (int(m.group(2)),... |
_params({'scoring': [str, callable, None]}, prefer_skip_nested_validation=True)
def get_scorer(scoring):
if isinstance(scoring, str):
try:
scorer = copy.deepcopy(_SCORERS[scoring])
except KeyError:
raise ValueError(('%r is not a valid scoring value. Use sklearn.metrics.get_sc... |
class GANLoss(nn.Module):
def __init__(self, gan_type, real_label_val=1.0, fake_label_val=0.0):
super(GANLoss, self).__init__()
self.gan_type = gan_type.lower()
self.real_label_val = real_label_val
self.fake_label_val = fake_label_val
if ((self.gan_type == 'gan') or (self.gan... |
def build_bbh_fewshot_dataset(dataset_name, folder):
assert (dataset_name in ALL_BBH_TEMPLATES)
prompt_templates = ALL_BBH_TEMPLATES[dataset_name]
for (idx, prompt_template) in enumerate(prompt_templates):
print('Current prompt template: ', prompt_template)
template = Template(prompt_templat... |
def get_regularization(gptq_config: GradientPTQConfig, representative_data_gen: Callable) -> Callable:
if (gptq_config.rounding_type == RoundingType.SoftQuantizer):
num_batches = 0
for _ in representative_data_gen():
num_batches += 1
n_epochs = (GradientPTQConfigV2.from_v1(n_ptq_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.