code stringlengths 101 5.91M |
|---|
class GMDataset(Dataset):
def __init__(self, name, length, cls=None, **args):
self.name = name
self.ds = eval(self.name)(**args)
self.length = length
self.obj_size = self.ds.obj_resize
self.classes = self.ds.classes
self.cls = (None if (cls == 'none') else cls)
de... |
class WordTextEncoder(CharacterTextEncoder):
def encode(self, s):
s = s.strip('\r\n ')
words = s.split(' ')
return ([self.vocab_to_idx(v) for v in words] + [self.eos_idx])
def decode(self, idxs, ignore_repeat=False):
vocabs = []
for (t, idx) in enumerate(idxs):
... |
def getFlying3dMetas(root, Type, data_type='clean'):
Metas = []
imgDir = (('flyingthings3d/frames_' + data_type) + 'pass')
dispDir = 'flyingthings3d/disparity'
Parts = ['A', 'B', 'C']
for Part in Parts:
partDir = osp.join(root, dispDir, Type, Part)
idxDirs = os.listdir(partDir)
... |
def build_and_train(game='pong', run_ID=0, cuda_idx=None, mid_batch_reset=False, n_parallel=2):
affinity = dict(cuda_idx=cuda_idx, workers_cpus=list(range(n_parallel)))
Collector = (GpuResetCollector if mid_batch_reset else GpuWaitResetCollector)
print(f'To satisfy mid_batch_reset=={mid_batch_reset}, using ... |
def print_layers_dims(model):
l_layers = model.layers
for i in range(len(l_layers)):
print(l_layers[i])
print('Input Shape: ', l_layers[i].input_shape, 'Output Shape: ', l_layers[i].output_shape) |
class RewardModel(nn.Module):
def __init__(self, belief_size, state_size, hidden_size, activation_function='relu'):
super().__init__()
self.act_fn = getattr(F, activation_function)
self.fc1 = nn.Linear((belief_size + state_size), hidden_size)
self.fc2 = nn.Linear(hidden_size, hidden_... |
class CorrectMetric():
def __init__(self):
self.item = []
def update(self, samples):
self.item.append(samples)
def result(self):
return 0
def reset(self):
self.item = [] |
class ResNet(nn.Module):
def __init__(self, block, layers, opt):
down_stride_1 = (1, 2, 2)
down_stride_2 = (2, 2, 2)
self.inplanes = 64
self.learning_policy = opt.learning_policy
self.num_classes = opt.n_classes
num_classes = opt.n_classes
shortcut_type = opt.... |
def find_pretrained_model(src_lang: str, tgt_lang: str) -> List[str]:
prefix = 'Helsinki-NLP/opus-mt-'
model_list = list_models()
model_ids = [x.modelId for x in model_list if x.modelId.startswith('Helsinki-NLP')]
src_and_targ = [remove_prefix(m, prefix).lower().split('-') for m in model_ids if ('+' not... |
def export_mannequin(mode: str, save_stem: ty.N[str]=None, overwrite: bool=False) -> None:
print(f"-> Exporting ground truth depths for Mannequin '{mode}'...")
ds = MannequinDataset(mode, datum='image depth K', shape=None, as_torch=False)
save_file = (ds.split_file.parent / f'{save_stem}.npz')
if ((not ... |
def generate_python_wrapper(header_directories, include_paths, library_name, cpp_filename, declarations, ignore_declarations={}, ignore_files={}):
warnings.filterwarnings(action='once', category=DeprecationWarning)
(generator_path, generator_name) = utils.find_xml_generator()
compiler = 'g++'
compiler_p... |
def parse_report(report):
out = {}
result_regexp = '(\\d*)MHz\\/(\\d*)MHz.*complexity:\\s(\\d*)\\sMACC'
matches = list(re.finditer(result_regexp, report, re.MULTILINE))
(cpu_freq, cpu_freq_max, macc) = matches[0].groups()
out['cpu_mhz'] = int(cpu_freq)
out['macc'] = int(macc)
key_value_regex... |
def uniform_noise(Cifar10_Y, noise_ratio):
array1 = Cifar10_Y.tolist()
array = Cifar10_Y.tolist()
array2 = Cifar10_Y
ratio = (5 * noise_ratio)
noisy_ratio = (ratio * 10)
for class_number in range(10):
ss = array.count(class_number)
first_pos = 0
find_out = []
for ... |
class dependencyGraph(object):
def __init__(self, dep, head, tok, tgt):
self.graph = nx.DiGraph()
self.name2concept = tok
self.root = None
for (i, x) in enumerate(head):
if (x == 0):
assert (self.root is None)
self.root = i
self... |
def generate_encrypted_file(kms, primary_key_path, data_key_path, input_path, output_path):
callBigDlFunc('float', 'generateEncryptedFile', kms, primary_key_path, data_key_path, input_path, output_path) |
_registry(pattern_type='RmsNorm')
class RmsNorm(Pattern):
def __call__(self, model):
pattern_mapping_config = {'RmsNorm': [{'patterns': {'in': [[(0, 'Pow'), (1, 'ReduceMean'), (2, 'Add'), (3, 'Rsqrt'), (4, 'Mul'), (5, 'Mul')]], 'out': [[(0, 'RmsNorm')]]}, 'search_mode': 'op_type', 'node_names': {0: 5}, 'inp... |
def logTrendFn(**kwargs):
dampening = kwargs['dampening']
displacement = kwargs['displacement']
timeSteps = kwargs['timeSteps']
if ('tStart' in kwargs):
tStart = kwargs['tStart']
else:
tStart = 0
steps = range((1 + tStart), (timeSteps + 1))
return (np.log(steps) + displacemen... |
def AddConvMaxpLayer(config_lines, name, input, args):
if ('3d-dim' not in input):
raise Exception("The input to AddConvMaxpLayer() needs '3d-dim' parameters.")
input = nodes.AddConvolutionLayer(config_lines, name, input, input['3d-dim'][0], input['3d-dim'][1], input['3d-dim'][2], args.filt_x_dim, args.... |
def get_division_counts_by_season(season: Optional[int]) -> int:
if (season is None):
season = (most_recent_season() - 1)
if (season >= 1994):
return 6
if (season >= 1969):
return 4
return 1 |
class ShapleyModule(ShapleyNetwork, ABC):
def __init__(self, inner_function: nn.Module, dimensions: ModuleDimensions=None, reference_values: torch.Tensor=None) -> None:
super(ShapleyModule, self).__init__(dimensions=dimensions, reference_values=reference_values)
self.inner_function = inner_function
... |
def diapreresnet1202_cifar100(num_classes=100, **kwargs):
return get_diapreresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False, model_name='diapreresnet1202_cifar100', **kwargs) |
class IBasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1):
super(IBasicBlock, self).__init__()
if ((groups != 1) or (base_width != 64)):
raise ValueError('BasicBlock only supports groups=1 and base... |
def determine_thresholds(confidence, resolution=100):
if isinstance(confidence, list):
confidence = np.array(confidence)
confidence = confidence.flatten()
confidence = confidence[(~ np.isnan(confidence))]
confidence.sort()
assert ((len(confidence) > resolution) and (resolution > 2))
thre... |
class QuantizationLayer(tf.keras.layers.Layer):
def __init__(self):
super(QuantizationLayer, self).__init__()
def call(self, x, weight):
i = tf.transpose(tf.constant([[1, 0], [0, 1], [0, 1]], dtype='float32'))
w = tf.matmul(weight, i)
return tf.div(x, w) |
class CelebA(data.Dataset):
def __init__(self, image_dir, attr_path, selected_attrs, transform, mode):
self.image_dir = image_dir
self.attr_path = attr_path
self.selected_attrs = selected_attrs
self.transform = transform
self.mode = mode
self.train_dataset = []
... |
def update_context(context, sentence, entities):
for (idx, (ent_key, ent_vals)) in enumerate(entities.items()):
for w in sentence:
if (w in ent_vals):
context[idx] = 1 |
def analytical_leg_jacobian(leg_angles, leg_id):
l_up = 0.2
l_low = 0.2
l_hip = (0.08505 * ((- 1) ** (leg_id + 1)))
(t1, t2, t3) = (leg_angles[0], leg_angles[1], leg_angles[2])
l_eff = np.sqrt((((l_up ** 2) + (l_low ** 2)) + (((2 * l_up) * l_low) * np.cos(t3))))
t_eff = (t2 + (t3 / 2))
J = n... |
class TrainOptions(BaseOptions):
def initialize(self):
BaseOptions.initialize(self)
self.parser.add_argument('--display_freq', type=int, default=100, help='frequency of showing training results on screen')
self.parser.add_argument('--display_single_pane_ncols', type=int, default=0, help='if ... |
def include_pip(tile_type, p):
is_xc7_logic = (tile_type in ('CLBLL_L', 'CLBLL_R', 'CLBLM_L', 'CLBLM_R'))
if (p.is_route_thru() and p.src_wire().name().endswith('_CE_INT')):
return False
if (p.is_route_thru() and is_xc7_logic):
return False
if (p.is_route_thru() and ('TFB' in p.dst_wire(... |
class MostVisitedExtract(AbstractExtract):
def __call__(self, node):
nodes = [node]
while ((not node.terminal) and (len(node.children) > 0)):
visits = [(i, child.n_visits) for (i, child) in enumerate(node.children)]
(max_idx, max_num_visits) = max(visits, key=operator.itemget... |
def train_step(epoch, loss_save):
for (_, data_train_group) in tqdm(enumerate(dataloader_train), desc='Training', total=len(dataloader_train)):
model.train()
mlp.train()
for data_train in data_train_group:
vector3 = []
regularization = 0
for data_train_ite... |
class AgentIDWrapper(Wrapper):
def __init__(self, env: Environment, has_global_state: bool=False):
super().__init__(env)
self.has_global_state = has_global_state
def _add_agent_ids(self, timestep: TimeStep, num_agents: int) -> Union[(Observation, ObservationGlobalState)]:
agent_ids = jnp... |
def get_score(x):
candidate_classification = x[0]
candidate_embedding = x[1]
classScore = (1.0 if (query_classification == candidate_classification) else 0.0)
visualScore = np.dot(query_embedding, candidate_embedding)
return (classScore + visualScore) |
def has_labels(dataset_dir, filename=LABELS_FILENAME):
return tf.gfile.Exists(os.path.join(dataset_dir, filename)) |
def parse_response(response):
(func_name, func_args) = ('', '')
i = response.rfind('\nAction:')
j = response.rfind('\nAction Input:')
k = response.rfind('\nObservation:')
if (0 <= i < j):
if (k < j):
response = (response.rstrip() + '\nObservation:')
k = response.rfind('\n... |
class VideoWriter():
def __init__(self, path, frame_size, codec='FFV1', fps=30.0, color=True):
codec = cv2.VideoWriter_fourcc(*codec)
self.stream = cv2.VideoWriter(path, codec, fps, frame_size, color)
def write(self, frame):
self.stream.write(frame)
def write_batch(self, batch):
... |
class FlashDistillationConfig(object):
def __init__(self, block_names: list=[], layer_mappings_for_knowledge_transfer: list=[], loss_types: list=[], loss_weights: list=[], add_origin_loss: list=[], train_steps: list=[]):
super().__init__()
self.block_names = block_names
self.layer_mappings_f... |
def register_model_architecture(model_name, arch_name):
def register_model_arch_fn(fn):
if (model_name not in MODEL_REGISTRY):
raise ValueError('Cannot register model architecture for unknown model type ({})'.format(model_name))
if (arch_name in ARCH_MODEL_REGISTRY):
raise Va... |
class CheckingTestCases(unittest.TestCase):
def test_should_is_not_null_raise_an_exception(self) -> None:
with self.assertRaises(NoneParameterException):
Check.is_not_none(None)
def test_should_is_valid_probability_raise_an_exception_if_the_value_is_negative(self) -> None:
with self.... |
def get_dataset_mt(dataset_args: Dict[(str, str)], model: str) -> DatasetDict:
dataset = DatasetDict()
for config in dataset_args['dataset_configs']:
dataset[config] = load_dataset(dataset_args['dataset_mt'], model, split=config)
return dataset |
class _DenseLayer(nn.Module):
def __init__(self, num_input_features, growth_rate, bottleneck_width, drop_rate):
super(_DenseLayer, self).__init__()
growth_rate = int((growth_rate / 2))
inter_channel = (int(((growth_rate * bottleneck_width) / 4)) * 4)
if (inter_channel > (num_input_fe... |
class FairseqDecoder(nn.Module):
def __init__(self, dictionary):
super().__init__()
self.dictionary = dictionary
self.onnx_trace = False
def forward(self, prev_output_tokens, encoder_out=None, **kwargs):
(x, extra) = self.extract_features(prev_output_tokens, encoder_out=encoder_o... |
def train_models_alpha_num_blocks_sweep(params, alpha, num_blocks, run_ctr_start=1, name_prefix=None):
p = params
(x_train, y_train, x_test, y_test) = get_dataset(cifar10, p)
run_ctr = run_ctr_start
for a in alpha:
p.alpha = a
for nb in num_blocks:
p.num_blocks = nb
... |
def batch_norm_template(inputs, is_training, scope, moments_dims_unused, bn_decay, data_format='NHWC'):
bn_decay = (bn_decay if (bn_decay is not None) else 0.9)
return tf.contrib.layers.batch_norm(inputs, center=True, scale=True, is_training=is_training, decay=bn_decay, updates_collections=None, scope=scope, da... |
def setup_train(args):
set_up_gpu(args)
export_root = create_experiment_export_folder(args)
export_experiments_config_as_json(args, export_root)
pp.pprint({k: v for (k, v) in vars(args).items() if (v is not None)}, width=1)
return export_root |
class CondenseInitBlock(nn.Module):
def __init__(self, in_channels, out_channels):
super(CondenseInitBlock, self).__init__()
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=2, padding=1, bias=False)
def forward(self, x):
x = self.conv(x)
... |
def set_seed(seed):
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed) |
class GhostConv(nn.Module):
def __init__(self, c1, c2, k=1, s=1, g=1, act=True):
super(GhostConv, self).__init__()
c_ = (c2 // 2)
self.cv1 = Conv(c1, c_, k, s, None, g, act)
self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
def forward(self, x):
y = self.cv1(x)
return ... |
def accuracy(pr, gt, threshold=None, ignore_channels=None):
pr = _threshold(pr, threshold=threshold)
(pr, gt) = _take_channels(pr, gt, ignore_channels=ignore_channels)
tp = (torch.sum((gt == pr), dtype=pr.dtype) * 1.0)
score = (tp / gt.view((- 1)).shape[0])
return score |
def _is_float(num: str) -> bool:
try:
float(num)
return True
except ValueError:
return False |
def plot_shelf_freqz(treble, fs):
Rpot = 10000.0
C = 3.9e-09
G1 = (1.0 / 100000.0)
G2 = (1.0 / (1800.0 + ((1 - treble) * Rpot)))
G3 = (1.0 / (4700.0 + (treble * Rpot)))
G4 = (1.0 / 100000.0)
b0s = (C * (G1 + G2))
b1s = (G1 * (G2 + G3))
a0s = (C * (G3 - G4))
a1s = ((- G4) * (G2 + ... |
class Pix2PixHDGenerator(BaseNetwork):
def modify_commandline_options(parser, is_train):
parser.add_argument('--resnet_n_downsample', type=int, default=4, help='number of downsampling layers in netG')
parser.add_argument('--resnet_n_blocks', type=int, default=9, help='number of residual blocks in th... |
def shufflenet_v2_mpncov_x0_5(pretrained=False, progress=True, **kwargs):
return _shufflenetv2_mpncov('shufflenetv2_mpncov_x0.5', pretrained, progress, [4, 8, 4], [24, 48, 96, 192, 1024], **kwargs) |
def timm_rn101(**kwargs):
default_kwargs = {}
default_kwargs.update(**kwargs)
return Myrn101(**default_kwargs) |
class TestToArray(unittest.TestCase):
((platform.system().lower() == 'windows'), 'not support mxnet on windows yet')
def testParse(self):
random_array = (np.random.random_sample([10, 10, 3]) * 255)
random_array = random_array.astype(np.uint8)
img1 = Image.fromarray(random_array)
... |
_registry
class AutoMixedPrecisionTuneStrategy(TuneStrategy):
def _initialize_config(self, conf):
config = conf.mixed_precision
config.approach = getattr(config, 'approach', None)
config.recipes = getattr(config, 'recipes', {})
config.calibration_sampling_size = getattr(config, 'cali... |
def main():
args = parse(sys.argv[1:])
out_dir = os.path.join(args.results_dir, args.run)
common.ensure_directories(out_dir)
urbansound8k.maybe_download_dataset(args.datasets_dir)
data = urbansound8k.load_dataset()
folds = urbansound8k.folds(data)
exsettings = common.load_settings_path(args.... |
class Dumper():
def __init__(self, dumping_path=None, dic={}):
self.dumping_path = dumping_path
self.dic = dic
def dump(self, dict_to_dump=None, dumping_path=None):
if (dumping_path is None):
dumping_path = self.dumping_path
if (dumping_path is None):
rais... |
def add_panoptic_deeplab_config(cfg):
add_deeplab_config(cfg)
cfg.INPUT.GAUSSIAN_SIGMA = 10
cfg.INPUT.IGNORE_STUFF_IN_OFFSET = True
cfg.INPUT.SMALL_INSTANCE_AREA = 4096
cfg.INPUT.SMALL_INSTANCE_WEIGHT = 3
cfg.INPUT.IGNORE_CROWD_IN_SEMANTIC = False
cfg.SOLVER.OPTIMIZER = 'ADAM'
cfg.MODEL.... |
def get_non_dominated_solutions(solutions: List[Solution]) -> List[Solution]:
archive: Archive = NonDominatedSolutionsArchive()
for solution in solutions:
archive.add(solution)
return archive.solution_list |
def parallel(func, arr: Collection, max_workers: int=None, leave=False):
max_workers = ifnone(max_workers, defaults.cpus)
if (max_workers < 2):
results = [func(o, i) for (i, o) in progress_bar(enumerate(arr), total=len(arr), leave=leave)]
else:
with ProcessPoolExecutor(max_workers=max_worker... |
class DiscourseUnit():
def __init__(self, unq_idx, sent_idx, rel_start, rel_end):
self.unq_idx = unq_idx
self.sent_idx = sent_idx
self.original_start_in_sent = rel_start
self.original_end_in_sent = rel_end
self.raw_words = []
self.bert_word_pieces = []
self.me... |
def get_results(output_dir, split='eval'):
path = os.path.join(output_dir, f'{split}_results.json')
if os.path.exists(path):
with open(path, 'r') as f:
return json.load(f)
raise ValueError(f"can't find {path}") |
def vis_keypoints(img, kps, alpha=1):
cmap = plt.get_cmap('rainbow')
colors = [cmap(i) for i in np.linspace(0, 1, (len(kps) + 2))]
colors = [((c[2] * 255), (c[1] * 255), (c[0] * 255)) for c in colors]
kp_mask = np.copy(img)
for i in range(len(kps)):
p = (kps[i][0].astype(np.int32), kps[i][1]... |
class WindFieldClass(ABC):
def __init__(self, np_random: (None | np.random.RandomState)=None):
self.np_random = (np.random.RandomState() if (np_random is None) else np_random)
def __call__(self, time: float, position: np.ndarray) -> np.ndarray:
pass
def _check_wind_field_validity(wind_field)... |
class StratifiedBootstrap(BaseShuffleSplit):
def __init__(self, n_splits: int=5, test_size: float=0.5, train_size: Optional[float]=None, random_state: Optional[Union[(int, RandomState)]]=None):
super().__init__(n_splits=n_splits, test_size=test_size, train_size=train_size, random_state=random_state)
def... |
def _logssim(img1, img2, window, window_size, channel, size_average=True):
mu1 = F.conv2d(img1, window, padding=(window_size // 2), groups=channel)
mu2 = F.conv2d(img2, window, padding=(window_size // 2), groups=channel)
mu1_sq = mu1.pow(2)
mu2_sq = mu2.pow(2)
mu1_mu2 = (mu1 * mu2)
sigma1_sq = (... |
def return_sets(list_of_neighbors, k, stats, u_rels):
each_set = defaultdict(set)
for neigh in list_of_neighbors:
each_set[neigh['rts']].add((neigh['e'], neigh['s']))
for (key, v) in each_set.items():
v_l = list(v)
np.random.shuffle(v_l)
for (end, start) in v_l[:k]:
... |
class TestTransaction(unittest.TestCase):
def test_init(self):
row1 = [1, 1, 0]
header1 = ['A', 'B', 'C']
transaction1 = Transaction(row1, header1, ('Class', 0))
transaction2 = UniqueTransaction(row1, header1, ('Class', 0))
def test_getclass(self):
row1 = [1, 1, 0]
... |
class TransformerDecoderLayer(nn.Module):
def __init__(self, args, no_encoder_attn=False, add_bias_kv=False, add_zero_attn=False):
super().__init__()
self.embed_dim = args.decoder_embed_dim
self.dropout_module = FairseqDropout(args.dropout, module_name=self.__class__.__name__)
self.q... |
def load_images(image_paths, image_size, image_names):
loaded_images = []
loaded_image_paths = []
for (i, img_path) in enumerate(image_paths):
try:
image = load_img(img_path, target_size=image_size)
image = keras.preprocessing.image.img_to_array(image)
image /= 25... |
class StochasticDepth(layers.Layer):
def __init__(self, drop_path_rate, **kwargs):
super().__init__(**kwargs)
self.drop_path_rate = drop_path_rate
def call(self, x, training=None):
if training:
keep_prob = (1 - self.drop_path_rate)
shape = ((tf.shape(x)[0],) + ((1... |
def reverse(tensor):
idx = [i for i in range((tensor.size(0) - 1), (- 1), (- 1))]
return tensor[idx] |
(name='Cohere', emoji='', models=['command', 'command-nightly', 'command-light', 'command-light-nightly'], rate_limit='sequential', settings_schema=COHERE_SETTINGS_SCHEMA)
def CohereCompletion(prompt: str, model: str, temperature: float=0.75, **kwargs) -> str:
print(f"Calling Cohere model {model} with prompt '{prom... |
class BarlowTwins(DCCA):
def __init__(self, *args, lamb=0.005, **kwargs):
super().__init__(*args, **kwargs)
self.lamb = lamb
self.bns = torch.nn.ModuleList([torch.nn.BatchNorm1d(self.latent_dimensions, affine=False) for _ in self.encoders])
def forward(self, views, **kwargs):
z =... |
def make_sub_graph(node, inits, input_data, output_data, reduce_range, opset, ir_version):
from onnx import TensorProto, helper, numpy_helper
input = helper.make_tensor_value_info(node.input[0], dtype_map[input_data.dtype], input_data.shape)
output = helper.make_tensor_value_info(node.output[0], dtype_map[o... |
def _shuffle_split(path, output_path, dataset_info, split, seed):
assert os.path.exists(os.path.join(path, f"{dataset_info['name']}-{split}.index"))
_cache()
def _get_shard_index(idx):
index_file = os.path.join(path, f"{dataset_info['name']}-{split}-{idx:06d}-of-{dataset_info[f'{split}_size']:06d}.i... |
class PickleWidget():
def __init__(self, viz):
self.viz = viz
self.search_dirs = []
self.cur_pkl = None
self.user_pkl = ''
self.recent_pkls = []
self.browse_cache = dict()
self.browse_refocus = False
self.load('', ignore_errors=True)
def add_recent... |
def unwrap_(*args: Any) -> Any:
return tuple(((t.raw if isinstance(t, Tensor) else t) for t in args)) |
class LockedDropout(nn.Module):
def __init__(self, dropout=None):
super().__init__()
self.dropout = dropout
def forward(self, x):
if ((not self.training) or (not self.dropout)):
return x
m = x.data.new(1, *x.size()[1:]).bernoulli_((1 - self.dropout))
mask = (V... |
def main():
args = parse_args()
dist_world_size = (args.nproc_per_node * args.nnodes)
current_env = os.environ.copy()
current_env['MASTER_ADDR'] = args.master_addr
current_env['MASTER_PORT'] = str(args.master_port)
current_env['WORLD_SIZE'] = str(dist_world_size)
processes = []
for local... |
def get_parser():
parser = argparse.ArgumentParser(description='GRA Transformer')
parser.add_argument('--work-dir', default='./work_dir/temp', help='the work folder for storing results')
parser.add_argument('-model_saved_name', default='')
parser.add_argument('--config', default='./config/nturgbd-cross-... |
def test_summarize(model, X):
d1 = model.distributions[0]
d2 = model.distributions[1]
model.summarize(X)
assert_array_almost_equal(model._xw_sum, [0., 1.895243, 2.635099, 3.469392], 4)
assert_array_almost_equal(model._xw_starts_sum, [0.136405, 1.863595], 4)
assert_array_almost_equal(model._xw_en... |
def get_example_inputs(model):
onnx_config_class = TasksManager.get_exporter_config_constructor(model_type=model.config.model_type, exporter='onnx', task='text2text-generation')
onnx_config = onnx_config_class(model.config, use_past=model.config.use_cache, use_past_in_inputs=model.config.use_cache)
encoder_... |
def shutdown():
global world
Logger.print('Shutting down...')
world.shutdown()
return |
def get_map(image_id, save_dir=None, coco_class=None, dataset='pascal'):
if (dataset == 'pascal'):
img_name = ((image_id.split('_')[0] + '_') + image_id.split('_')[1])
image = imread(f'{image_path}/{img_name}.jpg')
elif (dataset == 'coco'):
image = imread(f'{image_path}/{int(image_id):01... |
class AverageMeter(object):
def __init__(self):
self.value = 0
self.average = 0
self.sum = 0
self.count = 0
def reset(self):
self.value = 0
self.average = 0
self.sum = 0
self.count = 0
def update(self, value, n=1):
self.value = value
... |
class DiffTransformerEncoder(nn.TransformerEncoder):
def forward(self, src, pe, degree=None, mask=None, src_key_padding_mask=None):
output = src
for mod in self.layers:
output = mod(output, pe=pe, degree=degree, src_mask=mask, src_key_padding_mask=src_key_padding_mask)
if (self.n... |
class DataSetCSVagentActPred(DataSetCSVslotTagging):
def __init__(self, csv_file, window_size=5, train_data=None, flag='train'):
if (flag == 'train'):
self.window_size = window_size
elif (flag == 'test'):
self.window_size = train_data.window_size
else:
rai... |
def _get_images_opts():
parser = argparse.ArgumentParser()
parser.add_argument('--image_path', type=str, required=True)
parser.add_argument('--dataset_path', type=str, required=True)
return parser.parse_args() |
_model
def tv_resnet152(pretrained=False, **kwargs):
model_args = dict(block=Bottleneck, layers=[3, 8, 36, 3], **kwargs)
return _create_resnet('tv_resnet152', pretrained, **model_args) |
def _get_config(num_ghosts, maze_size):
agent_factors = dict(shape='circle', scale=0.05, c0=0.33, c1=1.0, c2=0.66)
prey_factors = dict(shape='circle', scale=0.025, c0=0.2, c1=1.0, c2=1.0)
ghost_factors = dict(shape='circle', scale=0.05, mass=np.inf, c0=0.0, c1=1.0, c2=0.8)
def state_initializer():
... |
def get_embeddings(file_enc, opt, flag):
embs = dict()
if (flag == 'enc'):
for (i, l) in enumerate(open(file_enc, 'rb')):
if (i < opt.skip_lines):
continue
if (not l):
break
if (len(l) == 0):
continue
l_split... |
class Base(object):
__metaclass__ = abc.ABCMeta
def __init__(self, log_name='logs.txt'):
self.cur_epoch = 0
self.tot_timer = Timer()
self.gpu_timer = Timer()
self.read_timer = Timer()
self.logger = colorlogger(cfg.log_dir, log_name=log_name)
def _make_batch_generator(... |
def test_linacc_constantacc_x_2d():
lp = potential.LogarithmicHaloPotential(normalize=1.0)
dp = potential.DehnenBarPotential(omegab=1.8, rb=0.5, Af=0.03)
diskpot = (lp + dp)
ax = 0.02
intax = (lambda t: ((ax * (t ** 2.0)) / 2.0))
framepot = potential.NonInertialFrameForce(a0=[ax, 0.0, 0.0])
... |
class Warmup(Callback):
def __init__(self, max_epochs):
super(Warmup, self).__init__()
if (max_epochs <= 0):
self.max_epochs = 1.0
else:
self.max_epochs = max_epochs
def on_epoch_begin(self, epoch, logs={}):
beta = np.minimum(1.0, ((epoch * 1.0) / (self.ma... |
class MNLI(PreprocessedTextDataset):
labels = ('contradiction', 'entailment', 'neutral')
def __init__(self, *args, **kwags):
super().__init__(*args, **kwags)
def get_instances(self, text_file):
with open(text_file, 'r') as f:
lines = csv.reader(f, delimiter='\t', quotechar=None)
... |
class Estimator(BaseEstimator):
def fit(self, data, epochs, batch_size=32, feature_cols=None, label_cols=None, validation_data=None, checkpoint_trigger=None):
invalidInputError(False, 'not implemented')
def predict(self, data, batch_size=4, feature_cols=None):
invalidInputError(False, 'not imple... |
class MMSeq2SeqModel(nn.Module):
def __init__(self, mm_encoder, history_encoder, input_encoder, response_decoder):
super(MMSeq2SeqModel, self).__init__()
self.history_encoder = history_encoder
self.mm_encoder = mm_encoder
self.input_encoder = input_encoder
self.response_decod... |
def test(binary_name, tests, logfile, logfile_name):
binary = make_binary(binary_name)
if (not os.path.exists(binary)):
fail_with(('Binary %s does not exist' % binary))
print_to_screen('\n{c.BOLD}# TESTING BINARY {name}{c.NORMAL}'.format(c=bcolors, name=binary_name))
benchmark_id = 1
passed_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.