code stringlengths 101 5.91M |
|---|
class CIFARWRN(nn.Module):
def __init__(self, channels, init_block_channels, in_channels=3, in_size=(32, 32), num_classes=10):
super(CIFARWRN, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module('init... |
.dataclass
class FlaxMultipleChoiceModelOutput(ModelOutput):
logits: jnp.ndarray = None
hidden_states: Optional[Tuple[jnp.ndarray]] = None
attentions: Optional[Tuple[jnp.ndarray]] = None |
_incremental_state
class FConvDecoder(FairseqDecoder):
def __init__(self, dictionary, embed_dim=512, out_embed_dim=256, max_positions=1024, convolutions=(((512, 3),) * 8), attention=True, dropout=0.1, selfattention=False, attention_nheads=1, selfattention_nheads=1, project_input=False, gated_attention=False, downsa... |
def read_from_file(file_name):
try:
file = open(file_name, 'r', encoding='utf-8')
content = file.read()
file.close()
except IOError as e:
content = ''
print('IO Error!:{}'.format(e))
return content |
def test_get_flat_plane_grid_triangles() -> None:
nearby_triangles = get_flat_plane_grid_triangles(range_m=1)
assert (len(nearby_triangles) == 8)
for range_m in range(30):
tris = get_flat_plane_grid_triangles(range_m)
print(f'{len(tris)} at range={range_m}') |
class AttentionActor(nn.Module):
def __init__(self, in_dim, out_dim, hidden_size, layers, activation=nn.ReLU):
super().__init__()
self.feedforward_model = build_model(hidden_size, out_dim, 1, hidden_size, activation)
self._attention_stack = AttentionEncoder(1, hidden_size, hidden_size)
... |
def initinterference(profile, test):
ans = []
if False:
latency = []
for la in profile['interference']['latency']:
if ((la[0] != 'ssd') and (la[1] != 'ssd')):
latency.append(la)
l = len(latency)
print(l)
l = len(profile['interference']['latency'])
... |
def test_predict_proba_raises(model, X):
f = getattr(model, 'predict_proba')
assert_raises(ValueError, f, [X])
assert_raises(ValueError, f, X[0])
assert_raises((ValueError, TypeError, RuntimeError), f, X[0][0])
if (MIN_VALUE is not None):
assert_raises(ValueError, f, [[[(MIN_VALUE - 0.1) for... |
def pre_process_dataset_composite_in_user_format(user_datasets, label_map, output_shape, train_users, window_size, shift, normalise_dataset=True, verbose=0):
if normalise_dataset:
(means, stds) = get_mean_std_from_user_list_format(user_datasets, train_users)
user_datasets_windowed = get_windows_dataset_... |
class ShapKernel(ExplainerMixin):
available_explanations = ['local']
explainer_type = 'blackbox'
def __init__(self, model, data, feature_names=None, feature_types=None, **kwargs):
from shap import KernelExplainer
self.model = model
self.feature_names = feature_names
self.feat... |
def obslogPath(year=None, hemisphere=None):
base = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'obslogs')
if (year is None):
if (_APOGEE_REDUX == 'v402'):
year = 2
elif ((_APOGEE_REDUX == 'v603') or (_APOGEE_REDUX == 'l30e.2')):
year = 3
elif (_APOGE... |
def adjust_learning_rate(optimizer, epoch):
lr = cfg.optimizer.lr
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr |
def get_rir_cifar(num_classes, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs):
channels = [[48, 48, 48, 48], [96, 96, 96, 96, 96, 96], [192, 192, 192, 192, 192, 192]]
init_block_channels = 48
final_block_channels = 384
net = CIFARRiR(channels=channels, init_bloc... |
def save_checkpoint(state, filename='checkpoint'):
if (False and ('optimizer_state' in state)):
optimizer_state = state['optimizer_state']
state.pop('optimizer_state', None)
optimizer_filename = '{}_optim.pth'.format(filename)
torch.save({'optimizer_state': optimizer_state}, optimize... |
def _features2eigenvalues(features):
gram = tf.matmul(features, features, transpose_b=True)
(eig, _) = tf.linalg.eigh(gram)
return eig |
def get_root_logger(save_dir, log_level=logging.INFO, filename='log.txt'):
logger = logging.getLogger()
if (not logger.hasHandlers()):
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=log_level)
(rank, _) = get_dist_info()
if (rank != 0):
logger.setLevel('ERR... |
def standard_laurent_ismember_filter(wsys, gpts, dim, points, rcotol=1e-06, evatol=1e-06, memtol=1e-06, verbose=True, tasks=0):
from phcpy.solutions import diagnostics
result = []
for point in points:
rco = diagnostics(point)[1]
if (rco > rcotol):
(isgood, ismember) = (True, Fals... |
class CosineAnnealingLR(object):
def __init__(self, T_max, eta_max=0.01, eta_min=0, last_epoch=(- 1)):
self.T_max = T_max
self.eta_max = eta_max
self.eta_min = eta_min
self.last_epoch = last_epoch
self._cur_lr = eta_max
def step(self):
self._cur_lr = self._get_lr(... |
class FEVERDocumentDatabase(DocDB):
def __init__(self, path=None):
super().__init__(path)
logger.info(f'Use FEVER db: {path}')
_cache(maxsize=1000)
def get_doc_lines(self, doc_id):
cursor = self.connection.cursor()
cursor.execute('SELECT lines FROM documents WHERE id = ?', (u... |
class StableDiffusionLDM3DPipeline(metaclass=DummyObject):
_backends = ['torch', 'transformers']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch', 'transformers'])
def from_config(cls, *args, **kwargs):
requires_backends(cls, ['torch', 'transformers'])
def from_pretr... |
def main():
batch_size = (c.BATCH_SIZE * c.TRIPLET_PER_BATCH)
train_path = c.DATASET_DIR
libri = data_catalog(train_path)
files = list(libri['filename'])
labels1 = list(libri['speaker_id'])
labels_to_id = {}
id_to_labels = {}
i = 0
for label in np.unique(labels1):
labels_to_i... |
def load_layer_wise_quantized_model(path):
model = torch.load(os.path.join(path, 'model_arch.pt'))
for (name, _) in model.named_modules():
if ((name + '.pt') in os.listdir(path)):
update_module(model, name, torch.load(os.path.join(path, (name + '.pt'))))
model.eval()
return model |
def get_ID_task_avg_score(result_dict):
sum = 0
num = 0
for (k, v) in result_dict.items():
if (k == 'best_model_dir'):
continue
sum += v
num += 1
return (sum / num) |
class LoadSaveStrategyTest(unittest.TestCase):
(torch.cuda.is_available(), 'Skip on gpu as cpu test covers it.')
def test_load_save_strategy(self):
pg_info = ([('data', 2)], None)
strategy = Strategy([('parallel_mode', pg_info, False), ('amp_native', None, False)])
(_, filename) = tempfi... |
def _extract_variable_from_kwargs(kwargs, name):
variable_value = kwargs.get(name, None)
if variable_value:
kwargs[name] = None
return (variable_value, kwargs) |
class HernquistPotential(DehnenSphericalPotential):
def __init__(self, amp=1.0, a=1.0, normalize=False, ro=None, vo=None):
DehnenSphericalPotential.__init__(self, amp=amp, a=a, alpha=1, normalize=normalize, ro=ro, vo=vo)
self._nemo_accname = 'Dehnen'
self.hasC = True
self.hasC_dxdv =... |
class TestExtractVideoFrames(unittest.TestCase):
def test_extract_video_frames(self):
try:
shutil.rmtree((TEST_FRAMES_DIR / 'video_frames'))
except FileNotFoundError:
pass
extract_video_frames((TEST_FRAMES_DIR / 'video.mp4'))
self.assertTrue((TEST_FRAMES_DIR /... |
def parse_config_dict(args, config_dict):
if (args.save_exp_code is not None):
config_dict['exp_arguments']['save_exp_code'] = args.save_exp_code
if (args.overlap is not None):
config_dict['patching_arguments']['overlap'] = args.overlap
return config_dict |
def _restore_attributes_(gm: GraphModule, attributes: Dict[(str, Any)]):
for (name, attr) in attributes.items():
setattr(gm, name, attr) |
class GroupedIterator(object):
def __init__(self, iterable, chunk_size):
self._len = int(math.ceil((len(iterable) / float(chunk_size))))
self.itr = iterable
self.chunk_size = chunk_size
def __len__(self):
return self._len
def __iter__(self):
return self
def __next... |
def make_loss(cfg, num_classes):
if (cfg.MODEL.METRIC_LOSS_TYPE == 'triplet'):
metric_loss_func = TripletLoss(cfg.SOLVER.MARGIN, cfg.SOLVER.HARD_EXAMPLE_MINING_METHOD)
elif (cfg.MODEL.METRIC_LOSS_TYPE == 'contrastive'):
metric_loss_func = ContrastiveLoss(cfg.SOLVER.MARGIN)
elif (cfg.MODEL.ME... |
class CNN_4Layer(nn.Module):
def __init__(self, in_channels, out_channels=64, hidden_size=64):
super(CNN_4Layer, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.hidden_size = hidden_size
self.encoder = nn.Sequential(conv3x3(in_channels, h... |
def select_topk(indices, query, gallery, topk=10):
results = []
for i in range(indices.shape[0]):
ids = indices[i][:topk]
results.append(([query[i][0]] + [gallery[id][0] for id in ids]))
return results |
def check_onnx(model_path, dataloader):
import onnxruntime as ort
import numpy as np
ort_session = ort.InferenceSession(model_path, providers=['CPUExecutionProvider'])
it = iter(dataloader)
input = next(it)
input_names = list(input.keys())
for k in input_names:
if ('label' in k):
... |
def download_model(url, model_name, retry_times=5):
if os.path.isdir(model_name):
return model_name
elif (os.path.exists(model_name) and is_tar_gz_file(model_name)):
print('file downloaded')
extrafile(model_name)
return True
print('download model...')
retries = 0
whil... |
_REGISTRY.register()
def build_fcos_dla_fpn_backbone(cfg, input_shape: ShapeSpec):
assert (cfg.MODEL.BACKBONE.FREEZE_AT == (- 1)), 'Freezing layers does not be supported for DLA'
depth_to_creator = {'DLA34': dla34}
bottom_up = depth_to_creator[cfg.MODEL.DLA.CONV_BODY](cfg)
in_features = cfg.MODEL.FPN.IN... |
class UniSpeechForCTC(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class Trainer():
def __init__(self, environment, policy, replay_buffer, curriculum_scheduler, mcts_train_params, mcts_test_params, num_validation_episodes, num_episodes_per_task, batch_size, num_updates_per_episode, verbose=True):
self.env = environment
self.policy = policy
self.buffer = rep... |
class Net(nn.Module):
def __init__(self, dropout, fc1_size, fc2_size):
super().__init__()
self.fc1 = nn.Linear(50, fc1_size)
self.relu1 = nn.ReLU()
self.dout = nn.Dropout(dropout)
self.fc2 = nn.Linear(fc1_size, fc2_size)
self.prelu = nn.PReLU(1)
self.out = nn.... |
def define_stochastic_G(nlatent, input_nc, output_nc, ngf, norm='instance', which_model_netG='resnet', use_dropout=False, gpu_ids=[]):
netG = None
use_gpu = (len(gpu_ids) > 0)
if use_gpu:
assert torch.cuda.is_available()
norm_layer = CondInstanceNorm
netG = CINResnetGenerator(nlatent, input_... |
def find_traj_with_fix_length(start_index, time_stamp_list, time_stamp_pose_dict):
length = 0.0
for i in range(start_index, (len(time_stamp_list) - 1)):
length += distance(time_stamp_pose_dict[time_stamp_list[i]], time_stamp_pose_dict[time_stamp_list[(i + 1)]])
if (length >= TRAJ_LENGTH):
... |
def make_kl_with_gaussian_prior(weight_decay, temperature=1.0):
def kl_fn(params):
n_params = sum([p.size for p in jax.tree_leaves(params)])
sigma_prior = jnp.sqrt((1 / weight_decay))
mu_vi_tree = params['mean']
sigma_vi_tree = jax.tree_map(jax.nn.softplus, params['inv_softplus_std']... |
def is_module_wrapper(module):
module_wrappers = tuple(MODULE_WRAPPERS.module_dict.values())
return isinstance(module, module_wrappers) |
def kconv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1), activation=None):
channel_axis = (1 if (backend.image_data_format() == 'channels_first') else (- 1))
filters = int((filters * alpha))
x = layers.ZeroPadding2D(padding=((0, 1), (0, 1)), name='conv1_pad')(inputs)
x = layers.Conv2D(filt... |
def pad(x: Tensor, p: int=(2 ** (4 + 3))) -> Tuple[(Tensor, Tuple[(int, ...)])]:
(h, w) = (x.size(2), x.size(3))
new_h = ((((h + p) - 1) // p) * p)
new_w = ((((w + p) - 1) // p) * p)
padding_left = ((new_w - w) // 2)
padding_right = ((new_w - w) - padding_left)
padding_top = ((new_h - h) // 2)
... |
def mnasnet0_5(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> MNASNet:
model = MNASNet(0.5, **kwargs)
if pretrained:
_load_pretrained('mnasnet0_5', model, progress)
return model |
class CompletionStreamResponse(BaseModel):
id: str = Field(default_factory=(lambda : f'cmpl-{random_uuid()}'))
object: str = 'text_completion'
created: int = Field(default_factory=(lambda : int(time.time())))
model: str
choices: List[CompletionResponseStreamChoice] |
def conv_output_length(input_length, filter_size, stride, pad=0):
if (input_length is None):
return None
if (pad == 'valid'):
output_length = ((input_length - filter_size) + 1)
elif (pad == 'full'):
output_length = ((input_length + filter_size) - 1)
elif (pad == 'same'):
... |
class Logger(object):
def __init__(self, config, rank=0):
self.rank = rank
self.summary_writer = None
self.continue_training = config.training_config.continue_training
self.logdir = config.training_config.logdir
self.sample_rate = config.data_config.sample_rate
if (se... |
def get_dropout_layer(dropout=None):
if (dropout is not None):
return [nn.Dropout(p=dropout)]
else:
return [] |
def Tanh(data, name=None):
name = (GetLayerName.get('tanh') if (name is None) else name)
x = mx.sym.tanh(data, name=name)
return x |
def deduplicate_dataset(dataset: Type[Dataset], jaccard_threshold: float=0.85) -> Tuple[(Type[Dataset], List[List[Dict]])]:
duplicate_clusters = make_duplicate_clusters(dataset, jaccard_threshold)
duplicate_indices = {x['base_index'] for cluster in duplicate_clusters for x in cluster}
extreme_dict = {}
... |
def test_generate_fangraphs_teams() -> None:
with patch.object(pd.DataFrame, 'to_csv', MagicMock()) as to_csv_mock:
result = _generate_teams()
assert (result is not None)
assert (not result.empty)
result = result.query('yearID <= 2019')
assert (len(result.columns) == 7)
... |
def test_ocr_reader_are_singletons():
reader_a = DummyOCRReader()
reader_b = DummyOCRReader()
reader_c = DummyOCRReader()
assert (reader_a is reader_b)
assert (reader_a is reader_c) |
(deadline=None)
(params=example_case_sampling())
def test_c_eval(params):
(poly, poly_h, x) = params
res = poly(x)
res_h = poly_h._eval_c(x)
coefficients = poly.coefficients
exponents = poly.exponents
all_close(res, res_h, coefficients, exponents, x) |
def realign(dir, iter, feat_dir, lang, prev_egs_dir, cur_egs_dir, prior_subset_size, num_archives, run_opts, online_ivector_dir=None):
raise Exception('Realignment stage has not been implemented in nnet3')
logger.info('Getting average posterior for purposes of adjusting the priors.')
avg_post_vec_file = com... |
def get_chunks(fpath, chunk_size):
f = open(fpath)
chunk = []
for line in f:
chunk.append(line.strip())
if (len(chunk) == chunk_size):
(yield chunk)
chunk = []
(yield chunk) |
def _get_tensorflow_version():
tf_version = str(tensorflow.__version__)
if ((int(tf_version.split('.')[0]) != 1) and (int(tf_version.split('.')[0]) != 2)):
raise ValueError('tensorflow version error')
return int(tf_version.split('.')[0]) |
def atom_to_feature_vector(atom):
atom_feature = [safe_index(allowable_features['possible_atomic_num_list'], atom.GetAtomicNum()), allowable_features['possible_chirality_list'].index(str(atom.GetChiralTag())), safe_index(allowable_features['possible_degree_list'], atom.GetTotalDegree()), safe_index(allowable_featur... |
class Model(Entity):
def __init__(self, name=None, pose=None):
Entity.__init__(self, name, pose)
self.links = []
self.joints = []
self.plugins = [] |
def noon(dim, parameter=1.1):
result = []
for i in range(dim):
pol = (('x' + str((i + 1))) + '*(')
for j in range(dim):
if (i != j):
if (pol[(- 1)] != '('):
pol = (pol + ' + ')
pol = (((pol + 'x') + str((j + 1))) + '^2')
pol... |
def get_transform(opt, for_val=False):
transform_list = []
if for_val:
transform_list.append(transforms.Resize(opt.loadSize, interpolation=PIL.Image.LANCZOS))
transform_list.append(transforms.CenterCrop(opt.loadSize))
transform_list.append(transforms.ToTensor())
else:
transfo... |
class att_TDNN(nn.Module):
def __init__(self, C, F, CE):
super().__init__()
dim = int((C * F))
self.mlp = nn.Linear(dim, dim)
self.TDNN = nn.Conv1d(dim, CE, kernel_size=1)
def FCA(self, x, B, C, F):
skip = x
x = torch.mean(x, dim=(- 1), keepdim=False).view(B, (- 1... |
class ResNetD(nn.Module):
def __init__(self, channels, init_block_channels, bottleneck, conv1_stride, ordinary_init=False, multi_output=False, in_channels=3, in_size=(224, 224), num_classes=1000):
super(ResNetD, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
s... |
def get_next_batch(dataloader, device):
data_dict = dataloader.__next__()
batch_dict = get_dict_template()
batch_dict['data'] = data_dict['data'].to(device)
batch_dict['time_steps'] = data_dict['time_steps'].to(device)
batch_dict['mask'] = data_dict['mask'].to(device)
return batch_dict |
class CocoDataset(CustomDataset):
CLASSES = ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic_light', 'fire_hydrant', 'stop_sign', 'parking_meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', '... |
class PRExplanation(ExplanationMixin):
explanation_type = None
def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None):
self.explanation_type = explanation_type
self._internal_obj = internal_obj
self.feature_names = feature_nam... |
def _download_file(downloadPath, filePath, verbose=False, spider=False):
downloadPath = downloadPath.replace(os.sep, '/')
sys.stdout.write(('\r' + ('Downloading file %s ...\r' % os.path.basename(filePath))))
sys.stdout.flush()
try:
os.makedirs(os.path.dirname(filePath))
except OSError:
... |
def test():
twisted2 = ['x**2*y - z*x;', 'x**2*z - y**2*x;']
maps = solve_binomials(3, twisted2, silent=False)
for solmap in maps:
print(solmap)
print('looking only for expected pure dimensional sets ...')
maps = solve_binomials(3, twisted2, puretopdim=True)
for solmap in maps:
p... |
class TrainData(tx.data.DatasetBase[(Example, Example)]):
def __init__(self, hparams=None, device: Optional[torch.device]=None):
self._hparams = HParams(hparams, self.default_hparams())
data_source = TrainDataSource(self._hparams.dataset.files, compression_type=self._hparams.dataset.compression_type... |
class U_Net_F_v2(nn.Module):
def __init__(self, img_ch=3, output_ch=1):
super(U_Net_F_v2, self).__init__()
self.Maxpool = nn.MaxPool2d(kernel_size=2, stride=2)
self.Conv1 = conv_block(ch_in=img_ch, ch_out=32)
self.Conv2 = conv_block(ch_in=32, ch_out=64)
self.Conv3 = conv_bloc... |
def vis():
def vis_mesh(mesh, include_wireframe=False, **kwargs):
from util3d.mayavi_vis import vis_mesh as vm
(v, f) = (np.array(mesh[k]) for k in ('vertices', 'faces'))
vm(v, f, include_wireframe=include_wireframe, **kwargs)
example_ids = list(get_example_ids(cat_id, 'eval'))
rando... |
class DatasetFactory(object):
def __init__(self):
pass
def get_by_name(dataset_name, opt, is_for_train):
if (dataset_name == 'ProcessedVideo'):
from .processed_video_dataset import ProcessedVideoDataset
dataset = ProcessedVideoDataset(opt, is_for_train)
elif (data... |
def parse_tuning_line(line, tmp):
tuning_strategy = re.search('Tuning strategy:\\s+([A-Za-z]+)', line)
if (tuning_strategy and tuning_strategy.group(1)):
tmp['strategy'] = tuning_strategy.group(1)
baseline_acc = re.search('FP32 baseline is:\\s+\\[Accuracy:\\s(\\d+(\\.\\d+)?), Duration \\(seconds\\):... |
class CycleGANDataset(data.Dataset):
def __init__(self, root, regexp, transform=None, target_transform=None, download=False):
self.root = root
self.transform = transform
self.target_transform = target_transform
(self.image_paths, self.labels) = self.find_images(regexp)
def find_i... |
def wave_feature_extraction(wav_file, sr):
(y, sr) = librosa.load(wav_file, sr)
(y, _) = librosa.effects.trim(y, top_db=20)
return y |
class CamembertTokenizer(PreTrainedTokenizer):
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 = ['attention_mask']
def __init__(self, vocab_file, bos_token='<s>', eos_token... |
def progress(self, message, *args, **kws):
if self.isEnabledFor(PROGRESS_LEVEL_NUM):
self._log(PROGRESS_LEVEL_NUM, message, args, **kws) |
class ConcatDataset(_ConcatDataset):
def get_idxs(self, idx):
dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx)
if (dataset_idx == 0):
sample_idx = idx
else:
sample_idx = (idx - self.cumulative_sizes[(dataset_idx - 1)])
return (dataset_idx, sample_... |
def autodoc_skip_member(app, what, name, obj, skip, options):
if getattr(obj, '__HIDE_SPHINX_DOC__', False):
return True
if (name in _DEPRECATED_NAMES):
return True
return None |
def shard_selection(shards, distributed_info=None):
if (distributed_info is not None):
(gr, ws) = distributed_info
if (len(shards) < ws):
warnings.warn('There are not enough shards.')
warnings.warn('Some data will be duplicated!')
ws = len(shards)
gr =... |
def build_dictionary(text):
wordcount = OrderedDict()
for cc in text:
words = cc.split()
for w in words:
if (w not in wordcount):
wordcount[w] = 0
wordcount[w] += 1
words = wordcount.keys()
freqs = wordcount.values()
sorted_idx = numpy.argsort(... |
def learning_rate_decay(init_lr, global_step, warmup_steps=4000.0):
step = tf.cast((global_step + 1), dtype=tf.float32)
return ((init_lr * (warmup_steps ** 0.5)) * tf.minimum((step * (warmup_steps ** (- 1.5))), (step ** (- 0.5)))) |
class Cifar10SemiSupervisedDatasetInterface(SemiDataSetInterface):
def __init__(self, data_root: str=DATA_PATH, labeled_sample_num: int=4000, seed: int=0, batch_size: int=10, labeled_batch_size: int=None, unlabeled_batch_size: int=None, val_batch_size: int=None, shuffle: bool=False, num_workers: int=1, pin_memory: ... |
def _RCMatch_composeAll(self, *, maximum=False, verbose=False):
return _unwrap(_RCMatch_composeAll_orig(self, maximum, verbose)) |
def parse_args():
parser = argparse.ArgumentParser(description='Create density figure')
parser.add_argument('--datasets', nargs='+', required=True, help='Datasets to use for density figure')
parser.add_argument('--output_file', required=True, type=Path, help='The jpg file to save the plot')
parser.add_a... |
_tf2
class TestSeq2Seq(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_seq2seq_fit_predict_evaluate(self):
(train_data, test_data) = create_data()
model = model_creator(config={'input_feature_num': 10, 'output_feature_num': 2, 'future_seq_len': test_data[(-... |
def nor_priors(priors):
(new_upriors, new_rpriors, new_ppriors) = priors
ranked_upriors = [(user, new_upriors[user]) for user in new_upriors.keys()]
ranked_upriors = sorted(ranked_upriors, reverse=True, key=(lambda x: x[1]))
ranked_rpriors = [(user, new_rpriors[user]) for user in new_rpriors.keys()]
... |
def compute_new_gpu_util(current_gpu_util, slo, arrival_rate, avg_latency, avg_throughput):
residual_latency = (slo - avg_latency)
residual_throughput = (avg_throughput - arrival_rate)
diff_latency = ((residual_latency * 100) / slo)
diff_throughput = ((residual_throughput * 100) / arrival_rate)
if (... |
def to_ram(ale):
ram_size = ale.getRAMSize()
ram = np.zeros(ram_size, dtype=np.uint8)
ale.getRAM(ram)
return ram |
.parametrize('workers_per_gpu', (0, 2))
.parametrize(('valid', 'env_cfg'), [(True, dict(mp_start_method='fork', opencv_num_threads=0, omp_num_threads=1, mkl_num_threads=1)), (False, dict(mp_start_method=1, opencv_num_threads=0.1, omp_num_threads='s', mkl_num_threads='1'))])
def test_setup_multi_processes(workers_per_gp... |
def run_asr(asr_dir, split, w2v_ckpt, w2v_label, res_dir):
cmd = ['python', '-m', 'examples.speech_recognition.infer']
cmd += [str(asr_dir.resolve())]
cmd += ['--task', 'audio_finetuning', '--nbest', '1', '--quiet']
cmd += ['--w2l-decoder', 'viterbi', '--criterion', 'ctc']
cmd += ['--post-process', ... |
def load_data(args):
train_data = ImagePaths(args.dataset_path, size=256)
train_loader = DataLoader(train_data, batch_size=args.batch_size, shuffle=False)
return train_loader |
class TestLinformerAttention():
.parametrize('device', ['cpu', 'cuda'])
.parametrize('softmax_temp', [None, 1.0, 0.235])
.parametrize('share_kv', [False, True])
.parametrize('proj_dim_k', [13, 47, 88])
.parametrize('seq_len', [127, 28, 468])
def test_output(self, seq_len, proj_dim_k, share_kv, s... |
def get_parser():
parser = argparse.ArgumentParser(description='Cumulative Reasoning')
parser.add_argument('--temperature', type=float, default=0.0, help='temperature')
parser.add_argument('--majoritycnt', type=int, choices=range(1, 101), default=1, help='numbers of majority voting times')
parser.add_ar... |
def test_record_breaking_render_method():
env = BrokenRecordableEnv()
rec = VideoRecorder(env)
rec.capture_frame()
rec.close()
assert rec.empty
assert rec.broken
assert (not os.path.exists(rec.path)) |
_torch
_retrieval
class RagModelSaveLoadTests(unittest.TestCase):
def get_rag_config(self):
question_encoder_config = AutoConfig.from_pretrained('facebook/dpr-question_encoder-single-nq-base')
generator_config = AutoConfig.from_pretrained('facebook/bart-large-cnn')
return RagConfig.from_ques... |
class BiLSTM(nn.Module):
def __init__(self, in_channel=1, out_channel=10):
super(BiLSTM, self).__init__()
self.hidden_dim = 64
self.kernel_num = 16
self.num_layers = 2
self.V = 5
self.embed1 = nn.Sequential(nn.Conv2d(in_channel, self.kernel_num, kernel_size=3, padding... |
def make_env_and_dataset(env_name: str, seed: int) -> Tuple[(gym.Env, D4RLDataset)]:
env = gym.make(env_name)
env = wrappers.EpisodeMonitor(env)
env = wrappers.SinglePrecision(env)
env.seed(seed)
env.action_space.seed(seed)
env.observation_space.seed(seed)
dataset = D4RLDataset(env)
if (... |
class TrialTreeMulti():
def __init__(self, trial_fn, varmults, numconfigs):
self.trial_fn = trial_fn
self.varmults = varmults
self.numconfigs = numconfigs
def __call__(self, *args, **kwargs):
trial = self.trial_fn(*args, **kwargs)
tree = trial['tree']
if (not isin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.