code
stringlengths
101
5.91M
class PushToHubMixin(): def push_to_hub(self, repo_path_or_name: Optional[str]=None, repo_url: Optional[str]=None, use_temp_dir: bool=False, commit_message: Optional[str]=None, organization: Optional[str]=None, private: Optional[bool]=None, use_auth_token: Optional[Union[(bool, str)]]=None, **model_card_kwargs) -> ...
def fbresnet34(num_classes=1000): model = FBResNet(BasicBlock, [3, 4, 6, 3], num_classes=num_classes) return model
class MidBlockTemporalDecoder(nn.Module): def __init__(self, in_channels: int, out_channels: int, attention_head_dim: int=512, num_layers: int=1, upcast_attention: bool=False): super().__init__() resnets = [] attentions = [] for i in range(num_layers): input_channels = (i...
def loadPal(filename): _annolist = AnnoList_pb2.AnnoList() f = open(filename, 'rb') _annolist.ParseFromString(f.read()) f.close() return _annolist
def get_deconv_output_size(input_size, kernel_size, stride, padding, dilation, output_padding): ndim = len(input_size) output_size = [] for i in range(ndim): if (kernel_size[i] == (- 1)): raise ValueError("deconv don't support kernel_size < 0") size = (((((input_size[i] - 1) * st...
def linspace(start, stop, num, endpoint=True): start = tf.convert_to_tensor(start) stop = tf.convert_to_tensor(stop, dtype=start.dtype) if endpoint: if (num == 1): return tf.reduce_mean(tf.stack([start, stop], axis=0), axis=0, keepdims=True) else: return tf.linspace(s...
class ReSDPipeline(StableDiffusionPipeline): _grad() def __call__(self, prompt: Union[(str, List[str])], prompt1_steps: Optional[int]=None, prompt2: Optional[str]=None, head_start_latents: Optional[Union[(torch.FloatTensor, list)]]=None, head_start_step: Optional[int]=None, height: Optional[int]=None, width: Op...
def cp_ckpt(remote_dir='data_wd/youtube_vos_jobs/result', curr_dir='backup'): exps = os.listdir(curr_dir) for exp in exps: exp_dir = os.path.join(curr_dir, exp) stages = os.listdir(exp_dir) for stage in stages: stage_dir = os.path.join(exp_dir, stage) finals = ['e...
def vgg16_bn(pretrained=False, **kwargs): if pretrained: kwargs['init_weights'] = False model = VGG(make_layers(cfg['D'], batch_norm=True), **kwargs) if pretrained: model.load_state_dict(torch.load(os.path.join(models_dir, model_name['vgg16_bn']))) return model
def create_dir_struct(): if (not os.path.isdir('train')): os.mkdir('train') if (not os.path.isdir('val')): os.mkdir('val') if (not os.path.isdir('test')): os.mkdir('test')
def check_input_shape(input_shape, factor): if (input_shape is None): raise ValueError('Input shape should be a tuple of 3 integers, not None!') (h, w) = (input_shape[:2] if (backend.image_data_format() == 'channels_last') else input_shape[1:]) min_size = (factor * 6) is_wrong_shape = (((h % min...
class MultipleOptimizer(object): def __init__(self, op): self.optimizers = op def param_groups(self): param_groups = [] for optimizer in self.optimizers: param_groups.extend(optimizer.param_groups) return param_groups def zero_grad(self): for op in self.op...
class Logger(object): 'Reference: def __init__(self, fn, ask=True): if (not os.path.exists('./results/')): os.mkdir('./results/') logdir = self._make_dir(fn) if (not os.path.exists(logdir)): os.mkdir(logdir) if ((len(os.listdir(logdir)) != 0) and ask): ...
def test_registry(): assert ('disp_mask' in LOSS_REG), 'Missing key from loss registry.' assert (LOSS_REG['disp_mask'] == MaskReg), 'Incorrect class in loss registry.'
def get_shared_folder() -> Path: user = os.getenv('USER') if Path('/checkpoint/').is_dir(): p = Path(f'/checkpoint/{user}/experiments') p.mkdir(exist_ok=True) return p raise RuntimeError('No shared folder available')
def _check_executable(cmd): if (subprocess.call('which {}'.format(cmd), shell=True) != 0): return False else: return True
def parseAbsFileLinesInList(pathToListingFile): pathToFolderContainingThisListFile = os.path.dirname(pathToListingFile) list1 = [] with open(pathToListingFile, 'r') as inp: for line in inp: if (line.strip() == '-'): list1.append('-') elif ((not line.startswith...
class PoolFormerForImageClassification(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def _test(): import torch pretrained = False models = [revnet38, revnet110, revnet164] for model in models: net = model(pretrained=pretrained) net.eval() weight_count = _calc_width(net) print('m={}, {}'.format(model.__name__, weight_count)) assert ((model != revne...
def which_algorithm(config: N2VConfig): if (config.structN2Vmask is not None): return Algorithm.StructN2V elif ((config.n2v_manipulator == PixelManipulator.MEDIAN.value) and (not config.unet_residual) and config.blurpool and config.skip_skipone): return Algorithm.N2V2 else: return Al...
class SimpleSampler(BaseSampler): def __init__(self, **kwargs): super(SimpleSampler, self).__init__(**kwargs) self._path_length = 0 self._path_return = 0 self._current_path = defaultdict(list) self._last_path_return = 0 self._max_path_return = (- np.inf) self....
def load_rf1(as_frame: bool=False) -> Union[(np.ndarray, pd.DataFrame)]: with resources.path('pytorch_widedeep.datasets.data', 'rf1_train.parquet.brotli') as fpath: df = pd.read_parquet(fpath) if as_frame: return df else: return df.to_numpy()
def unflatten_values(vals, batch_size, n_samples): data_dim = (vals[0].ndim - 1) assert all([(v.ndim == (data_dim + 1)) for v in vals]) if (data_dim == 0): return [v.reshape([batch_size, n_samples]) for v in vals] elif (data_dim == 1): return [v.reshape([batch_size, n_samples, v.shape[1]...
class ShardOptim(): class ShardFlatManager(): def __init__(self, param_name, fds, optim_slice): self.fds = fds self.param_name = param_name self.optim_slice = optim_slice def items(self): return self.optim_slice.items() def check_1d(self, state...
class _ReverseGrad(Function): def forward(ctx, input, grad_scaling): ctx.grad_scaling = grad_scaling return input.view_as(input) def backward(ctx, grad_output): grad_scaling = ctx.grad_scaling return (((- grad_scaling) * grad_output), None)
class TestTorchOP(unittest.TestCase): def setUpClass(self): pass def tearDownClass(self): pass def test_1(self): from torch.ao.quantization import MinMaxObserver, PerChannelMinMaxObserver, QConfig qconfig = QConfig(activation=MinMaxObserver.with_args(qscheme=torch.per_tensor_...
class TFAutoModelForNextSentencePrediction(_BaseAutoModelClass): _model_mapping = TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING
def load_mauna(): data_file = '../data/mauna.mat' data = scipy.io.loadmat(data_file) return (data['X'], data['y'])
def sample_stars_all_elements(weight, selection, elements, errors, nsample, random_seed=None): if random_seed: np.random.seed(random_seed) weight = np.cumsum((weight * selection)) weight /= weight[(- 1)] sample = np.random.random(nsample) sample = np.sort(sample) stars = np.zeros_like(we...
def add_results(final_results, name, result_dict, result_list, took, show_accuracy=False): percentiles = [50.0, 80.0, 90.0, 95.0, 99.0, 99.9] buckets = np.percentile(result_list, percentiles).tolist() buckets_str = ','.join(['{}:{:.4f}'.format(p, b) for (p, b) in zip(percentiles, buckets)]) if (result_d...
def make_focal_loss_evaluator(cfg): max_disp = cfg.model.losses.focal_loss.get('max_disp', None) start_disp = cfg.model.losses.focal_loss.get('start_disp', 0) dilation = cfg.model.losses.focal_loss.get('dilation', 1) weights = cfg.model.losses.focal_loss.get('weights', None) coefficient = cfg.model....
class StateDictType(enum.Enum): DIFFUSERS_OLD = 'diffusers_old' PEFT = 'peft' DIFFUSERS = 'diffusers'
class ConsistentMCDropout2d(_ConsistentMCDropout): def _get_sample_mask_shape(self, sample_shape): return ([sample_shape[0]] + ([1] * (len(sample_shape) - 1)))
class StreamingEpochBatchIterator(EpochBatchIterating): def __init__(self, dataset, max_sentences=1, collate_fn=None, epoch=1, num_workers=0, buffer_size=0, timeout=0, persistent_workers=False): assert isinstance(dataset, torch.utils.data.IterableDataset) self.dataset = dataset self.max_sent...
def CFNet(d, replace_mish=False): net = cfnet(d, use_concat_volume=True) if replace_mish: replace_layers(net, Mish, nn.ReLU(inplace=True)) print('replacing', Mish(), '->', nn.ReLU()) return net
def cross_entropy2d(input, target, weight=None, val=False): if val: size_average = False else: size_average = True (n, c, h, w) = input.size() log_p = F.log_softmax(input, dim=1) log_p = log_p.transpose(1, 2).transpose(2, 3).contiguous().view((- 1), c) log_p = log_p[(target.view(...
('action') def action(ac_data): room = state.get_room_for_client(request.sid) LOG.debug('Received action %s in room %s ', ac_data, room.id) game = room.game metadata = {'mturk_id': mturk_params(request.args)['workerId']} if ('virtual_room_id' in ac_data): vroom = ac_data['virtual_room_id'] ...
class Sigurbergsson2019(dataset.Dataset): name = 'sigurbergsson2019' url = ' hash = 'fb5c41c385062af222f68c8ebb2f7a86da26c081f6822f0' files = [{'name': 'sigurbergsson2019da.csv', 'language': 'da', 'type': 'training', 'platform': 'unknown'}] license = 'UNKNOWN' def process(cls, tmp_file_path, dat...
def test_find_duplicates_dir_num_enc_workers(cnn, mocker): num_enc_workers = 2 cnn.encoding_map = data_encoding_map() ret_val_find_dup_dict = {'filename1.jpg': [('dup1.jpg', 0.82)], 'filename2.jpg': [('dup2.jpg', 0.9)]} encode_images_mocker = mocker.patch('imagededup.methods.cnn.CNN.encode_images') ...
def set_grad_none(model, targets): for (n, p) in model.named_parameters(): if (n in targets): p.grad = None
class SupervisedDataset(Dataset): def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer): super(SupervisedDataset, self).__init__() logging.warning('Loading data...') list_data_dict = json.load(open(data_path, 'r')) logging.warning('Formatting inputs...') ...
def write_latest_filename(output_label, latest_filename): latest_fits_filename_holder = os.path.join('latest_filenames', 'latest_{}.txt'.format(output_label)) ensure_containing_directory_exists(latest_fits_filename_holder) with open(latest_fits_filename_holder, 'w') as stream: stream.write(latest_fi...
class SECONDNet(Detector3DTemplate): def __init__(self, model_cfg, num_class, dataset): super().__init__(model_cfg=model_cfg, num_class=num_class, dataset=dataset) self.module_list = self.build_networks() def forward(self, batch_dict): for cur_module in self.module_list: batc...
class MultiScalePrior(Flow): def __init__(self, in_channels, hidden_channels, h_channels, factor, transform, alpha, inverse, coupling_type, h_type, activation, normalize, num_groups): super(MultiScalePrior, self).__init__(inverse) self.conv1x1 = Conv1x1Flow(in_channels, inverse=inverse) self...
class ATCDataASR(datasets.GeneratorBasedBuilder): DEFAULT_WRITER_BATCH_SIZE = 256 DEFAULT_CONFIG_NAME = 'all' BUILDER_CONFIGS = [ATCDataASRConfig(name='train', description='ATC train dataset.'), ATCDataASRConfig(name='dev', description='ATC dev dataset.'), ATCDataASRConfig(name='test', description='ATC test...
class Barrier(Node): def __init__(self, children): super().__init__('barrier', children, None) def qasm(self, prec=15): return (('barrier ' + self.children[0].qasm(prec)) + ';')
_module class XMLDataset(CustomDataset): def __init__(self, min_size=None, **kwargs): super(XMLDataset, self).__init__(**kwargs) self.cat2label = {cat: (i + 1) for (i, cat) in enumerate(self.CLASSES)} self.min_size = min_size def load_annotations(self, ann_file): img_infos = [] ...
class Normalize(tv_t.Normalize): def __init__(self, mean, std, inplace=False) -> None: super().__init__(mean, std, inplace)
class TimeInvariantMLSAFilter(object): def __init__(self, coef, alpha, n_shift): self.coef = coef self.n_shift = n_shift self.mlsa_filter = pysptk.synthesis.Synthesizer(pysptk.synthesis.MLSADF(order=(coef.shape[0] - 1), alpha=alpha), hopsize=n_shift) def __call__(self, y): assert...
class II2S(nn.Module): def __init__(self, opts): super(II2S, self).__init__() self.opts = opts self.net = Net(self.opts) self.load_downsampling() self.setup_loss_builder() self.set_up_face_predictor() def load_downsampling(self): factor = (self.opts.size /...
def retrieve_info_for_model(model_type, frameworks: Optional[List[str]]=None): if (model_type not in auto_module.MODEL_NAMES_MAPPING): raise ValueError(f'{model_type} is not a valid model type.') model_name = auto_module.MODEL_NAMES_MAPPING[model_type] config_class = auto_module.configuration_auto.C...
class BiReLUFunction(InplaceFunction): def forward(ctx, input, inplace=False): if ((input.size(1) % 2) != 0): raise RuntimeError('dimension 1 of input must be multiple of 2, but got {}'.format(input.size(1))) ctx.inplace = inplace if ctx.inplace: ctx.mark_dirty(input)...
def deep_merge(base_item, new_item): if (isinstance(base_item, dict) and isinstance(new_item, dict)): ret = deepcopy(base_item) for key in new_item: if (key in ret): ret[key] = deep_merge(ret[key], new_item[key]) else: ret[key] = new_item[key] ...
def evaluate(config: DictConfig) -> None: OmegaConf.set_struct(config, False) checkpoint_type = config.eval.get('checkpoint_type', 'lightning') if (checkpoint_type not in ['lightning', 'pytorch']): raise NotImplementedError(f'checkpoint_type ${checkpoint_type} not supported') if (checkpoint_type...
class SENet_senti_attention_wise(nn.Module): def __init__(self, C): super(SENet_senti_attention_wise, self).__init__() self.base = models.resnet101(pretrained=True) self.spatial = senti_block() self.fc = nn.Linear(2048, 3) def forward(self, x): for (name, module) in self....
class TestUtils(unittest.TestCase): ('numpy.random.randint') def test_random_crop(self, mock_np_random_randint): mock_np_random_randint.return_value = 1 test_img = np.expand_dims(np.array([[0, 255], [0, 255]]), axis=2) crop_dims = (1, 1) cropped_img = utils.random_crop(test_img, ...
.ml_torch_only def test_ragged_to_dense(dtype, ml): values = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], dtype=dtype) row_splits = np.array([0, 2, 4, 4, 5, 12, 13], dtype=np.int64) out_col_size = 4 default_value = np.array((- 1), dtype=dtype) ans = mltest.run_op(ml, ml.device, True, ml.ops....
_update_dense(default_config=ConfigDense()) def test_cg_dense(*args, **kwargs): f = _test_cg_gpr(*args, **kwargs) mf = tf.reduce_mean(f, axis=0) res = tf.squeeze((f - mf), axis=(- 1)) Sff = (tf.matmul(res, res, transpose_a=True) / f.shape[0]) return (mf, Sff)
def preprocess_image(image, is_training): if is_training: image = tf.image.resize_image_with_crop_or_pad(image, (HEIGHT + 8), (WIDTH + 8)) image = tf.random_crop(image, [HEIGHT, WIDTH, DEPTH]) image = tf.image.random_flip_left_right(image) image = tf.image.per_image_standardization(image...
def rprecision(guess_item, gold_item, rank_keys): gold_ids_list = _get_ids_list(gold_item, rank_keys) guess_ids = _get_ids_list(guess_item, rank_keys)[0] Rprec_vector = [] for gold_ids in gold_ids_list: Rprec = _computeRprec(guess_ids, gold_ids) Rprec_vector.append(Rprec) return max(...
def resnet18_mpncov_160(pretrained=False, progress=True, **kwargs): return _resnet_mpncov_160('resnet18_mpncov_160', BasicBlock, [2, 2, 2, 2], pretrained, progress, **kwargs)
class ANYDataset(): def initialize(self, opt): self.data_size = 0 def __len__(self): return self.data_size def name(self): return 'ANY'
_module() class IterTimerHook(Hook): def before_epoch(self, runner): self.t = time.time() def before_iter(self, runner): runner.log_buffer.update({'data_time': (time.time() - self.t)}) def after_iter(self, runner): runner.log_buffer.update({'time': (time.time() - self.t)}) se...
class FrozenPbModel(TFModel): def supports_path(path: str) -> bool: return ('frozen_pb' == get_model_type(path)) def supports_profiling(self) -> bool: return True
(events=subsets(_ALL_EVENTS_WITH_HANDLERS)) _events_with_registered_handlers_to_subset def test_list_nested_in_dict(events): assert (_RECORDED_EVENTS == []) run_cell('x = {1: [2, 3, 4]}') throw_and_print_diff_if_recorded_not_equal_to(filter_events_to_subset([TraceEvent.init_module, TraceEvent.before_stmt, T...
def train(max_walk_length, p, q, run): g = nx.planted_partition_graph(n_communities, community_size, p_in, p_out) labels = np.zeros(((n_communities * community_size), n_communities), dtype=np.float32) for c in range(n_communities): labels[(range((c * community_size), ((c + 1) * community_size)), c)]...
class GroundTruthDatasetFactory(Dataset): def __init__(self, train_gt_images, val_gt_images, test_gt_images, inner_circle=True): self.train_gt_images = train_gt_images self.val_gt_images = val_gt_images self.test_gt_images = test_gt_images assert (self.train_gt_images.shape[1] == sel...
class PoolerEndLogits(nn.Module): def __init__(self, hidden_size, num_classes): super(PoolerEndLogits, self).__init__() self.dense_0 = nn.Linear(hidden_size, hidden_size) self.activation = nn.Tanh() self.LayerNorm = nn.LayerNorm(hidden_size) self.dense_1 = nn.Linear(hidden_si...
def log_args(args): logging.info('\n+ Hyperpixel Flow Arguments +') for arg_key in args.__dict__: logging.info(('| %20s: %-24s |' % (arg_key, str(args.__dict__[arg_key])))) logging.info('++\n')
class FurthestPointSampling(Function): def forward(ctx, points_xyz: torch.Tensor, num_points: int) -> torch.Tensor: assert points_xyz.is_contiguous() (B, N) = points_xyz.size()[:2] output = torch.cuda.IntTensor(B, num_points) temp = torch.cuda.FloatTensor(B, N).fill_(.0) ext_...
class TestNoiseAdaptiveLayout(QiskitTestCase): def test_on_linear_topology(self): calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0) qr = QuantumRegister(2, name='q') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit)...
def line_on_mask(line, mask, width=2, iou_threshold=0.6): iou = compute_iou_mask_and_line(line, mask, width) return (iou > iou_threshold)
class _pure_kv_variable_scope(): def __init__(self, name_or_scope, reuse=None, initializer=None, regularizer=None, caching_device=None, partitioner=None, custom_getter=None, old_name_scope=None, dtype=dtypes.float32, use_resource=None, constraint=None): self._name_or_scope = name_or_scope self._reus...
class ILPolicy(Policy, metaclass=abc.ABCMeta): def __init__(self, net, dim_actions): super(Policy, self).__init__() self.net = net self.dim_actions = dim_actions self.action_distribution = CategoricalNet(self.net.output_size, self.dim_actions) def forward(self, *x): raise...
def main(): parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--env', help='environment ID (0==sine, 1==stand, 2=reset, 3=overheat)', type=int, default=0) args = parser.parse_args() print(('--env=' + str(args.env))) if (args.env == 0): ...
def merging_lora_with_base(pipe, ckpt_dir, adapter_name='default'): unet_sub_dir = os.path.join(ckpt_dir, 'unet') text_encoder_sub_dir = os.path.join(ckpt_dir, 'text_encoder') if isinstance(pipe.unet, PeftModel): pipe.unet.set_adapter(adapter_name) else: pipe.unet = PeftModel.from_pretra...
def flip_first_two_dim(inp): if (len(inp.size()) == 2): return inp.permute(1, 0).contiguous() elif (len(inp.size()) == 3): return inp.permute(1, 0, 2).contiguous()
.dataclass class DDIMSchedulerState(): common: CommonSchedulerState final_alpha_cumprod: jnp.ndarray init_noise_sigma: jnp.ndarray timesteps: jnp.ndarray num_inference_steps: Optional[int] = None def create(cls, common: CommonSchedulerState, final_alpha_cumprod: jnp.ndarray, init_noise_sigma: jn...
def get_icd9_descript_dict(path): lines = _read_file(path) icd9_descript_dict = {} for l in lines[1:]: elems = l.split('\t') try: assert (len(elems) == 8) except: print('Problem with following line while loading icd9_descript_dict:') print(l) ...
def convert_layer(layer, mode, copy_weights, layer_config=None, output_dim=None): (layer_bias, bias_weight) = (False, None) if (('weight' in layer.__dict__['_parameters']) and copy_weights): weight = layer.weight if (('bias' in layer.__dict__['_parameters']) and (layer.bias is not None)): bi...
def get_tfrecord_by_location(tfrecord: str, location: Tuple[(int, int)], decode: bool=True, *, locations_array: Optional[List[Tuple[(int, int)]]]=None, index_array: Optional[np.ndarray]=None) -> Any: if isinstance(location, list): location = tuple(location) if ((not isinstance(location, tuple)) or (len(...
def require_onnx(test_case): if (not is_onnx_available()): return unittest.skip('test requires ONNX')(test_case) else: return test_case
def wrn28_10(num_classes=10, dropout=False): model = Wide_ResNet(depth=28, widen_factor=10, num_classes=num_classes) return model
def finalize_config(cfg, cfg_file_path, cfg_cmd_string): if (cfg_file_path is not None): __merge_config_from_file(cfg, cfg_file_path) if (cfg_cmd_string is not None): __merge_config_from_cmdline(cfg, cfg_cmd_string) cfg.immutable(True)
def parse_device_type(str): mace_check((str in DEVICE_MAP), ('unknown device %s' % str)) return DEVICE_MAP[str]
class Constants(ConstantsBase): def __init__(self, **kwargs): self.RUN = 'test' w = 1e-10 self.P = problems.Sin1D_2(w=w, A=0, B=((- 1) / w)) self.SUBDOMAIN_XS = get_subdomain_xs([np.array([2, 3, 2, 4, 3])], [((2 * np.pi) / self.P.w)]) self.SUBDOMAIN_WS = get_subdomain_ws(self...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_channels, out_channels, stride=1): super().__init__() self.residual_function = nn.Sequential(nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=T...
def test_inv_link_logit(): scores = np.array([[np.inf, (- np.inf), 999.0, (- 999.0), 0.0, 1.0986123, np.nan]]) expected = np.array([[[0.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.5, 0.5], [0.25, 0.75], [np.nan, np.nan]]]) result = inv_link(scores, 'logit') np.testing.assert_almost_equal(result, exp...
def main_upper(x_minus, x_plus, y_minus, y_plus, plot=False, num=0, print_info=True): if print_info: print('14 orthant upper: using 23 orthant lower function') x_minus_new = (- x_plus) x_plus_new = (- x_minus) (a, b, c) = lower.main_lower(x_minus_new, x_plus_new, y_minus, y_plus, print_info=prin...
def generate_dataset(seed, in_file, tokenizer_name, out_dir, eval_ratio): tokenizer = transformers.AutoTokenizer.from_pretrained(tokenizer_name, use_fast=False) with open(in_file, 'r') as f: conversations = json.load(f) random.seed(seed) random.shuffle(conversations) eval_num = int((eval_rat...
class ParserFileManager(object): def __init__(self, grammar_dir): self.grammar_dir = Path(grammar_dir) self.max_size = 12 self.logger = LaLogger.getInstance().get_logger(LoggerTypeEnum.DEFAULT) self.parser_dict = {} self.prefix = 'parser' self.module_dir = 'iheartla' ...
def save_vocab(count=[], name='vocab.txt'): pwd = os.getcwd() vocabulary_size = len(count) with open(os.path.join(pwd, name), 'w') as f: for i in xrange(vocabulary_size): f.write(('%s %d\n' % (tf.compat.as_text(count[i][0]), count[i][1]))) print(('%d vocab saved to %s in %s' % (vocab...
def compare_dataframes(gts, ts): accs = [] names = [] for (k, tsacc) in ts.items(): if (k in gts): logging.info('Comparing {}...'.format(k)) accs.append(mm.utils.compare_to_groundtruth(gts[k], tsacc, 'iou', distth=0.5)) names.append(k) else: lo...
class StickPlot(): def __init__(self, title, stick_figure_edges, ax, elev=17, azim=47, rang=800): self.lines = [] self.ghost_lines = [] self.initialized = False self.ax = ax self.ax.set_title(title) self.ax.view_init(elev=elev, azim=azim) self.ax.set_xlim3d((-...
def use_gpu(compute_device_type='CUDA', use_cpu=True) -> None: C = bpy.context preferences = bpy.context.preferences cycles_preferences = preferences.addons['cycles'].preferences compute_devices = [d[0] for d in cycles_preferences.get_device_types(C)] if (compute_device_type not in compute_devices):...
class Writer(): def __init__(self, opt): self.name = opt.name self.opt = opt self.save_dir = os.path.join(opt.checkpoints_dir, opt.name) self.log_name = os.path.join(self.save_dir, 'loss_log.txt') self.testacc_log = os.path.join(self.save_dir, 'testacc_log.txt') self....
_module() class DavarLoadImageFromFile(): def __init__(self, decode_from_array=False, to_float32=False): self.decode_from_array = decode_from_array self.to_float32 = to_float32 def __call__(self, results): if self.decode_from_array: data_array = results['img_info'] ...
class LongformerOnnxConfig(OnnxConfig): def inputs(self) -> Mapping[(str, Mapping[(int, str)])]: return OrderedDict([('input_ids', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'})]) def outputs(self) -> Mapping[(str, Mapping[(int, str)])]: return OrderedDict([('last_...
def search_by_batch(model, beams, mem_dict): def ready_to_submit(hypotheses): inp = model.prepare_incremental_input([hyp.seq[(- 1):] for hyp in hypotheses]) concat_hyps = dict() for hyp in hypotheses: for (k, v) in hyp.state_dict.items(): concat_hyps[k] = (concat_...
class SensorSuite(): sensors: Dict[(str, Sensor)] observation_spaces: SpaceDict def __init__(self, sensors: Iterable[Sensor]) -> None: self.sensors = OrderedDict() spaces: OrderedDict[(str, Space)] = OrderedDict() for sensor in sensors: assert (sensor.uuid not in self.sen...