code stringlengths 101 5.91M |
|---|
class TrainCommand(BaseTransformersCLICommand):
def register_subcommand(parser: ArgumentParser):
train_parser = parser.add_parser('train', help='CLI tool to train a model on a task.')
train_parser.add_argument('--train_data', type=str, required=True, help='path to train (and optionally evaluation) d... |
def compute_loss(predictions, labels, loss_wts={'malware': 1.0, 'count': 0.1, 'tags': 0.1}):
loss_dict = {'total': 0.0}
if ('malware' in labels):
malware_labels = labels['malware'].float().to(device)
malware_loss = F.binary_cross_entropy(predictions['malware'].reshape(malware_labels.shape), malw... |
class Engine(object):
def __init__(self, test_id=1, mass=1.0):
self.mass = mass
self.xy_limit = 1
self.action_limit = 0.2
self.pos = np.array([0.0, 0.0])
self.data_path = os.path.join('./tmp/data/test{}'.format(test_id))
if (not os.path.exists(self.data_path)):
... |
class GroupSampler(Sampler):
def __init__(self, dataset, samples_per_gpu=1):
assert hasattr(dataset, 'flag')
self.dataset = dataset
self.samples_per_gpu = samples_per_gpu
self.flag = dataset.flag.astype(np.int64)
self.group_sizes = np.bincount(self.flag)
self.num_samp... |
class BiFpn(nn.Module):
def __init__(self, config, feature_info):
super(BiFpn, self).__init__()
self.num_levels = config.num_levels
norm_layer = (config.norm_layer or nn.BatchNorm2d)
if config.norm_kwargs:
norm_layer = partial(norm_layer, **config.norm_kwargs)
act... |
def kl_binary(p_logit, q_logit):
if isinstance(p_logit, chainer.Variable):
xp = cuda.get_array_module(p_logit.data)
else:
xp = cuda.get_array_module(p_logit)
p_logit = F.concat([p_logit, xp.zeros(p_logit.shape, xp.float32)], 1)
q_logit = F.concat([q_logit, xp.zeros(q_logit.shape, xp.floa... |
def export_model_run_task(run_dir: str, score: Dict[(str, any)]):
task_name = score['task']
task = TASKS[task_name]()
filename = (score['id'] + '.txt')
pred_path = None
script_dir = os.path.dirname(os.path.realpath(__file__))
checkpoints_dir = os.path.join(script_dir, os.path.pardir, 'checkpoint... |
def get_features_from_audio(audio, tuning_offset, visualize=False):
f_pitch = audio_to_pitch_features(f_audio=audio, Fs=Fs, tuning_offset=tuning_offset, feature_rate=feature_rate, verbose=visualize)
f_chroma = pitch_to_chroma(f_pitch=f_pitch)
f_chroma_quantized = quantize_chroma(f_chroma=f_chroma)
f_pit... |
def test_minimum_spanning_tree():
graph = [[0, 1, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 0, 8, 5], [0, 0, 8, 0, 1], [0, 0, 5, 1, 0]]
graph = np.asarray(graph)
expected = [[0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 5], [0, 0, 0, 0, 1], [0, 0, 0, 0, 0]]
expected = np.asarray(expected)
csgraph = csr_mat... |
def pivot_dataframe_batch(list_files, settings):
num_elem = len(list_files)
num_chunks = ((num_elem // 10) + 1)
list_chunks = np.array_split(np.arange(num_elem), num_chunks)
if (not settings.debug):
max_workers = (multiprocessing.cpu_count() - 2)
for chunk_idx in tqdm(list_chunks, desc='... |
def test():
model.eval()
criterion = nn.CrossEntropyLoss(size_average=False)
test_loss = 0
correct = 0
for (batch_idx, (data, target)) in enumerate(test_loader):
(data, target) = (data.cuda(GPU_ID), target.cuda(GPU_ID))
(data, target) = (Variable(data, volatile=True), Variable(target... |
def freeze_bn(m):
classname = m.__class__.__name__
if (classname.find('BatchNorm') != (- 1)):
m.eval()
freeze_params(m) |
def BatchNorm(nf, ndim=2, norm_type=NormType.Batch, **kwargs):
return _get_norm('BatchNorm', nf, ndim, zero=(norm_type == NormType.BatchZero), **kwargs) |
class RequestField(object):
def __init__(self, name, data, filename=None, headers=None):
self._name = name
self._filename = filename
self.data = data
self.headers = {}
if headers:
self.headers = dict(headers)
def from_tuples(cls, fieldname, value):
if ... |
class ReconciliationProblem2Test(AbstractTest):
def __init__(self):
super().__init__()
self.problem = ReconciliationProblem2()
def name(self):
return 'recon2'
def run(self):
ncf = NcfEpi.new_total_flow(4)
hc = HardCodedPartitioning(partition_vector=[0, 0, 1, 1])
... |
def _include_file_data(login, record):
if ('files' not in record):
if ('files' in record.get('links', {})):
url = record['links']['files']
elif ('id' in record):
url = (login.base_url + 'api/deposit/depositions/{0}/files'.format(record['id']))
else:
return... |
def elliptic_curve():
EllipticCurveTraces(100000).run()
EllipticCurveTraces(500000).run()
Divpoly(59).run()
EllipticCurvePointMul(1000).run()
EllipticCurvePointMul(2000).run()
EllipticCurvePointMul(2500).run()
EllipticCurveMW([5, 6, 7, 8, 9]).run()
EllipticCurveMW([50, 6, 7, 8, 9]).run()... |
class MAP_L21NormPrior(Prior):
def __init__(self, size, gamma=1, axis=0, isotropic=True):
assert ((type(size) == tuple) and (len(size) > 1)), 'size must be a tuple of length > 1'
self.size = size
self.gamma = gamma
self.axis = axis
self.isotropic = isotropic
self.repr... |
def train(arg1, arg2=None, arg3=None):
(prob, param) = (None, None)
if isinstance(arg1, (list, tuple)):
assert isinstance(arg2, (list, tuple))
(y, x, options) = (arg1, arg2, arg3)
prob = problem(y, x)
param = parameter(options)
elif isinstance(arg1, problem):
prob = a... |
def register_Ns3HashFunctionFnv1a_methods(root_module, cls):
cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')])
cls.add_constructor([])
cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True)
cls.add_method('GetHa... |
class TrivialTriangleFactory():
def triangle(self, a, b, c, color=None):
return [a, b, c]
def smooth_triangle(self, a, b, c, da, db, dc, color=None):
return [a, b, c] |
def cmpe_se_3x3_resnet164(use_1x1=True, **kwargs):
return get_cmpe_se_resnet(version=3, num_layers=164, **kwargs) |
class CscTrainingModel(BaseTrainingEngine, ABC):
def __init__(self, cfg, *args, **kwargs):
super().__init__(cfg, *args, **kwargs)
self.w = cfg.MODEL.HYPER_PARAMS[0]
def training_step(self, batch, batch_idx):
(ori_text, cor_text, det_labels) = batch
outputs = self.forward(ori_text... |
class PAPIUtils(object):
def available_counters() -> Dict[(str, int)]:
if (os.name == 'nt'):
return {}
try:
p = subprocess.Popen("papi_avail -d -a | grep -E '^PAPI_'", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
(stdout, ... |
def can_move(movable):
return (can_move_x(movable) or can_move_y(movable) or can_move_z(movable)) |
class MetricOptions():
def __init__(self, G_ema=None, G=None, D=None, M=None, G_kwargs={}, D_kwargs={}, M_kwargs={}, dataset_kwargs={}, testset_kwargs={}, num_gpus=1, rank=0, device=None, progress=None, cache=True, txt_recon=True, img_recon=False, metric_only_test=False, use_fmri=False, fmri_vec=None, fmri_vec2=Non... |
def action_android():
(sccache, python, pip) = setup_basic_build_env()
setup_android_ndk()
handle_alternate_actions()
build_android(python, pip)
try:
sccache('-s')
except CommandFailed:
pass |
.torch
def test_item_embedder_weights(tensor_schema):
item_embedder = SasRecModel(tensor_schema.subset(['item_id', 'timestamp']), hidden_size=64, max_len=5, ti_modification=True).item_embedder
assert (item_embedder.get_item_weights(torch.tensor([0, 1, 2, 3])).size() == (4, 64)) |
def multiple_samples_collate(batch, fold=False):
(inputs, labels, video_idx, extra_data) = zip(*batch)
inputs = [item for sublist in inputs for item in sublist]
labels = [item for sublist in labels for item in sublist]
video_idx = [item for sublist in video_idx for item in sublist]
(inputs, labels, ... |
.parametrize('channel_axis', [0, 1, 2, (- 1), (- 2), (- 3)])
def test_laplacian_pyramid_max_layers(channel_axis):
for downscale in [2, 3, 5, 7]:
if (channel_axis is None):
shape = (32, 8)
shape_without_channels = shape
else:
shape_without_channels = (32, 8)
... |
_utils.polymorphic_model()
class GdsMesh(Mesh):
type = schema_utils.polymorphic_model_type('mesh.gds_mesh')
material = types.ModelType(Material)
extents = optplan.vec2d()
gds_layer = types.ListType(types.IntType()) |
def save_graph_to_file(sess, graph, graph_file_name):
output_graph_def = graph_util.convert_variables_to_constants(sess, graph.as_graph_def(), [FLAGS.final_tensor_name])
with gfile.FastGFile(graph_file_name, 'wb') as f:
f.write(output_graph_def.SerializeToString())
return |
def conv(x, channels, kernel=4, stride=2, pad=0, pad_type='zero', use_bias=True, scope='conv'):
with tf.variable_scope(scope):
if scope.__contains__('discriminator'):
weight_init = tf.random_normal_initializer(mean=0.0, stddev=0.02)
else:
weight_init = tf_contrib.layers.varia... |
def perform_tests_with(clf, cv_test, stopwords=True):
multilabel_doc = (x_test[0] + x_test[1])
multilabel_labels = [y_test[0], y_test[1]]
multilabel_idxs = [clf.get_category_index(y_test[0]), clf.get_category_index(y_test[1])]
new_cat = 'bla'
def_cat = 'music'
def_cat_idx = clf.get_category_inde... |
def sentnet_color_2d(width, height, frame_count, lr, output=9, model_name='sentnet_color.model'):
network = input_data(shape=[None, width, height, 3], name='input')
network = conv_2d(network, 96, 11, strides=4, activation='relu')
network = max_pool_2d(network, 3, strides=2)
network = local_response_norm... |
class KLLoss(loss._Loss):
def forward(self, output, target):
if (not self.training):
return F.cross_entropy(output, target)
assert ((type(output) == tuple) and (len(output) == 2) and (output[0].size() == output[1].size())), 'output must a pair of tensors of same size.'
(model_out... |
def get_chunks_by_qa(qa_pair, article_seg_json):
chunks = {}
for (key, value) in article_seg_json.items():
if ('slack' in qa_pair['article_segment_id']):
ids = set(['-'.join(sent['id'].split('-')[:2]) for sent in value['seg_dialog']])
for article_full_id in qa_pair['article_full_... |
def debug_code_agents(agent_test_config, memory_json_file, workspace: Workspace):
agents = []
goals = [['1- Run test.py using the execute_python_file command.', '2- Read code.py using the read_file command.', '3- Modify code.py using the write_to_file command.Repeat step 1, 2 and 3 until test.py runs without er... |
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('from_path')
parser.add_argument('to_path')
return parser.parse_args() |
def ignore_in_to_list(getitem_function):
getitem_function.ignore_in_to_list = True
return getitem_function |
class semanticModule(nn.Module):
def __init__(self, in_dim):
super(semanticModule, self).__init__()
self.chanel_in = in_dim
self.enc1 = _EncoderBlock(in_dim, (in_dim * 2))
self.enc2 = _EncoderBlock((in_dim * 2), (in_dim * 4))
self.dec2 = _DecoderBlock((in_dim * 4), (in_dim * ... |
def create_project(project_id: str, base_path: str='', meta: Dict[(str, Any)]=None):
project = Project(base_path, project_id)
project._YAML = meta
return project |
class TimmMixup(Mixup):
def __call__(self, x, target):
if (self.mode == 'elem'):
lam = self._mix_elem(x)
elif (self.mode == 'pair'):
assert ((len(x) % 2) == 0), 'Batch size should be even when using this'
lam = self._mix_pair(x)
else:
lam = sel... |
class ResNet(Classifier):
def __init__(self, N_class, resolution=(1, 32, 32), blocks=[3, 3, 3], normalization=True, channels=64, **kwargs):
super(ResNet, self).__init__(N_class, resolution, **kwargs)
self.blocks = blocks
self.channels = channels
self.normalization = normalization
... |
class Context(object):
def __init__(self, command, parent=None, info_name=None, obj=None, auto_envvar_prefix=None, default_map=None, terminal_width=None, max_content_width=None, resilient_parsing=False, allow_extra_args=None, allow_interspersed_args=None, ignore_unknown_options=None, help_option_names=None, token_n... |
def test_callbacks():
from functools import partial
def func1():
return 'func1'
def func2(a, b, c, d):
return ('func2', a, b, c, d)
def func3(a):
return 'func3({})'.format(a)
assert (m.test_callback1(func1) == 'func1')
assert (m.test_callback2(func2) == ('func2', 'Hello',... |
('/get_transaction/<txhash>', methods=('GET',))
def get_transaction(txhash):
web3 = connect_to_geth(app.web3_url, app.consensus)
try:
tx = dict(web3.eth.get_transaction(txhash))
except:
tx = {'status': 'No such transaction'}
resp = Response(json.dumps(tx, cls=HexJsonEncoder, indent=5))
... |
def findtask(description):
task_list = ee.data.getTaskList()
for t in task_list:
if (t['description'] == description):
if ((t['state'] == 'READY') or (t['state'] == 'RUNNING')):
return True
return False |
def cumulative_distribution(image, nbins=256):
(hist, bin_centers) = histogram(image, nbins)
img_cdf = hist.cumsum()
img_cdf = (img_cdf / float(img_cdf[(- 1)]))
cdf_dtype = utils._supported_float_type(image.dtype)
img_cdf = img_cdf.astype(cdf_dtype, copy=False)
return (img_cdf, bin_centers) |
def haar_init_(A):
torch.nn.init.orthogonal_(A)
with torch.no_grad():
if (A.det() < 0.0):
idx = np.random.randint(0, A.size(0))
A[idx] *= (- 1.0)
An = la.logm(A.data.cpu().numpy()).real
An = (0.5 * (An - An.T))
A.copy_(torch.tensor(An))
return A |
def is_word_exist(new_word, words_in_db):
for key in words_in_db:
word = words_in_db[key]
if (word['word'] == new_word):
return True
return False |
def text2tensor(text, size=256):
nums = [ord(x) for x in text]
assert (len(nums) < size)
nums.extend(([0] * (size - len(nums))))
nums = np.array(nums, dtype=np.uint8)
return torch.from_numpy(nums) |
class MultitaskDatasetWrapper(BaseWrapperDataset):
def __init__(self, dataset, target_language_id, sample=1.0, name=''):
super().__init__(dataset)
self.target_language_id = target_language_id
self.sample = sample
self.name = name
def collater(self, *args, **kwargs):
ans =... |
def train_speaker_dependent(config: Config, data: DataLoader, model_name: str) -> None:
results = []
for (fold, (train_index, test_index)) in enumerate(data.get_stratified_k_fold()):
config.fold = (fold + 1)
print('Present Fold:', config.fold)
(train_input, train_output, test_input, test... |
class RecorderWrapper(gym.Wrapper):
def __init__(self, env, fps, save_dir, label, record_every):
super().__init__(env)
self.record_every = record_every
self.save_dir = save_dir
self.label = label
assert (self.label in ('emulator', 'preproc'))
self.fps = fps
se... |
def get_arguments(traj_data):
task_type = traj_data['task_type']
try:
r_idx = traj_data['repeat_idx']
except:
r_idx = 0
language_goal_instr = traj_data['turk_annotations']['anns'][r_idx]['task_desc']
sliced = exist_or_no(traj_data['pddl_params']['object_sliced'])
mrecep_target = ... |
class ViTMSNPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def pc_loss(f, K, labels):
sigmoid = nn.Sigmoid()
fbar = f.gather(1, labels.long().view((- 1), 1)).repeat(1, K)
loss_matrix = sigmoid(((- 1.0) * (f - fbar)))
(M1, M2) = (((K * (K - 1)) / 2), (K - 1))
pc_loss = ((((torch.sum(loss_matrix) * (K - 1)) / len(labels)) - M1) + M2)
return pc_loss |
class ConfigurationTestCase(unittest.TestCase):
def test_default(self):
config = Configuration()
self.assertEqual(config.log, 'info')
self.assertTrue(config.interactive)
def test_example(self):
SAGE_BOOTSTRAP = ' loG:CrItIcAl, interactive:TRUE'
result = run_config_with(SA... |
class TestSnapshotter():
def setup_method(self):
self.temp_dir = tempfile.TemporaryDirectory()
def teardown_method(self):
self.temp_dir.cleanup()
.parametrize('mode, files', [*configurations])
def test_snapshotter(self, mode, files):
snapshotter = Snapshotter(self.temp_dir.name, ... |
def profile_likelihood(ln, lk, n, k, ww, plot=False):
def p_d(d):
return _compute_binomial_logl(d, lk, k, ln, n, w=ww)
dx = 10.0
d_left = D_MIN
d_right = ((D_MAX + dx) + d_left)
elements = 0
counter = 0
while (elements < 3):
dx /= 10.0
counter += 1
d_range = n... |
class BaseGenerator(metaclass=abc.ABCMeta):
def generate(self, query: str, stop_tokens=None, max_output_len=None):
pass |
class MetaModule(nn.Module):
def meta_named_parameters(self, prefix='', recurse=True):
gen = self._named_members((lambda module: (module._parameters.items() if isinstance(module, MetaModule) else [])), prefix=prefix, recurse=recurse)
for elem in gen:
(yield elem)
def meta_parameters(... |
class TimeEstimator():
def __init__(self, total_iter, step_size):
self.avg_time_window = []
self.exp_avg_time = None
self.alpha = 0.7
self.last_time = time.time()
self.total_iter = total_iter
self.step_size = step_size
self.buffering_exp = True
def update(... |
def load_image(file_path, input_height=128, input_width=None, output_height=128, output_width=None, crop_height=None, crop_width=None, is_random_crop=True, is_mirror=True, is_gray=False):
if (input_width is None):
input_width = input_height
if (output_width is None):
output_width = output_height... |
class PhaseShiftTest(tf.test.TestCase):
def test_upper(self):
ps = PhaseShiftUpper(RANDOM_PHASE_SHIFT)
ps_inv = PhaseShiftUpper((- RANDOM_PHASE_SHIFT))
self.assertAllClose((ps.matrix ps.inverse_matrix), IDENTITY)
self.assertAllClose(ps.matrix.conj(), ps.inverse_matrix)
self.... |
class MeasureStatistics(metaclass=Singleton):
def __init__(self, folder):
self.enabled = False
self.folder = os.path.join(base_dir, 'distance', folder)
self.stats = {}
self.stats_names = ['dist']
def save_measure(self, tensor, id):
if (id not in self.stats):
s... |
class Sphinx(PythonModule):
def __init__(self):
PythonModule.__init__(self, 'sphinx', spkg='sphinx', type='standard') |
def audio_to_sequence_example(filename, labels, sample_rate, n_samples):
segments = _audio_to_segments(filename, sample_rate=sample_rate, n_samples=n_samples)
sequence_example = _segments_to_sequence_example(segments, labels)
return sequence_example |
class WHUBuildingDataset(Dataset):
def __init__(self, data_root='data/whubuilding/train', mode='train', img_dir='image', mask_dir='label', img_suffix='.tif', mask_suffix='.tif', transform=None, mosaic_ratio=0.25, img_size=ORIGIN_IMG_SIZE):
self.data_root = data_root
self.img_dir = img_dir
se... |
def add_data_arguments(parser):
parser.add_argument('--ent_emb', default=['tzw'], nargs='+', help='sources for entity embeddings')
parser.add_argument('-ds', '--dataset', default='csqa', choices=DATASET_LIST, help='dataset name')
parser.add_argument('--data_dir', default='data', type=str, help='Path to the ... |
class ActionTokenTester(TokenTester):
def test_consistent(self, env, dom, dom_elem):
raise NotImplementedError() |
def download_wiki2():
URL = '
path_to_zip_file = download_file(URL)
print(f'-I- Donwloaded wikitext2 to {path_to_zip_file}. Extracting...')
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
zip_ref.extractall(DATA_DIR)
print('-I- Done') |
def helper_prod_test_service(request: Request, expected_text: str):
service = get_prod_service()
auth = get_authentication()
result = service.make_request(auth, request)
print(result)
assert result.success
assert (len(result.completions) == request.num_completions)
for completion in result.c... |
def test_case14():
url = (brokerIp + '/ngsi-ld/v1/entities/')
r = requests.post(url, data=json.dumps(ld_data.subdata14))
print(r.content)
print(r.status_code)
assert (r.status_code == 400) |
class input_file(cmd_arg):
def find_node(self, base_path):
assert isinstance(base_path, Node.Node)
self.node = base_path.find_resource(self.name)
if (self.node is None):
raise Errors.WafError(('Input file %s not found in ' % (self.name, base_path)))
def get_path(self, env, ab... |
def match_declarations_with_differentiability_info(declarations, differentiability_infos):
infos_by_signature = {f['signature']: f for f in differentiability_infos}
def find_info(declaration):
signature = get_signature(declaration)
if (signature in infos_by_signature):
return infos_b... |
def get_root():
parser = xml.sax.make_parser()
myHandler = MyHandler()
parser.setContentHandler(myHandler)
parser.setFeature(feature_external_ges, True)
parser.parse('resources/config.xml')
return parser |
class EngineType(Enum):
BD = 0
GDMA = 1
GDE = 2
SORT = 3
NMS = 4
CDMA = 5
UNKNOWN = (- 1) |
def issigned_long_longarray(var):
return (isarray(var) and (var.get('typespec') in ['integer', 'logical']) and (get_kind(var) == '8')) |
def param2pystr(p):
if ((param_kind(p) == IN_ARRAY) or (param_kind(p) == OUT_ARRAY) or (param_kind(p) == IN_ARRAY) or (param_kind(p) == INOUT_ARRAY) or (param_kind(p) == OUT)):
return ('ctypes.POINTER(%s)' % type2pystr(param_type(p)))
else:
return type2pystr(param_type(p)) |
.core
.usefixtures('interactions_full_pandas_dataset')
def test_feature_schema_schema_copy(interactions_full_pandas_dataset):
feature_list = get_features(interactions_full_pandas_dataset)
feature_list_copy = feature_list.copy()
for feature in feature_list_copy.values():
if (feature.feature_type == F... |
def select_child(state_dict, string):
if (string[(- 1)] != '.'):
string = (string + '.')
return {k.replace(string, ''): v for (k, v) in state_dict.items() if k.startswith(string)} |
class TestFairseqEncoderBase(unittest.TestCase):
def setUpClass(cls):
if (cls is TestFairseqEncoderBase):
raise unittest.SkipTest('Skipping test case in base')
super().setUpClass()
def setUpEncoder(self, encoder):
self.assertTrue(isinstance(encoder, FairseqEncoder), msg='This... |
def load(filename, batch_size=None, exclude_parameter=False, parameter_only=False, extension='.nntxt', parameter_scope=None, rng=None):
from nnabla.utils import nnabla_pb2
from nnabla.utils.get_file_handle import get_initial_file_loader, load_files, FileHandlerContext
ctx = FileHandlerContext()
ctx.excl... |
def text_query(clip_model, scene_pcd, scene_graph, device='cuda:0'):
query = input("Please query an object: (input 'q' to quit)\n")
while (query != 'q'):
text_feature = get_clip_feature(clip_model, query, normalize=True, device=device)
text_feature = text_feature.cpu().detach().numpy().flatten()... |
.expansion
class ExpandGemvMKL(ExpandTransformation):
environments = [environments.intel_mkl.IntelMKL]
def expansion(*args, **kwargs):
return ExpandGemvOpenBLAS.expansion(*args, **kwargs) |
class Checkpointer(object):
def __init__(self, cfg, models, auxiliary=None, save=True):
self.models = models
self.auxiliary = auxiliary
self.cfg = cfg
self._save = save
def save(self, _name, **kwargs):
if (not self._save):
return
data = dict()
... |
class FakeProtocol():
def __init__(self, name, memories=[]):
self.name = name
self.other_is_setted = False
self.is_started = False
self.rule = Rule(None, None, None, None, None)
self.rule.protocols.append(self)
self.memories = memories
self.own = None
def ... |
def multi_dimensional_attention(rep_tensor, rep_mask, scope=None, keep_prob=1.0, is_train=None, wd=0.0, activation='elu', tensor_dict=None, name=None):
(bs, sl, vec) = (tf.shape(rep_tensor)[0], tf.shape(rep_tensor)[1], tf.shape(rep_tensor)[2])
ivec = rep_tensor.get_shape()[2]
with tf.variable_scope((scope o... |
class TestKerasBaseWeightsQuantizer(BaseKerasTrainableInfrastructureTest):
def __init__(self, unit_test):
super().__init__(unit_test)
def get_weights_quantization_config(self):
return TrainableQuantizerWeightsConfig(weights_quantization_method=QuantizationMethod.UNIFORM, weights_n_bits=8, weight... |
()
def sample_report() -> CoverageReport:
return CoverageReport(module='cov_demo', source=['def foo():\n', ' pass\n', '\n', '\n', 'def baz():\n', ' assert 3 == 5 and 3 == -3\n', '\n', '\n', 'def bar(x: int):\n', ' if x:\n', ' return 5\n', ' else:\n', ' return 6\n'], branches=CoverageEntry(... |
class ColorizationModel(Pix2PixModel):
def modify_commandline_options(parser, is_train=True):
Pix2PixModel.modify_commandline_options(parser, is_train)
parser.set_defaults(dataset_mode='colorization')
return parser
def __init__(self, opt):
Pix2PixModel.__init__(self, opt)
... |
def plot_fig(test_img, scores, gts, threshold, save_dir, class_name):
num = len(scores)
for i in range(num):
img = test_img[i]
img = denormalization(img)
gt = gts[i].transpose(1, 2, 0).squeeze()
heat_map = (scores[i] * 255)
mask = scores[i]
mask[(mask > threshold)... |
class PeriodicCheckpointer():
def __init__(self, checkpointer: Any, period: int, max_epoch: int=None):
self.checkpointer = checkpointer
self.period = int(period)
self.max_epoch = max_epoch
self.best_metric = (- 1)
def step(self, epoch: int, **kwargs: Any):
epoch = int(epo... |
def test_bilevel():
expected = np.zeros((10, 10), bool)
expected[::2] = 1
img = imread(fetch('data/checker_bilevel.png'))
assert_array_equal(img.astype(bool), expected) |
def init_weight(dim_in, dim_out, name=None, stddev=1.0):
return tf.Variable(tf.truncated_normal([dim_in, dim_out], stddev=(stddev / math.sqrt(float(dim_in)))), name=name) |
class DebertaTokenizerFast(GPT2TokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
model_input_names = ['input_ids', 'attention_mask', 'token_type_ids']
slow_tokenizer_class = Deb... |
class TestLoopBlockingSolver(TestLoopBlockingFixture):
def setUp(self):
super(TestLoopBlockingSolver, self).setUp()
self.optkeys_bypsol = ['BYPSOL_{}'.format(dce) for dce in range(de.NUM)]
for reside_dce in range(de.NUM):
opt_dict = self.options['BYPSOL']._asdict()
by... |
def preprocess_rl_variant(variant):
if variant.get('do_state_exp', False):
if ('observation_key' not in variant):
variant['observation_key'] = 'state_observation'
if ('desired_goal_key' not in variant):
variant['desired_goal_key'] = 'state_desired_goal'
if ('achieved_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.