code
stringlengths
101
5.91M
def write_wav_scpf(fn, utts, audio_dir, audio_ext='.flac'): with open(fn, 'wb') as f: for utt in sorted(utts): if (audio_ext == '.flac'): wav_str = '{} sox -t flac {}/{}.flac -t wav -r 16k -b 16 --channels 1 - |\n'.format(utt, audio_dir, utt) elif (audio_ext == '.wav'...
class ShakeDropFunction(torch.autograd.Function): def forward(ctx, x, training=True, p_drop=0.5, alpha_range=[(- 1), 1]): ctx.training = training ctx.p_drop = p_drop if training: gate = torch.empty(1, device=x.device).bernoulli_((1 - p_drop)) ctx.save_for_backward(gat...
def recall(gold, pred): tp = 0 fn = 0 assert (len(gold) == len(pred)) for sent_idx in pred.keys(): p = pred[sent_idx] g = gold[sent_idx] for edge_label in g: if (edge_label in p): tp += 1 else: fn += 1 try: retur...
def DistributedFairseqModel(args, model, process_group=None): assert isinstance(model, nn.Module) if ((args.distributed_wrapper == 'DDP') and (args.ddp_backend == 'c10d')): ddp_class = nn.parallel.DistributedDataParallel init_kwargs = dict(module=model, device_ids=[args.device_id], output_device...
def load_pretrained_model(model_name='resnet18', device='cuda', num_params=3, inplace=True, data_path='/scratch/users/vision/data/cosmo'): if (model_name == 'resnet18'): model_ft = models.resnet18(pretrained=False) model_ft.conv1 = nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), ...
_registry('Basic') class BasicNAS(NASBase): def __init__(self, conf_fname_or_obj, search_space=None, model_builder=None): NASBase.__init__(self, search_space=search_space, model_builder=model_builder) self._train_func = None self._eval_func = None self.init_by_cfg(conf_fname_or_obj) ...
def _clip_actions(algo, actions): epsilon = 1e-06 lower = (torch.from_numpy(algo._env_spec.action_space.low).to(algo.device) + epsilon) upper = (torch.from_numpy(algo._env_spec.action_space.high).to(algo.device) - epsilon) clip_up = (actions > upper).float() clip_down = (actions < lower).float() ...
def fuse_conv_and_bn(conv, bn): fusedconv = nn.Conv2d(conv.in_channels, conv.out_channels, kernel_size=conv.kernel_size, stride=conv.stride, padding=conv.padding, groups=conv.groups, bias=True).requires_grad_(False).to(conv.weight.device) w_conv = conv.weight.clone().view(conv.out_channels, (- 1)) w_bn = to...
def test_isotropic_hernquist_sigmar(): pot = potential.HernquistPotential(amp=2.3, a=1.3) dfh = isotropicHernquistdf(pot=pot) numpy.random.seed(10) samp = dfh.sample(n=300000) tol = 0.05 check_sigmar_against_jeans(samp, pot, tol, beta=0.0, rmin=(pot._scale / 10.0), rmax=(pot._scale * 10.0), bins...
def splice(s): buf = [] ans = [] for c in s: if is_all_chinese(c): if buf: buf_str = ''.join(buf) buf = [] ans.append(buf_str) ans.append(c) else: buf.append(c) if buf: buf_str = ''.join(buf) ...
class RLlibMetricLogger(DefaultCallbacks): def __init__(self, metrics: Mapping[(str, 'Metric')]) -> None: super().__init__() self.metrics = metrics def on_episode_start(self, *, episode, **kwargs) -> None: for metric_id in self.metrics.keys(): episode.user_data[metric_id] = [...
def trace_back(error_msg): exc = traceback.format_exc() msg = f'''[Error]: {error_msg}. [Traceback]: {exc}''' return msg
def gen_space_config(opt_lib_group, opt_lib_methods, total_process, included_opts=[]): space_config = [] for (group_name, opt_candidates_raw) in opt_lib_group.items(): opt_candidates = [] if ((group_name == 'module_replace') and opt_lib_methods['module_replace'].disabled): continue ...
class Args(Tap): data_path: str smiles_column: str = None features_generator: str = 'rdkit_2d_normalized' save_path: str save_frequency: int = 10000 restart: bool = False sequential: bool = False def add_arguments(self) -> None: self.add_argument('--features_generator', choices=g...
class VocabInfoTest(tf.test.TestCase): def setUp(self): super(VocabInfoTest, self).setUp() tf.logging.set_verbosity(tf.logging.INFO) self.vocab_list = ['Hello', '.', 'Bye'] self.vocab_file = test_utils.create_temporary_vocab_file(self.vocab_list) def tearDown(self): super...
def text_ontonotes(tree, filename='filename', words=None, tree_text=None, depth=0): resolve = False if (words is None): resolve = True words = [] tree_text = '' if (tree.word is None): tree_text += (('(' + tree.label) + '_') else: words.append((tree.word, tree.lab...
_comparison(baseline_images=['3d_custom_order'], remove_text=False, extensions=['png']) def test_3d_custom_order(grid_archive_3d): plt.figure(figsize=(8, 6)) parallel_axes_plot(grid_archive_3d, measure_order=[1, 2, 0])
def AccWordStatsForUtterance(split_lines_of_utt, segments_for_utterance): global word_count_pair line_is_in_segment = ([False] * len(split_lines_of_utt)) for segment in segments_for_utterance: for i in range(segment.start_index, segment.end_index): line_is_in_segment[i] = True for i ...
_builder('ok_vqa') class OKVQABuilder(COCOVQABuilder): DATASET_CONFIG_DICT = {'default': 'configs/datasets/okvqa/defaults.yaml'}
def find_free_port() -> int: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('localhost', 0)) sockname = sock.getsockname() sock.close() return sockname[1]
_processor('alpro_video_train') class AlproVideoTrainProcessor(AlproVideoBaseProcessor): def __init__(self, image_size=384, mean=None, std=None, min_scale=0.5, max_scale=1.0, n_frms=MAX_INT): super().__init__(mean=mean, std=std, n_frms=n_frms) self.image_size = image_size self.transform = tr...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--saveas', metavar='S', type=str, required=True, help='Name of the merged predictions file') parser.add_argument('--filenames', nargs='+', type=str, help='names of predictions files to merge separated by spaces') args = parser.parse_arg...
def save_checkpoint(state, is_best, epoch, save_path='./'): print("=> saving checkpoint '{}'".format(epoch)) torch.save(state, os.path.join(save_path, 'checkpoint.pth.tar')) if ((epoch % 10) == 0): torch.save(state, os.path.join(save_path, ('checkpoint_%03d.pth.tar' % epoch))) if is_best: ...
def magspec_vad(wav, n_fft=1024, hop_length=256): stft = librosa.stft(wav, n_fft=n_fft, hop_length=hop_length, center=False) (mag, phase) = librosa.magphase(stft) mag = (mag / np.max(mag)) mag_sum = mag.sum(0) mag_sum[(mag_sum >= 0.1)] = 1 mag_sum[(mag_sum != 1)] = 0 diff = np.diff(np.pad(ma...
def plot_curves_parser(txtfile, multi=True): lines = read_lines(txtfile) if multi: val_losses = {'total': [], 'iou': [], 'stop': [], 'class': []} train_losses = {'total': [], 'iou': [], 'stop': [], 'class': []} else: val_loss = [] train_loss = [] print('Scanning text file...
def transform_state_dict_to_dtype(original_state_dict, dtype='bf16'): sd_copy = copy.deepcopy(original_state_dict) for name in original_state_dict: if sd_copy[name].is_floating_point(): if (dtype == 'bf16'): sd_copy[name] = original_state_dict[name].bfloat16() if ...
class Lin(nn.Module): def __init__(self, in_channels, out_channels): super(Lin, self).__init__() self.model = nn.Sequential(nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=True), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True)) def forward(self, x): return self.model(x)
_comparison(baseline_images=['2d_long_square'], remove_text=False, extensions=['png']) def test_2d_long_square(sliding_archive_2d_long): plt.figure(figsize=(8, 6)) sliding_boundaries_archive_heatmap(sliding_archive_2d_long, aspect='equal')
class SingleStepGaussian(): def __init__(self, means, sigma=0.0001): self.sigma = sigma sigmas = (torch.ones_like(means) * sigma) self.dist = torch.distributions.Normal(means, sigmas) def sample(self, condition_dict=None): samples = self.dist.sample() return samples d...
def main(args): if args.output_dir: utils.mkdir(args.output_dir) utils.init_distributed_mode(args) print(args) if args.cifar10: args.val_resize_size = 32 args.val_crop_size = 32 args.train_crop_size = 32 if (args.post_training_quantize and args.distributed): r...
def get_string_lvl(array, index2str): result = '' for y in range(array.shape[0]): for x in range(array.shape[1]): result += index2str[array[y][x]] result += '\n' return result
_registry(op_types='Pad') class QPadOperator(QOperator): def __init__(self, onnx_node, children, initializers): super().__init__(onnx_node, children, initializers)
def main(): args = get_args() lexiconp = read_lexiconp(args.lexiconp) write_position_dependent_lexicon(lexiconp, args.separator)
def l2norm(X, dim=(- 1), eps=1e-08): norm = (torch.pow(X, 2).sum(dim=dim, keepdim=True).sqrt() + eps) X = torch.div(X, norm) return X
def _duration_to_string(duration, precision=2): if (duration > 1): return (str(round(duration, precision)) + ' s') elif ((duration * (10 ** 3)) > 1): return (str(round((duration * (10 ** 3)), precision)) + ' ms') elif ((duration * (10 ** 6)) > 1): return (str(round((duration * (10 **...
def synthesize_training_data(nexamples, vocab_size, min_length=10, max_length=30, seed=None): if (seed is not None): set_random_seed(seed) dataset = [] for i in range(nexamples): length = np.random.randint(min_length, max_length) example = np.random.randint(0, vocab_size, size=length...
class StableDiffusionParadigmsPipeline(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_p...
class MAMLFirstOrderOptimizer(Optimizer): def __init__(self, tf_optimizer_cls=tf.train.AdamOptimizer, tf_optimizer_args=None, learning_rate=0.001, max_epochs=1, tolerance=1e-06, num_minibatches=1, verbose=False): self._target = None if (tf_optimizer_args is None): tf_optimizer_args = dic...
def ra2idx(rng, agl): (rng_id, _) = find_nearest(range_grid, rng) (agl_id, _) = find_nearest(angle_grid, agl) return (rng_id, agl_id)
class Candidates(object): def __init__(self, language, Load, association_dict=None, freq_threshold=1, delta_threshold=0.1): self.language = language self.Load = Load self.freq_threshold = freq_threshold self.delta_threshold = delta_threshold self.association_dict = associatio...
def bar_plot(ax, data, colors=None, total_width=0.8, single_width=1, legend=True, ns=''): if (colors is None): colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] n_bars = len(data) print(data) if (n_bars > 0): bar_width = (total_width / n_bars) bars = [] for (i, (...
def get_cls_doc(elt, full_name: str) -> str: parent_class = inspect.getclasstree([elt])[(- 1)][0][1][0] (name, args) = format_ft_def(elt, full_name) if (parent_class != object): args += f' :: {link_type(parent_class, include_bt=True)}' return (name, args)
class TestRGBfromDisp(): def test_default(self): x = torch.rand(2, 1, 10, 20) out = rgb_from_disp(x) out2 = rgb_from_disp(x, cmap='turbo', vmin=0, vmax=[np.percentile(x[0], 95), np.percentile(x[1], 95)]) assert np.allclose(out, out2), 'Incorrect default params.' def test_range(se...
def rgb_loader(path): with open(path, 'rb') as f: with Image.open(f) as img: return img.convert('RGB')
def palette_val(palette): new_palette = [] for color in palette: color = [(c / 255) for c in color] new_palette.append(tuple(color)) return new_palette
def get_checkpoint_files(model_name_or_path, local_rank, token=None): cached_repo_dir = get_repo_root(model_name_or_path, local_rank, token) file_list = [str(entry) for entry in Path(cached_repo_dir).rglob('*.[bp][it][n]') if entry.is_file()] return file_list
.parametrize('kernel_size, out_channels, in_channels, with_inp_importance, with_neighbors_importance, with_normalization', [(1, 2, 7, True, False, False), (2, 1, 1, False, False, False), (3, 5, 3, False, True, True), (33, 3, 4, False, True, False)]) .ml .parametrize('dtype', [np.float32]) def test_sparseconv_gradient(m...
_config def student_taskonomy_encoder_penultimate(): cfg = {'learner': {'model': 'TaskonomyEncoder', 'model_kwargs': {'train': True, 'eval_only': False}}}
def plot_data_and_recon(data_tensor, recon_tensor): data_tensor = convert_tensor(data_tensor) recon_tensor = convert_tensor(recon_tensor) n_frames = data_tensor.shape[0] for frame_num in range(1, (n_frames + 1)): plt.subplot(2, n_frames, frame_num) plt.imshow(data_tensor[(frame_num - 1)]...
def get_kpis(env: CityLearnEnv) -> pd.DataFrame: kpis = env.evaluate() kpi_names = ['electricity_consumption', 'cost', 'carbon_emissions', 'average_daily_peak', 'ramping', '1 - load_factor'] kpis = kpis[kpis['cost_function'].isin(kpi_names)].dropna() kpis['value'] = kpis['value'].round(3) kpis = kpi...
def transpile_circuit(circuit, transpile_config): if transpile_config.pass_manager: pass_manager = transpile_config.pass_manager elif (transpile_config.optimization_level is not None): level = transpile_config.optimization_level if (level == 0): pass_manager = level_0_pass_ma...
class Attention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0.0, proj_drop=0.0): super().__init__() self.num_heads = num_heads head_dim = (dim // num_heads) self.scale = (head_dim ** (- 0.5)) self.qkv = nn.Linear(dim, (3 * dim), bias=qkv_bias) ...
def dict_mean(dicts): means = {} for key in dicts[0].keys(): means[key] = (sum((d[key] for d in dicts)) / len(dicts)) return means
class LatentSpacePolicy(BasePolicy): def __init__(self, *args, smoothing_coefficient=None, **kwargs): super(LatentSpacePolicy, self).__init__(*args, **kwargs) assert ((smoothing_coefficient is None) or (0 <= smoothing_coefficient <= 1)) self._smoothing_alpha = (smoothing_coefficient or 0) ...
class Config(NamedTuple): seed: int = 3431 batch_size: int = 32 lr: int = 5e-05 n_epochs: int = 10 warmup: float = 0.1 save_steps: int = 100 total_steps: int = 100000 data_parallel: bool = False comments: str = ''
class TestSNNBiasFit(TrainDiffPOSNN, GenDiffSigmoidSNNWithoutKernel, DiffTestBase, unittest.TestCase): def mod_params(self): self.n_epochs = 10 self.sample_size = 100 self.length = 50 self.obj_func_kwargs = {'n_pos': 50, 'n_neg': 50, 'n_sampling': 1, 'beta': 1.0} def preprocess(s...
def test_config_build_detector(): from mmcv import Config from mmdet.models import build_detector config_dpath = _get_config_directory() print(f'Found config_dpath = {config_dpath}') import glob config_fpaths = list(glob.glob(join(config_dpath, '**', '*.py'))) config_fpaths = [p for p in con...
def read_lines(filepath): with open(filepath, 'r') as f: return [e.strip('\n') for e in f.readlines()]
_TFVolume.register('soft') class TFSoftVolume(_TFVolume): def __init__(self, log_scale: bool=True, volume_temperature: float=1.0) -> None: super().__init__(log_scale) self.volume_temperature = volume_temperature def __call__(self, box_tensor: TFBoxTensor) -> tf.Tensor: return tf_soft_vol...
_torch class AutoModelTest(unittest.TestCase): def test_model_from_pretrained(self): logging.basicConfig(level=logging.INFO) for model_name in list(BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: config = AutoConfig.from_pretrained(model_name) self.assertIsNotNone(config) ...
def posterize(pil_img, level): level = int_parameter(sample_level(level), 4) ret = ImageOps.posterize(pil_img, (4 - level)) return ret
def print_diff(diff_lines, use_color): if use_color: diff_lines = colorize(diff_lines) sys.stdout.writelines(diff_lines)
_model('dummy_model') class DummyModel(FairseqLanguageModel): def __init__(self, args, encoder): super().__init__(encoder) self.args = args def add_args(parser): parser.add_argument('--num-layers', type=int, default=24) parser.add_argument('--embed-dim', type=int, default=1024) ...
def normalization(planes, norm='bn'): if (norm == 'bn'): m = nn.BatchNorm3d(planes) elif (norm == 'gn'): m = nn.GroupNorm(4, planes) elif (norm == 'in'): m = nn.InstanceNorm3d(planes) else: raise ValueError('normalization type {} is not supported'.format(norm)) return...
class TestGemm(object): def test_gemm(self): mata_shape = [2, 7] matb_shape = [7, 4] matc_shape = [2, 4] output_shape = [2, 4] alpha = np.round(np.random.rand(), 2) beta = np.round(np.random.rand(), 2) (trans_a, trans_b) = (0, 0) input_x = np.random.ra...
def replace_keys(d: dict[(str, ...)], old: str, new: str, is_prfx: bool=False, is_sffx: bool=False) -> dict[(str, ...)]: return {replace_str(k, old, new, is_prfx=is_prfx, is_sffx=is_sffx): v for (k, v) in d.items()}
(version='2.0') class PyTorchCriterions(object): def __init__(self): self.criterions = {} self.criterions.update(PYTORCH_CRITERIONS)
class ResBlock(nn.Module): def __init__(self, start_filts, planes, conv, stride=1, downsample=None, norm=None, relu='relu'): super(ResBlock, self).__init__() self.conv1 = conv(start_filts, planes, ks=1, stride=stride, norm=norm, relu=relu) self.conv2 = conv(planes, planes, ks=3, pad=1, norm=...
_loss def charbonnier_loss_color(pred, target, eps=1e-06): diff = torch.add(pred, (- target)) diff_sq = (diff * diff) diff_sq_color = torch.mean(diff_sq, 1, True) error = torch.sqrt((diff_sq_color + eps)) loss = torch.mean(error) return loss
class MaskedLMConfig(FairseqDataclass): data: str = field(default=MISSING, metadata={'help': 'colon separated path to data directories list, will be iterated upon during epochs in round-robin manner'}) sample_break_mode: SAMPLE_BREAK_MODE_CHOICES = field(default='none', metadata={'he...
def main(_): set_path(args, args.experiment_name) tfconfig = tf.ConfigProto(allow_soft_placement=True) tfconfig.gpu_options.allow_growth = True with tf.Session(config=tfconfig) as sess: model = AUGAN(sess, args) (model.train(args) if (args.phase == 'train') else model.test(args))
def _contiguous_ranges(span_list): output = [] for (_, span) in itertools.groupby(enumerate(span_list), (lambda p: (p[1] - p[0]))): span = list(span) output.append((span[0][1], span[(- 1)][1])) return output
class ImageNetSRTrain(ImageNetSR): def __init__(self, **kwargs): super().__init__(**kwargs) def get_base(self): with open('data/imagenet_train_hr_indices.p', 'rb') as f: indices = pickle.load(f) dset = ImageNetTrain(process_images=False) return Subset(dset, indices)
class Params(): def __init__(self): arguments = docopt(__doc__) self.experiments_config = arguments['--config'] self.training_trees = train_utils.load_tuple_trees('../../dataset_creation/data/uspto-train-depth_and_tree_tuples.pick', np.random.RandomState(10)) self.training_data_smi_l...
def test_traffic(): import numpy as np from dynamics_and_models import ReferencePath def _reset_init_state(): ref_path = ReferencePath('straight') random_index = (int((np.random.random() * (900 + 500))) + 700) (x, y, phi) = ref_path.indexs2points(random_index) v = (8 * np.ran...
def main(args): layers_map = {'relu4_2': '22', 'relu2_2': '8', 'relu3_2': '13', 'relu1_2': '4'} vis = visdom.Visdom(port=args.display_port) loss_graph = {'g': [], 'gd': [], 'gf': [], 'gpl': [], 'gpab': [], 'gs': [], 'd': [], 'gdl': [], 'dl': []} transforms = get_transforms(args) if (args.color_space...
class InstanceMaker(AwsInstance): def __init__(self, identity, name, instance_type, db, force, no_connect, spot, queue_name): super(InstanceMaker, self).__init__(identity, require_pem=True) self.name = name self.instance_type = instance_type self.db = db self.force = force ...
def multinomial_resample(weights): cumulative_sum = np.cumsum(weights) cumulative_sum[(- 1)] = 1.0 return np.searchsorted(cumulative_sum, random(len(weights)))
def parse_component(component): if isinstance(component, str): return (component, None) elif isinstance(component, dict): component_name = list(component.keys())[0] arguments = component[component_name] return (component_name, arguments) else: raise ValueError('Argume...
def get_linker(full_mol, clean_frag, starting_point): matches = list(full_mol.GetSubstructMatches(clean_frag)) if (len(matches) == 0): print('No matches') return '' linker_len = (full_mol.GetNumHeavyAtoms() - clean_frag.GetNumHeavyAtoms()) if (linker_len == 0): return '' mol_...
class GaussianNoiseLayer(nn.Module): def __init__(self): super(GaussianNoiseLayer, self).__init__() def forward(self, x): if (self.training == False): return x noise = Variable(torch.randn(x.size()).cuda(x.get_device())) return (x + noise)
def save_embeddings(filepath, filename, embeddings): if (not os.path.exists(filepath)): os.mkdir(filepath) target_path = os.path.join(filepath, filename) torch.save({'embeds': embeddings}, target_path) return True
class Net(network.resnet38d.Net): def __init__(self): super(Net, self).__init__() self.f8_3 = torch.nn.Conv2d(512, 64, 1, bias=False) self.f8_4 = torch.nn.Conv2d(1024, 128, 1, bias=False) self.f8_5 = torch.nn.Conv2d(4096, 256, 1, bias=False) self.f9 = torch.nn.Conv2d(448, 448...
_errors def prediction_tester(project, verbosity, passed, **kwargs) -> None: sf.setLoggingLevel(verbosity) project.predict(**kwargs)
def set_double_double_solution(nvr, sol, vrblvl=0): if (vrblvl > 0): print('in set_double_double_solution, nvr :', nvr) print('the solution :') print(sol) set_double_double_solutions(nvr, [sol]) phc = get_phcfun() apars = (c_int32 * 2)() apars[0] = c_int32(1) apars[1] = c...
def bbox3d2roi(bbox_list): rois_list = [] for (img_id, bboxes) in enumerate(bbox_list): if (bboxes.size(0) > 0): img_inds = bboxes.new_full((bboxes.size(0), 1), img_id) rois = torch.cat([img_inds, bboxes], dim=(- 1)) else: rois = torch.zeros_like(bboxes) ...
class InceptionV4Encoder(InceptionV4, EncoderMixin): def __init__(self, stage_idxs, out_channels, depth=5, **kwargs): super().__init__(**kwargs) self._stage_idxs = stage_idxs self._out_channels = out_channels self._depth = depth self._in_channels = 3 for m in self.mod...
def chamfer_loss(pc1, pc2): pc1 = pc1.permute(0, 2, 1) pc2 = pc2.permute(0, 2, 1) (chamfer_dist, _) = chamfer_distance(pc1, pc2) return chamfer_dist
def input_fn_builder(input_files, max_seq_length, is_training, num_cpu_threads=4): def input_fn(params): batch_size = params['batch_size'] name_to_features = {'input_ids': tf.FixedLenFeature([max_seq_length], tf.int64), 'target_ids': tf.FixedLenFeature([max_seq_length], tf.int64), 'input_mask': tf.F...
def main(args): public_key = fetch_public_key(args.repo) password = (args.password or getpass('PyPI password: ')) update_travis_deploy_password(encrypt(public_key, password.encode())) print("Wrote encrypted password to .travis.yml -- you're ready to deploy")
def find_ref_span(sent_offsets, target): (start, end) = target ref_start = (- 1) ref_end = (- 1) for (i, (sent_start, sent_end)) in enumerate(sent_offsets): if ((start >= sent_start) and (start <= sent_end)): ref_start = sent_start if ((end >= sent_start) and (end <= sent_end...
class GitProcessor(ProcessorMixin): attributes = ['image_processor', 'tokenizer'] image_processor_class = 'AutoImageProcessor' tokenizer_class = 'AutoTokenizer' def __init__(self, image_processor, tokenizer): super().__init__(image_processor, tokenizer) self.current_processor = self.imag...
def get_key(variable): if (variable in KEYS): return KEYS[variable] else: return generic_key(variable)
class SelfAttention(layers.Layer): def __init__(self, hidden_dim, output_dim, **kwargs): self.hidden_dim = hidden_dim self.output_dim = output_dim super().__init__(**kwargs) def get_config(self): config = super().get_config().copy() config.update({'hidden_dim': self.hidde...
def load_examples(path: str, seed: int) -> List[Example]: question_df = pd.read_csv(path) random.seed(seed) def shuffle_choices_and_create_example(row) -> Example: list_choices = [row['Incorrect Answer 1'], row['Incorrect Answer 2'], row['Incorrect Answer 3'], row['Correct Answer']] random.s...
def main(args): train_args = vars(args).copy() train_args['tree_subsample_frac'] = 1.0 train_args['tree_subsample_order'] = 'random' train_args['instance_subsample_frac'] = 1.0 method_name = util.get_method_identifier(args.model_type, train_args) in_dir = os.path.join(args.in_dir, args.custom_in...
class LevitImageProcessor(metaclass=DummyObject): _backends = ['vision'] def __init__(self, *args, **kwargs): requires_backends(self, ['vision'])
class TopDownGlobalChaFuseReduce(HybridBlock): def __init__(self, channels=64): super(TopDownGlobalChaFuseReduce, self).__init__() self.channels = channels with self.name_scope(): self.feature_high = nn.HybridSequential(prefix='feature_high') self.feature_high.add(nn....
def _check_Parikh2014(mus, lams, views): failed_check = [i for (i, (mu, lam, view)) in enumerate(zip(mus, lams, views)) if (mu < (lam / (np.linalg.norm(view) ** 2)))] if failed_check: raise ValueError(f'mu, lam, view not matching condition specified from Parikh 2014 (mu<lam/frobenius(representations)**2...
def test_decompose(): from cascades import run_cascade pols = ['(x1-1)*(x1-2)*(x1-3)*(x1-4);', '(x1-1)*(x2-1)*(x2-2)*(x2-3);', '(x1-1)*(x1-2)*(x3-1)*(x3-2);', '(x1-1)*(x2-1)*(x3-1)*(x4-1);'] deco = run_cascade(4, 3, pols) fadc = decompose(deco) write_decomposition(fadc)