code stringlengths 101 5.91M |
|---|
class rm_vlc_upload(StreamUpload):
mode = hl2ss.StreamMode.MODE_1
profile = hl2ss.VideoProfile.H264_MAIN
bitrate = ((3 * 1024) * 1024)
gop_size = hl2ss.get_gop_size(profile, hl2ss.Parameters_RM_VLC.FPS)
def create_client(self):
return hl2ss.rx_rm_vlc(self.host, self.port, hl2ss.ChunkSize.RM_... |
class BasicConv3d(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride, padding=0):
super(BasicConv3d, self).__init__()
self.conv = nn.Conv3d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, bias=False)
self.bn = nn.BatchNorm3d(out_planes, ... |
_model
def seresnet34(pretrained=False, **kwargs):
model_args = dict(block=BasicBlock, layers=[3, 4, 6, 3], block_args=dict(attn_layer='se'), **kwargs)
return _create_resnet('seresnet34', pretrained, **model_args) |
def move_file_to_dir_url(url_file, path_read, file_to_write):
with open(url_file, 'r', encoding='utf-8') as fd:
lines = fd.read().splitlines()
url_names = get_url_hashes(lines)
print('len of urls {}'.format(len(url_names)))
url_names = [os.path.join(path_read, url) for url in url_names]
... |
def get_parser(allow_policy_list=False):
parser = argparse.ArgumentParser()
parser.add_argument('--config', type=str)
parser.add_argument('--log-dir', type=str, default=None)
parser.add_argument('--checkpoint-replay-pool', type=(lambda x: bool(strtobool(x))), default=None, help="Whether a checkpoint sho... |
def main():
parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]), formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__)
parser.add_argument('input', help='XML wiki dump file')
groupO = parser.add_argument_group('Output')
groupO.add_argument('-o', '--output', default='... |
def load_json_string(cont):
cont = jsmin.jsmin(cont)
cont = re.sub(',[ \t\r\n]*}', '}', cont)
cont = re.sub((',[ \t\r\n]*' + '\\]'), ']', cont)
return json.loads(cont) |
class RSICD(torch.utils.data.Dataset):
splits = ['train', 'val', 'test']
def __init__(self, root: str='.data/rsicd', split: str='train', transform: T.Compose=T.Compose([T.ToTensor()])):
assert (split in self.splits)
self.root = root
self.transform = transform
self.captions = self... |
class RandomFourierFeatureKernel(AbstractSpectralKernel):
def __init__(self, measure, manifold):
super().__init__(measure, manifold)
manifold.generate_lb_eigenspaces(measure)
point = self.manifold.id
self.normalizer = self.forward(point, point, normalize=False)[(0, 0)]
def comput... |
class GraphConvolution(Layer):
def __init__(self, input_dim, output_dim, adj, dropout=0.0, act=tf.nn.relu, **kwargs):
super(GraphConvolution, self).__init__(**kwargs)
with tf.variable_scope((self.name + '_vars')):
self.vars['weights'] = weight_variable_glorot(input_dim, output_dim, name=... |
def get_bond_between_indx_atoms(mol, idx_start, idx_end) -> float:
bnd = mol.GetBondBetweenAtoms(idx_start, idx_end)
bnd = (bnd.GetBondTypeAsDouble() if (bnd is not None) else 0.0)
return bnd |
def get_index(span):
for (idx, s) in enumerate(span.doc.sents):
if (span == s):
return idx |
class TextTransformer(Preprocessing):
def __init__(self, bigdl_type='float', *args):
super(TextTransformer, self).__init__(bigdl_type, *args)
def transform(self, text_feature):
res = callZooFunc(self.bigdl_type, 'transformTextFeature', self.value, text_feature.value)
return TextFeature(j... |
class TileLabelInterleaver(StyleGAN2Interleaver):
def __init__(self, tile_labels: str, resolution: Any=None, xflip: Any=None, labels: Any=None, **kwargs: Any) -> None:
super().__init__(labels=tile_labels, **kwargs)
self._process_labels_df()
if (not isinstance(self.labels, pd.DataFrame)):
... |
class TID2013Folder(data.Dataset):
def __init__(self, root, index, transform, patch_num):
refpath = os.path.join(root, 'reference_images')
refname = getTIDFileName(refpath, '.bmp.BMP')
txtpath = os.path.join(root, 'mos_with_names.txt')
fh = open(txtpath, 'r')
imgnames = []
... |
def make_schema_copying_data_provider(data_sources_source, data_sources_target, data_sources_schema, reader=tf.TextLineReader, num_samples=None, source_delimiter=' ', target_delimiter=' ', **kwargs):
(dataset_source, dataset_schemas) = _make_copying_data_provider_base(data_sources_source, data_sources_schema, reade... |
def ReadLexicon(lexicon_file_handle):
lexicon = set()
if lexicon_file_handle:
for line in lexicon_file_handle.readlines():
splits = line.strip().split()
if (len(splits) == 0):
continue
if (len(splits) < 2):
raise Exception((('Invalid fo... |
class DistStereoVisHook(DistVisHook):
def visualize(self, runner, results):
for result in results:
if (result is None):
continue
for key in result.keys():
runner.log_buffer.output[key] = result[key]
log_str = 'Epoch [{}] Visualization Finished!... |
def training_2nd_item_task_fbne(model, sess):
best_loss = 0
saver = tf.train.Saver()
data_train = fbne_data.Dataset(setting.oracle_training_file_item_task)
train_batches = data_train.get_positive_instances_item_task(0, 'train')
num_batch_train = ((data_train.oracle_num_items // setting.batch_size_it... |
class TFElectraForMultipleChoice():
def __init__(self, *args, **kwargs):
requires_tf(self)
def from_pretrained(self, *args, **kwargs):
requires_tf(self) |
class FullGrad():
def __init__(self, model, im_size=(3, 224, 224)):
self.model = model
self.im_size = ((1,) + im_size)
self.model_ext = FullGradExtractor(model, im_size)
self.biases = self.model_ext.getBiases()
self.checkCompleteness()
def checkCompleteness(self):
... |
def resnet152(pretrained: bool=False, **kwargs: Any) -> ResNet:
return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, **kwargs) |
_auth
def fetch_accounts(filters, url, auth_headers):
endpoint = f'{url}/api/v1/accounts/'
r = requests.get(endpoint, headers=auth_headers, params=filters)
if (r.status_code != 200):
r.raise_for_status()
return json.loads(r.text)['results'] |
def conv(x, channels, kernel=4, stride=2, pad=0, use_bias=True, scope='conv_0'):
with tf.variable_scope(scope):
x = tf.pad(x, [[0, 0], [pad, pad], [pad, pad], [0, 0]])
x = tf.layers.conv2d(inputs=x, filters=channels, padding='same', kernel_size=kernel, kernel_initializer=tf.contrib.layers.xavier_ini... |
def to_bytes(string):
if (sys.hexversion > ):
return bytes(string, 'utf-8')
return string |
def preprocess_buys(path=DATA_PATH, file=DATA_FILE, path_proc=DATA_PATH_PROCESSED, version=VERSION):
(data, buys) = load_data((path + file), version)
store_buys(buys, (path_proc + file)) |
def vgg11(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> VGG:
return _vgg('vgg11', 'A', False, pretrained, progress, **kwargs) |
class SmoothCrossEntropyLoss(_Loss):
__constants__ = ['label_smoothing', 'vocab_size', 'ignore_index', 'reduction']
def __init__(self, label_smoothing, vocab_size, ignore_index=(- 100), reduction='mean', is_logits=True):
assert (0.0 <= label_smoothing <= 1.0)
super().__init__(reduction=reduction... |
def judge_is_nan(list_of_np_or_tensor):
for m in list_of_np_or_tensor:
if hasattr(m, 'numpy'):
if np.any(np.isnan(m.numpy())):
print(list_of_np_or_tensor)
raise ValueError
elif np.any(np.isnan(m)):
print(list_of_np_or_tensor)
raise ... |
def main():
writer = SummaryWriter()
(finetune_args, training_args) = HfArgumentParser((FinetuneArguments, TrainingArguments)).parse_args_into_dataclasses()
model = AutoModel.from_pretrained('THUDM/chatglm-6b', load_in_8bit=True, trust_remote_code=True, device_map='auto', torch_dtype=torch.float16)
mode... |
def transform_finished_strategies_to_hebo(space, opt_lib_group, finished_strategies, included_opts=[]):
opt_to_group_hash = {}
for (group_name, opt_candidates) in opt_lib_group.items():
for opt_name in opt_candidates:
assert (not (opt_name in opt_to_group_hash.keys())), 'We should not have d... |
class ConLL2003Standardiser(SpanAnnotator):
def __init__(self):
super(ConLL2003Standardiser, self).__init__('')
def __call__(self, doc):
for source in doc.spans:
new_spans = []
for span in doc.spans[source]:
if ('\n' in span.text):
cont... |
def make_env(with_ns: bool, PATHS: dict, PARAMS: dict, log: bool=False, max_steps: int=1000):
def _init():
ns = (f'eval_sim' if with_ns else '')
env = GazeboEnv(ns, PARAMS['reward_fnc'], PARAMS['discrete_action_space'], goal_radius=0.05, max_steps_per_episode=max_steps, train_mode=False, task_mode='... |
def DeeplabMulti(pretrained=True, num_classes=21):
model = ResNetMulti(Bottleneck, [3, 4, 23, 3], num_classes)
if pretrained:
saved_state_dict = model_zoo.load_url(RESTORE_FROM)
new_params = model.state_dict().copy()
for i in saved_state_dict:
i_parts = i.split('.')
... |
def saliency_map_gradient(numpy_image, model, attr_func):
img_tensor = torch.from_numpy(numpy_image)
img_tensor.requires_grad_(True)
result = model(_add_batch_one(img_tensor))
target = attr_func(result)
target.backward()
return (img_tensor.grad.numpy(), result) |
class LeNet5Base(nn.Module):
def __init__(self, num_classes):
super(LeNet5Base, self).__init__()
self.conv_part = nn.Sequential(nn.Conv2d(1, 20, kernel_size=5), nn.ReLU(True), nn.MaxPool2d(kernel_size=2), nn.Conv2d(20, 50, kernel_size=5), nn.ReLU(True), nn.MaxPool2d(kernel_size=2))
self.fc_p... |
def download_url(url, dst):
from six.moves import urllib
print('* url="{}"'.format(url))
print('* destination="{}"'.format(dst))
def _reporthook(count, block_size, total_size):
global start_time
if (count == 0):
start_time = time.time()
return
duration = (... |
class DomainNetDataset(Dataset):
all_domains = ['clipart', 'infograph', 'painting', 'quickdraw', 'real', 'sketch']
resorted_domains = {0: ['real', 'clipart', 'infograph', 'painting', 'quickdraw', 'sketch'], 1: ['clipart', 'infograph', 'painting', 'quickdraw', 'sketch', 'real'], 2: ['infograph', 'painting', 'qui... |
_model
def nfnet_f0(pretrained=False, **kwargs):
return _create_normfreenet('nfnet_f0', pretrained=pretrained, **kwargs) |
def _resample(img, class_info, magnitude):
x = img
m = float_parameter(magnitude, 1)
noise = torch.randn(img.size()).cuda()
x_hat = (x + ((noise * class_info['sd'].cuda()) * m))
return (x_hat, []) |
def ApplyFont(ax):
ticks = (ax.get_xticklabels() + ax.get_yticklabels())
text_size = 14.0
for t in ticks:
t.set_fontname('Times New Roman')
t.set_fontsize(text_size)
txt = ax.get_xlabel()
txt_obj = ax.set_xlabel(txt)
txt_obj.set_fontname('Times New Roman')
txt_obj.set_fontsiz... |
def parse_log(log_path):
with open(log_path, 'r') as f:
log = f.read().splitlines()
results = {}
if (('limit-annos' in str(log_path)) and ('keypoints' in str(log_path))):
metrics = {'mean_iod'}
expected_occurences = 1
elif ('keypoints' in str(log_path)):
metrics = {'iod'}... |
class RobertaConfig(PretrainedConfig):
model_type = 'roberta'
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=512, type_vocab_size=2, ... |
def create_testing_dataset_files(name_to_prepend, dataset, reactants_to_reactant_id_dict):
print(f'Going through dataset {name_to_prepend}')
reactants_interested_in_set = set(reactants_to_reactant_id_dict.keys())
reactant_bags = []
corresponding_products = []
unreachable_reactants = []
unreachab... |
def get_tens_mem(tensor):
if torch.is_tensor(tensor):
a = (tensor.element_size() * tensor.nelement())
else:
a = 0
tensor_memory = round((a / 1048576), 4)
return tensor_memory |
class EnvDiscrete(EnvFeature):
def __init__(self, code='000001', day='', data_norm=True, latency=1, T=50, wo_lob_state=False, wo_market_state=False, wo_agent_state=False, wo_dampened_pnl=False, wo_matched_pnl=False, wo_inv_punish=False, **kwargs):
super().__init__(**kwargs)
print('Environment: EnvDi... |
def reshape_patch_back(patch_tensor, patch_size):
assert (5 == patch_tensor.ndim)
batch_size = np.shape(patch_tensor)[0]
seq_length = np.shape(patch_tensor)[1]
patch_height = np.shape(patch_tensor)[2]
patch_width = np.shape(patch_tensor)[3]
channels = np.shape(patch_tensor)[4]
img_channels =... |
.slow
def test_correlated_samples():
(nsamples, nchains) = _get_sample_size()
decay_factor = 0.9
correlated_samples = _construct_correlated_samples(nsamples, nchains, decay_factor)
(autocorr_curve, _) = statistics.multi_chain_autocorr_and_variance(correlated_samples)
tau = statistics.tau(autocorr_cu... |
def gender_cla(ref, pred):
(ref, pred) = (ref.lower(), pred.lower())
if (('female' in ref) and ('female' in pred)):
return True
elif (('female' not in ref) and ('female' not in pred)):
return True
else:
return False |
_module()
class Mask2FormerHead(MaskFormerHead):
def __init__(self, in_channels: List[int], feat_channels: int, out_channels: int, num_things_classes: int=80, num_stuff_classes: int=53, num_queries: int=100, num_transformer_feat_level: int=3, pixel_decoder: ConfigType=..., enforce_decoder_input_project: bool=False,... |
def rouge_score(preds, golds):
rouge_results = {}
rouge1 = []
rouge2 = []
rougeL = []
for (srcs, tgts) in zip(preds, golds):
references = ' '.join(tgts)
predictions = ' '.join(srcs)
res = rougeScore(predictions, references)
rouge1.append(res['rouge1_fmeasure'])
... |
def clustered_broadcast(Y, groups, counts, factors, X=None):
device = Y.device
if (X is None):
X = torch.zeros((groups.shape + (Y.shape[(- 1)],)), device=device, dtype=Y.dtype)
if (device.type == 'cpu'):
broadcast_cpu(Y, groups, factors, X)
else:
(N, H, C, E) = Y.shape
(_... |
class NNCG():
root_node: Edge = None
test_nodes: List[KerasLayerNode] = []
def __init__(self):
self.id = ''
self.test_nodes = []
self.testing = None
self.model = None
self.min_in = 0
self.max_in = 0
def keras_compile(self, imdb, model, code_path, identifie... |
def get_scheduler(args):
if (args.sched in ['multistep', 'cosine', 'linear', 'exponential', 'uneven_multistep']):
return LrScheduler(args)
else:
raise NotImplementedError('The scheduler {} is not implemented! Please choose from [multistep, cosine, linear, exponential]'.format(args.scheduler)) |
class MyModelCannotComputeOutputShape(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense = tf.keras.layers.Dense(4, activation=tf.nn.relu)
def call(self, inputs):
return self.dense(inputs)
def compute_output_shape(self, input_shape):
raise NotImplementedError(... |
class VehiclePIDController():
def __init__(self, vehicle, args_lateral, args_longitudinal, offset=0, max_throttle=0.75, max_brake=0.3, max_steering=0.8):
self.max_brake = max_brake
self.max_throt = max_throttle
self.max_steer = max_steering
self._vehicle = vehicle
self._world... |
class ModelArguments():
model_name_or_path: str = field()
new_adapter_name: str = field(default=None) |
def test_target_pipe(X_iris, y_iris) -> None:
X_types = {'continuous': ['sepal_length', 'sepal_width', 'petal_length'], 'confounds': ['petal_width']}
target_pipeline = TargetPipelineCreator().add('confound_removal', confounds=['confounds', 'continuous'])
pipeline_creator = PipelineCreator(problem_type='regr... |
class DeepONet(NN):
def __init__(self, layer_sizes_branch, layer_sizes_trunk, activation, kernel_initializer):
super().__init__()
if isinstance(activation, dict):
activation_branch = activations.get(activation['branch'])
self.activation_trunk = activations.get(activation['tru... |
class QueryDataset(Dataset):
def __init__(self, tokenizer: PreTrainedTokenizer, qrel_path: str, query_path: str, max_query_len: int, index_doc_ids: np.ndarray, rel_threshold=1, verbose=True):
super().__init__()
self.tokenizer = tokenizer
docid2offset = dict(((str(docid), idx) for (idx, docid... |
def pixelAccuracy(imPred, imLab):
pixel_labeled = np.sum((imLab >= 0))
pixel_correct = np.sum(((imPred == imLab) * (imLab >= 0)))
pixel_accuracy = ((1.0 * pixel_correct) / pixel_labeled)
return (pixel_accuracy, pixel_correct, pixel_labeled) |
class DynamicGraphConvolution(nn.Module):
def __init__(self, in_features, out_features, num_nodes):
super(DynamicGraphConvolution, self).__init__()
self.static_adj = nn.Sequential(nn.Conv1d(num_nodes, num_nodes, 1, bias=False), nn.LeakyReLU(0.2))
self.static_weight = nn.Sequential(nn.Conv1d(... |
def attack_success(cleancrop, x, initial_pic, target_class, searchspace, sticker, opstickercv, magnification, zstore, facemask, targeted_attack=False):
(attack_image, valid) = predict.perturb_image(x, initial_pic, sticker, opstickercv, magnification, zstore, searchspace, facemask)
(rank, _) = eval('predict.pred... |
def load_tf_weights_in_gpt_neo(*args, **kwargs):
requires_backends(load_tf_weights_in_gpt_neo, ['torch']) |
class _append_return_to_pipe(object):
def __init__(self, func):
self.func = func
def __call__(self, queue, *args, **kwargs):
res = self.func(*args, **kwargs)
queue.put(res) |
def test_tuple():
assert (_make_annotation_str_for_obj(()) == 'Tuple')
assert (_make_annotation_str_for_obj((3, 4)) == 'Tuple[int, int]')
assert (_make_annotation_str_for_obj((3, 4, 5.0)) == 'Tuple[int, int, float]')
assert (_make_annotation_str_for_obj((3, 4, 5, 6)) == 'Tuple[int, ...]')
assert (_m... |
def test_stochastic_network_4(net):
net.add_connections_between(['A'], ['B'], rate=0.0)
assert (not net.graph.has_edge('A', 'B'))
net.resample_connectivity()
assert (not net.graph.has_edge('A', 'B')) |
def playback_dataset(args):
write_video = (args.video_path is not None)
assert (not (args.render and write_video))
if (args.render_image_names is None):
env_meta = FileUtils.get_env_metadata_from_dataset(dataset_path=args.dataset)
env_type = EnvUtils.get_env_type(env_meta=env_meta)
a... |
def test_two_sided_pval_from_pval():
pval = np.asarray([1.0, 0.025, 0.5])
one_minus_pval = np.asarray([0.0, 0.975, 0.5])
(two_sided_pval, two_sided_pval_corr) = two_sided_pval_from_pval(pval, one_minus_pval)
expected = np.asarray([[0.0, 0.05, 1.0], [0.0, 0.15, 1.0]])
assert_almost_equal(two_sided_pv... |
class Attention_50(nn.Module):
def __init__(self):
super(Attention_50, self).__init__()
self.name = 'Attention_50'
self.lr = 0.0008
self.n_hosts = 50
self.n_feats = (3 * self.n_hosts)
self.n_window = 3
self.n_latent = 10
self.n_hidden = 16
self... |
def get_raytune_search_alg(raytune_cfg, seeds=False):
if ((raytune_cfg['sched'] == 'pbt') or (raytune_cfg['sched'] == 'pb2')):
if (raytune_cfg['search_alg'] is not None):
print("INFO: Using schedule '{}' is not compatible with Ray Tune search algorithms.".format(raytune_cfg['sched']))
... |
class QuantitativeClassifier():
def __init__(self, rules, default_class):
self.rules = rules
self.default_class = default_class
def rule_model_accuracy(self, quantitative_dataframe, ground_truth):
predicted = self.predict(quantitative_dataframe)
return accuracy_score(predicted, g... |
def gaussian_square(times: np.ndarray, amp: complex, center: float, width: float, sigma: float, zeroed_width: Union[(None, float)]=None) -> np.ndarray:
square_start = (center - (width / 2))
square_stop = (center + (width / 2))
if zeroed_width:
zeroed_width = min(width, zeroed_width)
gauss_ze... |
class PipeGradScaler(GradScaler):
def __init__(self, init_scale=(2.0 ** 16), growth_factor=2.0, backoff_factor=0.5, growth_interval=2000, enabled=True, process_group='pipe', stage_id=None):
super().__init__(init_scale=init_scale, growth_factor=growth_factor, backoff_factor=backoff_factor, growth_interval=gr... |
(config_path='./confs', config_name='gala', version_base='1.1')
def main(opt):
pl.seed_everything(0)
model = NeRFModel.load_from_checkpoint('model.ckpt')
datamodule = hydra.utils.instantiate(opt.dataset, train=False)
trainer = pl.Trainer(accelerator='gpu', **opt.trainer_args)
result = trainer.test(m... |
def DenseNet201(include_top=False, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000, **kwargs):
return DenseNet([6, 12, 48, 32], include_top, weights, input_tensor, input_shape, pooling, classes, **kwargs) |
class _DenseBlock(nn.Sequential):
def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate):
super(_DenseBlock, self).__init__()
for i in range(num_layers):
layer = _DenseLayer((num_input_features + (i * growth_rate)), growth_rate, bn_size, drop_rate)
... |
def rotate_mesh_for_webview(meshes):
verts_packed = meshes.verts_packed()
faces_list = meshes.faces_list()
tex = meshes.textures
rot_matrix = torch.FloatTensor(np.linalg.inv(np.array([[1, 0, 0], [0, 0.9816272, (- 0.190809)], [0, 0.190809, 0.9816272]])))
verts_packed = torch.mm(rot_matrix, verts_pack... |
def write_config_files(config_dir, all_layers):
config_basename_to_lines = defaultdict(list)
config_basename_to_header = get_config_headers()
for layer in all_layers:
try:
pairs = layer.get_full_config()
for (config_basename, line) in pairs:
config_basename_to... |
def latitude_and_longitude_convert_to_decimal_system(*arg):
return (float(arg[0]) + ((float(arg[1]) + ((float(arg[2].split('/')[0]) / float(arg[2].split('/')[(- 1)])) / 60)) / 60)) |
def snapshotToMovie(snap, filename, *args, **kwargs):
if kwargs.has_key('tmpdir'):
tmpdir = kwargs['tmpdir']
kwargs.pop('tmpdir')
else:
tmpdir = '/tmp'
if kwargs.has_key('framerate'):
framerate = kwargs['framerate']
kwargs.pop('framerate')
else:
framerate ... |
def generate_urban_atlas_boundaries():
ua_bounds = [(ua.split('_')[(- 1)], gpd.read_file((((UA_DIR + ua) + '/Shapefiles/') + x)).geometry.values[0]) for ua in os.listdir(UA_DIR) for x in os.listdir(((UA_DIR + ua) + '/Shapefiles/')) if x.endswith('_UA2012_Boundary.shp')]
ua_gdf = gpd.GeoDataFrame(ua_bounds, colu... |
class RTFMAbstractEnv(RTFMEnv):
def __init__(self, room_size=6):
super(RTFMAbstractEnv, self).__init__(room_size)
self.nb_physical = (self.world.height * self.world.width)
self.nb_entities = (self.nb_physical + len(self.abstract_entities))
self.entity2idx = {entity: (self.nb_physical... |
class eca_layer(nn.Module):
def __init__(self, channel, k_size=3):
super().__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.conv = nn.Conv1d(1, 1, kernel_size=k_size, padding=((k_size - 1) // 2), bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
y = sel... |
def _load_checkpoint(checkpoint_path, model, optimizer, scheduler, logger, distributed):
print('loading from a checkpoint at {}'.format(checkpoint_path))
if distributed:
checkpoint_state = torch.load(checkpoint_path, map_location=(lambda storage, loc: storage))
else:
checkpoint_state = torch... |
(events=subsets(_ALL_EVENTS_WITH_HANDLERS))
_events_with_registered_handlers_to_subset
def test_for_loop_nested_in_while_loop(events):
assert (_RECORDED_EVENTS == [])
run_cell('\n i = 0\n while i < 10:\n for j in range(2):\n i += 1\n ')
throw_and_print_diff_if_... |
def get_rouge(hypotheses, reference, sent_split=True, use_cf=False):
assert (len(hypotheses) == len(reference))
assert (len(hypotheses) > 0)
hyps = []
refs = []
for (hyp, ref) in zip(hypotheses, reference):
hyp = ' '.join(hyp)
ref = ' '.join(ref)
if sent_split:
hs... |
def FuseGTestH(gtest_root, output_dir):
output_file = open(os.path.join(output_dir, GTEST_H_OUTPUT), 'w')
processed_files = set()
def ProcessFile(gtest_header_path):
if (gtest_header_path in processed_files):
return
processed_files.add(gtest_header_path)
for line in open(... |
def generate_labels(img_info, detail_api, out_dir):
def _class_to_index(mask, _mapping, _key):
values = np.unique(mask)
for i in range(len(values)):
assert (values[i] in _mapping)
index = np.digitize(mask.ravel(), _mapping, right=True)
return _key[index].reshape(mask.shap... |
class VecEnv(ABC):
closed = False
viewer = None
metadata = {'render.modes': ['human', 'rgb_array']}
def __init__(self, num_envs, observation_space, action_space):
self.num_envs = num_envs
self.observation_space = observation_space
self.action_space = action_space
def reset(se... |
class GCRN(nn.Module):
input_dim: int
feature_dim: int
hidden_dim: int
output_dim: int
feature_pre: bool
layer_num: int
dropout: float
duration: int
rnn_type: str
bias: bool
method_name: str
def __init__(self, input_dim, feature_dim, hidden_dim, output_dim, feature_pre=Tr... |
class FunnelBaseModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
_grad()
def test(model, xs, y_true, evaluator):
model.eval()
y_preds = []
loader = DataLoader(range(y_true.size(0)), batch_size=400000)
for perm in loader:
y_pred = model([x[perm] for x in xs]).argmax(dim=(- 1), keepdim=True)
y_preds.append(y_pred.cpu())
y_pred = torch.cat(y_preds, d... |
class SensorManager(Singleton):
def __init__(self, param_dict):
self.param_dict = param_dict
self.sensor_dict = {}
self.known_sensors = ['camera', 'lidar', 'imu', 'gps']
def init(self, key):
if (key in self.param_dict):
sensor_type = self.get_type(key)
if ... |
class BaseModel():
def __init__(self, model, fp16=False, device='cuda', max_batch_size=16, embedding_dim=768, text_maxlen=77):
self.model = model
self.name = 'SD Model'
self.fp16 = fp16
self.device = device
self.min_batch = 1
self.max_batch = max_batch_size
se... |
def node_label_and_degree_worker(G, node_map):
freq = np.zeros(len(node_map))
for u in G.nodes():
freq[node_map[(G.degree[u], G.nodes[u]['label'])]] += 1
return freq |
class ContinuousMLPBaseline(Baseline):
def __init__(self, env_spec, num_seq_inputs=1, regressor_args=None, name='ContinuousMLPBaseline'):
super().__init__(env_spec)
if (regressor_args is None):
regressor_args = dict()
self._regressor = ContinuousMLPRegressor(input_shape=((env_spe... |
def get_linear_layer(input_dim: int, output_dim: int, weight_norm=False, initializer: Initializer=Initializer.Xavier_uniform, *args, **kwargs):
layer = torch.nn.Linear(input_dim, output_dim)
init_method = InitializerFactory.get_initializer(initializer=initializer, **kwargs)
init_method(layer.weight)
tor... |
def compute_contracted(ilegs, jlegs, appearances):
ip = 0
jp = 0
ni = len(ilegs)
nj = len(jlegs)
new_legs = []
while True:
if (ip == ni):
new_legs.extend(jlegs[jp:])
break
if (jp == nj):
new_legs.extend(ilegs[ip:])
break
(ii... |
class BartTokenizerFast(metaclass=DummyObject):
_backends = ['tokenizers']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tokenizers']) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.