code
stringlengths
101
5.91M
def log_Normal_diag(sample, mean, log_var): return ((- 0.5) * (log_var + (K.square((sample - mean)) / K.exp(log_var))))
def getAllWords(fName): dat = open(fName).read() dat = json.loads(dat) dat = dat['questions'] wordsX = [] wordsY = [] for e in dat: wordsX += e['question'].lower()[:(- 1)].split() if ('answer' in e.keys()): wordsY += e['answer'].lower().split() return ((wordsX + [...
def replace_unk(beam_lst, lst_src, int_order): result = [] for (idx, num) in enumerate(int_order): fields = get_wikibio_poswrds(lst_src[num]) fields = [wrd for ((k, idx), wrd) in fields.items()] result.append(fields) result_2 = [] x_idx = 0 temp_store = [] for ii in range...
class FusedBiasLeakyReLUFunctionBackward(Function): def forward(ctx, grad_output, out, negative_slope, scale): ctx.save_for_backward(out) ctx.negative_slope = negative_slope ctx.scale = scale empty = grad_output.new_empty(0) grad_input = ext_module.fused_bias_leakyrelu(grad_o...
def test_linear_regression(): dataset = load_diabetes() (X, y) = (dataset.data, dataset.target) feature_names = dataset.feature_names sk_lr = SKLinear() our_lr = LinearRegression(feature_names=feature_names) sk_lr.fit(X, y) our_lr.fit(X, y) sk_pred = sk_lr.predict(X) our_pred = our_l...
def sanity_check_paramter_updates(model, last_ckpt): for (i, v) in model.named_modules(): if (hasattr(v, 'weight') and hasattr(v, 'popup_scores')): if (getattr(v, 'weight') is not None): w1 = getattr(v, 'weight').data.cpu() w2 = last_ckpt[(i + '.weight')].data.cpu...
def get_keywords(): git_refnames = ' (HEAD -> main)' git_full = 'e12c47d414dceb457ce128bf87c67fbd4479f14a' git_date = '2021-12-04 07:26:07 -0800' keywords = {'refnames': git_refnames, 'full': git_full, 'date': git_date} return keywords
def load_dataset_splits(task, splits): for split in splits: if (split == 'train'): task.load_dataset(split, combine=True) else: for k in itertools.count(): split_k = (split + (str(k) if (k > 0) else '')) try: task.load_datas...
def _cfgs_to_fx_cfgs(op_cfgs, observer_type='post_training_static_quant'): version = get_torch_version() if (observer_type == 'post_training_dynamic_quant'): model_qconfig = torch.quantization.default_dynamic_qconfig elif (observer_type == 'quant_aware_training'): model_qconfig = (torch.quan...
class TestDetInferencer(TestCase): ('mmengine.infer.infer._load_checkpoint', return_value=None) def test_init(self, mock): DetInferencer('rtmdet-t') DetInferencer('configs/yolox/yolox_tiny_8xb8-300e_coco.py') def assert_predictions_equal(self, preds1, preds2): for (pred1, pred2) in z...
class NormalizationWrapper(torch.nn.Module): def __init__(self, model, mean, std): super().__init__() mean = torch.tensor(mean) std = torch.tensor(std) mean = mean[(..., None, None)] std = std[(..., None, None)] self.train(model.training) self.model = model ...
def plot_precision_recall_curve_sklearn(y_hat: np.ndarray, y_true: np.ndarray, y_hat_probs: np.ndarray, save_plot: bool=True, save_fpath: str='2022_02_02_precision_recall.pdf') -> None: y_true_list = [] probas_pred = [] for (y_hat_, y_true_, y_hat_prob_) in zip(y_hat, y_true, y_hat_probs): y_true_li...
class MultipleMetrics(object): def __init__(self, metrics: List[Metric], prefix: str=''): instantiated_metrics = [] for metric in metrics: if isinstance(metric, type): instantiated_metrics.append(metric()) else: instantiated_metrics.append(metr...
class TFAutoModelForQuestionAnswering(object): def __init__(self): raise EnvironmentError('TFAutoModelForQuestionAnswering is designed to be instantiated using the `TFAutoModelForQuestionAnswering.from_pretrained(pretrained_model_name_or_path)` or `TFAutoModelForQuestionAnswering.from_config(config)` method...
class DwsConvBlock(nn.Module): def __init__(self, in_channels, out_channels, stride): super(DwsConvBlock, self).__init__() self.dw_conv = dwconv3x3_block(in_channels=in_channels, out_channels=in_channels, stride=stride) self.pw_conv = conv1x1_block(in_channels=in_channels, out_channels=out_c...
def collate_custom(batch): if isinstance(batch[0], np.int64): return np.stack(batch, 0) if isinstance(batch[0], torch.Tensor): return torch.stack(batch, 0) elif isinstance(batch[0], np.ndarray): return np.stack(batch, 0) elif isinstance(batch[0], int_classes): return torc...
def header_properties(field_list, field_names): lines = [] lines.append(('element vertex %d' % field_list[0].shape[0])) i = 0 for fields in field_list: for field in fields.T: lines.append(('property %s %s' % (field.dtype.name, field_names[i]))) i += 1 return lines
def unit_vector(elevation_angle: np.float64, azimuthal_angle: np.float64) -> np.ndarray: elevation_angle_in_radians = np.deg2rad(elevation_angle) azimuthal_angle_in_radians = np.deg2rad(azimuthal_angle) return np.array([(np.cos(elevation_angle_in_radians) * np.sin(azimuthal_angle_in_radians)), (np.cos(eleva...
class NXDOManagerWithServer(NXDOManager): def __init__(self, solve_restricted_game: SolveRestrictedGame, n_players: int=2, log_dir: str=None, manager_metadata: dict=None, port: int=4545): super(NXDOManagerWithServer, self).__init__(solve_restricted_game=solve_restricted_game, n_players=n_players, log_dir=lo...
class Orthogonal(Initializer): def __init__(self, gain=1.0): if (gain == 'relu'): gain = np.sqrt(2) self.gain = gain def sample(self, shape): if (len(shape) < 2): raise RuntimeError('Only shapes of length 2 or more are supported.') flat_shape = (shape[0], ...
class TestRPN(TestCase): def setUp(self): register_all_modules() (['rpn/rpn_r50_fpn_1x_coco.py']) def test_init(self, cfg_file): model = get_detector_cfg(cfg_file) model.backbone.depth = 18 model.neck.in_channels = [64, 128, 256, 512] model.backbone.init_cfg = None ...
def clip_noise_schedule(alphas2, clip_value=0.001): alphas2 = np.concatenate([np.ones(1), alphas2], axis=0) alphas_step = (alphas2[1:] / alphas2[:(- 1)]) alphas_step = np.clip(alphas_step, a_min=clip_value, a_max=1.0) alphas2 = np.cumprod(alphas_step, axis=0) return alphas2
def test_rvalue_ref_param(): r = m.RValueRefParam() assert (r.func1('123') == 3) assert (r.func2('1234') == 4) assert (r.func3('12345') == 5) assert (r.func4('123456') == 6)
class HumanOutputFormat(KVWriter, SeqWriter): def __init__(self, filename_or_file): if isinstance(filename_or_file, str): self.file = open(filename_or_file, 'wt') self.own_file = True else: assert hasattr(filename_or_file, 'read'), ('expected file or str, got %s' ...
_registry(pattern_type='Transformer2Dmodel_QKVReshapeTo4D') class Transformer2Dmodel_QKVReshapeTo4D(Pattern): def __call__(self, model): pattern_mapping_config = {'Transformer2Dmodel_QKVReshapeTo4D': [{'patterns': {'in': [[(0, 'Shape'), (1, 'Gather'), (2, 'Div'), (3, 'Cast'), (4, 'Cast'), (5, 'Unsqueeze'), ...
def main(): cfg.merge_from_file(args.config) dataset_root = os.path.join(your_dataset_path, args.dataset) model = ModelBuilder() model = load_pretrain(model, args.snapshot).cuda().eval() tracker = build_tracker(model) dataset = DatasetFactory.create_dataset(name=args.dataset, dataset_root=datase...
class LinearSchedule(ScalarSchedule): def __init__(self, init_value, final_value, ramp_duration): self._init_value = init_value self._final_value = final_value self._ramp_duration = ramp_duration def get_value(self, t): return (self._init_value + ((self._final_value - self._init_...
def _split_string_to_tokens(text): if (not text): return [] ret = [] token_start = 0 is_alnum = [(c in _ALPHANUMERIC_CHAR_SET) for c in text] for pos in xrange(1, len(text)): if (is_alnum[pos] != is_alnum[(pos - 1)]): token = text[token_start:pos] if ((token !...
def vgg19_bn(pretrained=False, **kwargs): model = VGG(make_layers(cfg['E'], batch_norm=True), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg19_bn'])) return model
def test_gym_environment(env, ctxt=None, seed=1): set_seed(seed) with LocalTFRunner(snapshot_config=ctxt) as runner: policy = CategoricalMLPPolicy(name='policy', env_spec=env.spec, hidden_sizes=(32, 32)) obs_var = tf.compat.v1.placeholder(tf.float32, shape=[None, None, env.observation_space.flat...
class SupervisionStrategy(ABC): def get_image_pair(self, batch, *args): pass def get_correlation(self, correlation_matrix): pass def compute_loss(self, correlation_matrix, *args): pass
class ManualTask(ABSTask): def __init__(self, ns: str, obstacles_manager: ObstaclesManager, robot_manager: RobotManager): super().__init__(obstacles_manager, robot_manager) self.ns = ns self.ns_prefix = ('' if (ns == '') else (('/' + ns) + '/')) rospy.Subscriber(f'{self.ns}manual_goa...
class TensorboardLogger(object): def __init__(self): self._logger = None self._global_step = 0 def create(self, path): self._logger = tensorboardX.SummaryWriter(path) def noop(self, *args, **kwargs): return def step(self): self._global_step += 1 def global_ste...
class BaseTask(): def __init__(self, work_root: Optional[Union[(str, Path)]], data: dict, model_builder: Callable, train_builder: Callable, evaluator: BaseEvaluator, device: torch.device, structure_builder: Optional[Callable]=None, study_name: Optional[str]=None, overwrite: bool=True): self.data = data ...
def get_data_layer(roidb, num_classes): if cfg.TRAIN.HAS_RPN: if cfg.IS_MULTISCALE: raise 'Calling caffe modules...' else: layer = RoIDataLayer(roidb, num_classes) else: layer = RoIDataLayer(roidb, num_classes) return layer
def dot(l1=[], l2=[]): sum1 = 0 for i in range(0, len(l1)): sum1 = ((l1[i] * l2[i]) + sum1) return sum1
def resnet34(num_classes=1000, pretrained='imagenet'): model = models.resnet34(pretrained=False) if (pretrained is not None): settings = pretrained_settings['resnet34'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_resnets(model) return model
class DependenceData(object): def __init__(self, module='', initialized_list=[], name_list=[]): self.module = module self.name_list = name_list self.initialized_list = initialized_list
def get_feature_iterator(feature_type, checkpoint_path, layer, manifest_path, sample_pct): feature_reader_cls = get_feature_reader(feature_type) with open(manifest_path, 'r') as fp: lines = fp.read().split('\n') root = lines.pop(0).strip() file_path_list = [os.path.join(root, line.split(...
def run(args, error_queue): try: single_process_main(args) except KeyboardInterrupt: pass except Exception: import traceback error_queue.put((args.rank, traceback.format_exc()))
def triangle(x, loc=0, size=0.5, area=1): return (0 if (abs(((x - loc) / size)) > 1) else ((1 - abs(((x - loc) / size))) * abs((area / size))))
def resume_checkpoint(model, optimizer, checkpoint_filename, opt, map_location='cpu'): logging.info(('resuming from ' + checkpoint_filename)) checkpoint = torch.load(checkpoint_filename, map_location=map_location) assert ('state_dict' in checkpoint) state_dict = checkpoint['state_dict'] model.load_s...
class GridWorldEnv(Env): UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3 STAY = 4 CONTROL_NAMES = ['UP', 'RIGHT', 'DOWN', 'LEFT', 'STAY'] def __init__(self, shape=[2, 2], init_state=None): self.shape = shape self.n_states = np.prod(shape) self.n_observations = self.n_states ...
class _ConvNdKernel(Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation, transposed, output_padding, groups, bias): super(_ConvNdKernel, self).__init__() if ((in_channels % groups) != 0): raise ValueError('in_channels must be divisible by groups'...
def data_collator(features: list) -> dict: len_ids = [len(feature['input_ids']) for feature in features] longest = max(len_ids) input_ids = [] labels_list = [] for (ids_l, feature) in sorted(zip(len_ids, features), key=(lambda x: (- x[0]))): ids = feature['input_ids'] seq_len = featu...
def test_actionAngle_input_wrongunits(): from galpy.actionAngle import actionAngleSpherical from galpy.potential import PlummerPotential pot = PlummerPotential(normalize=1.0, b=0.7) aA = actionAngleSpherical(pot=pot, ro=8.0, vo=220.0) with pytest.raises(units.UnitConversionError) as excinfo: ...
class Data(): def __init__(self, data_dir='data/FB15k-237/', reverse=False): self.train_data = self.load_data(data_dir, 'train', reverse=reverse) self.valid_data = self.load_data(data_dir, 'valid', reverse=reverse) self.test_data = self.load_data(data_dir, 'test', reverse=reverse) se...
class DatabaseGenerator(Generator): def __init__(self, database: chex.Array): self._boards = jnp.asarray(database) def __call__(self, key: chex.PRNGKey) -> State: (key, idx_key) = jax.random.split(key) idx = jax.random.randint(idx_key, shape=(), minval=0, maxval=self._boards.shape[0]) ...
def train_scan(scan_net, inference_vectorizer, train_Xy, val_Xy, epochs=1, batch_size=1, patience=3): (train_Xy, val_Xy) = (train_reformat(train_Xy), scan_reform(val_Xy)) optimizer = optim.Adam(scan_net.parameters()) criterion = nn.BCELoss(reduction='sum') total_epoch_loss = [] for epoch in range(ep...
def clean_hparams_dict(hparams_dict): return {key: val for (key, val) in hparams_dict.items() if val}
def get_last_checkpoint(folder): content = os.listdir(folder) checkpoints = [path for path in content if ((_re_checkpoint.search(path) is not None) and os.path.isdir(os.path.join(folder, path)))] if (len(checkpoints) == 0): return return os.path.join(folder, max(checkpoints, key=(lambda x: int(_...
.vcr() def test_extract_extract_references_from_url(app_client): journal_kb_data = {'COMMUNICATIONS IN ASTEROSEISMOLOGY': 'Commun.Asteros.', 'PHYS REV': 'Phys.Rev.', 'PHYSICAL REVIEW': 'Phys.Rev.', 'PHYS REV LETT': 'Phys.Rev.Lett.', 'JINST': 'JINST', 'JOURNAL OF INSTRUMENTATION': 'JINST', 'SENS ACTUATORS B': 'Sens....
_model def hrnet_w18(pretrained=True, **kwargs): return _create_model('hrnet_w18', pretrained, kwargs)
class InvertedResidual(nn.Module): def __init__(self, in_chs, out_chs, dw_kernel_size=3, stride=1, dilation=1, pad_type='', act_layer=nn.ReLU, noskip=False, exp_ratio=1.0, exp_kernel_size=1, pw_kernel_size=1, se_ratio=0.0, se_kwargs=None, norm_layer=nn.BatchNorm2d, norm_kwargs=None, conv_kwargs=None, drop_path_rate...
class DMFNet(MFNet): def __init__(self, in_channels, num_classes, n=32, channels=128, groups=16, norm='bn'): super(DMFNet, self).__init__(in_channels, num_classes, n, channels, groups, norm) self.encoder_block2 = nn.Sequential(DMFUnit(n, channels, g=groups, stride=2, norm=norm, dilation=[1, 2, 3]), ...
def new_ps_resource_optimizer(optimize_mode: str, job_uuid, resoure_limits: ResourceLimits): logger.info('New %s resource optimizer for job %s', optimize_mode, job_uuid) if (optimize_mode == OptimizeMode.CLUSTER): if GlobalBrainClient.BRAIN_CLIENT.available(): return BrainResoureOptimizer(j...
_registry(pattern_type='ReshapeBeforeRestoreHiddenStates') class ReshapeBeforeRestoreHiddenStates(Pattern): def __call__(self, model): pattern_mapping_config = {'ReshapeBeforeRestoreHiddenStates': [{'patterns': {'in': [[(0, 'LayerNorm'), (1, 'ScatterElements')]], 'out': [[(0, 'LayerNorm'), (1, 'Reshape'), (...
def double_double_laurent_cascade_step(dim, embsys, esols, tasks=0): from phcpy.phcpy2c3 import py2c_copy_dobldobl_Laurent_container_to_start_system from phcpy.phcpy2c3 import py2c_copy_dobldobl_container_to_start_solutions from phcpy.phcpy2c3 import py2c_dobldobl_Laurent_cascade_homotopy from phcpy.phc...
def set_optimizer(cN, lrate_in, minibatch_multiplier, lazy_regularization=True, clip=None): args = dict(cN.opt_args) args['minibatch_multiplier'] = minibatch_multiplier args['learning_rate'] = lrate_in if lazy_regularization: mb_ratio = (cN.reg_interval / (cN.reg_interval + 1)) args['lea...
class ChatGLMConfig(PretrainedConfig): model_type = 'chatglm' def __init__(self, vocab_size=150528, hidden_size=4096, num_layers=28, num_attention_heads=32, layernorm_epsilon=1e-05, use_cache=False, bos_token_id=150004, eos_token_id=150005, mask_token_id=150000, gmask_token_id=150001, pad_token_id=0, max_sequen...
def annotations_to_jsonl(annotations, output_file): with open(output_file, 'w') as of: for ann in sorted(annotations, key=(lambda x: x.annotation_id)): as_json = _annotation_to_dict(ann) as_str = json.dumps(as_json, sort_keys=True) of.write(as_str) of.write('\...
class RandomGrayscale(object): def __init__(self, p=0.1): self.p = p self.tv_F = tv_t.Grayscale(self.size, self.vertical_flip) self.cv_F = cv_t.Grayscale(self.size, self.vertical_flip) def __call__(self, img): if (type(img) == np.ndarray): return self.cv_F.__call__(im...
def DenseNet201(Num_classes=10): return DenseNet(Bottleneck, [6, 12, 48, 32], growth_rate=32, num_classes=Num_classes)
class LayoutLMModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def save_zip(url, loc): if (not os.path.exists(loc)): urllib.request.urlretrieve(url, loc)
def is_plugin_enabled(plugin_name): if ((plugin_name in plugins) and plugins[plugin_name]['enable']): return True return False
def open_image(path: str) -> 'JpegImageFile': from PIL import Image if path.startswith('hdfs'): import pyarrow as pa fs = pa.hdfs.connect() with fs.open(path, 'rb') as f: image = Image.open(f) image.load() return image elif path.startswith('s3'): ...
def init_logger(log_file=None): log_format = logging.Formatter('[%(levelname)s] %(message)s') logger = logging.getLogger() logger.setLevel(logging.INFO) console_handler = logging.StreamHandler() console_handler.setFormatter(log_format) logger.handlers = [console_handler] if (log_file and (lo...
class CodeDataset(FairseqDataset): def __init__(self, manifest, dictionary, dur_dictionary, f0_dictionary, config, discrete_dur, discrete_f0, log_f0, normalize_f0_mean, normalize_f0_std, interpolate_f0, return_filename=False, strip_filename=True, shifts='0,0', return_continuous_f0=False): random.seed(1234) ...
def YOLO(): global metaMain, netMain, altNames configPath = './cfg/yolov4.cfg' weightPath = './yolov4.weights' metaPath = './cfg/coco.data' if (not os.path.exists(configPath)): raise ValueError((('Invalid config path `' + os.path.abspath(configPath)) + '`')) if (not os.path.exists(weight...
def standard_random_system(neq, nvr, nbrmon, deg, cff): from phcpy.phcpy2c3 import py2c_syscon_random_system from phcpy.interface import load_standard_system py2c_syscon_random_system(nvr, nbrmon, deg, cff, neq) return load_standard_system()
def load_and_migrate_checkpoint(ckpt_path): checkpoint = torch.load(ckpt_path, map_location='cpu') migrated_state_dict = {} for (key, value) in checkpoint['state_dict'].items(): key = key.replace('joint_net', 'joint.net') migrated_state_dict[key] = value del migrated_state_dict['audio_pr...
def format_dataset_name(dataset_name): if (dataset_name == 'cos_e'): return 'cos_e/v1.11' elif (dataset_name == 'wiki_hop'): return 'wiki_hop/original' elif (dataset_name == 'paws'): return 'paws/labeled_final' elif (dataset_name == 'glue_qqp'): return 'glue/qqp' elif...
def split_rnn_outputs(model, rnn_outputs): if using_skip_rnn(model): return (rnn_outputs.h, rnn_outputs.state_gate) else: return (rnn_outputs, tf.no_op())
class UpBlockTemporalDecoder(nn.Module): def __init__(self, in_channels: int, out_channels: int, num_layers: int=1, add_upsample: bool=True): super().__init__() resnets = [] for i in range(num_layers): input_channels = (in_channels if (i == 0) else out_channels) resne...
def get_log_path(model_save_dir, args): mkdir(model_save_dir) if (args['task_name'] == 'qnli'): output_result_path = (model_save_dir + '/training_logs_reduced_qnli_{0}_{1}'.format(str(args['lr']), str((args['per_device_train_batch_size'] * len(args['device']))))) elif (args['task_name'] == 'cola'): ...
class CameraClient(): def __init__(self, port): self.conn = Client(('localhost', port), authkey=CONN_AUTHKEY) self.conn.send(None) data = self.conn.recv() remove_shm_from_resource_tracker() self.shm = shared_memory.SharedMemory(name=data['name']) self.image = np.ndarr...
def get_block_fun(block_type): block_funs = {'vanilla_block': VanillaBlock, 'res_basic_block': ResBasicBlock, 'res_bottleneck_block': ResBottleneckBlock} assert (block_type in block_funs.keys()), "Block type '{}' not supported".format(block_type) return block_funs[block_type]
class InferenceRunner(Callback): IOTensor = namedtuple('IOTensor', ['index', 'isOutput']) def __init__(self, ds, infs, inf_epochs, input_tensors=None): assert isinstance(ds, DataFlow), ds self.ds = ds if (not isinstance(infs, list)): self.infs = [infs] else: ...
def setup(rank, world_size, port='10231'): os.environ['MASTER_ADDR'] = 'localhost' os.environ['MASTER_PORT'] = port dist.init_process_group('gloo', rank=rank, world_size=world_size)
class ToyGenerator(Generator): def __init__(self) -> None: super().__init__(max_num_items=20, max_num_ems=60, container_dims=TWENTY_FOOT_DIMS) def __call__(self, key: chex.PRNGKey) -> State: solution = self._generate_solved_instance(key) state = self._unpack_items(solution) retur...
def _is_math_expr_safe(expr): only_allowed_chars = _allowedchars.match(expr) if (not only_allowed_chars): return False elif (not (only_allowed_chars.group(0) == expr)): return False sub_expressions = re.findall(_expr_regex, expr) if (not all([_valid_sub_expr.match(sub_exp) for sub_ex...
def compute_feature_stats_for_dataset(opts, detector_url, detector_kwargs, rel_lo=0, rel_hi=1, batch_size=64, data_loader_kwargs=None, max_items=None, swav=False, sfid=False, **stats_kwargs): dataset = dnnlib.util.construct_class_by_name(**opts.dataset_kwargs) if (data_loader_kwargs is None): data_loade...
class PDO(PolicyGradientSafe, Serializable): def __init__(self, optimizer=None, optimizer_args=None, safety_constraint=None, pdo_vf_mode=1, **kwargs): Serializable.quick_init(self, locals()) if (optimizer is None): if (optimizer_args is None): optimizer_args = dict() ...
class Attribute(Param): def __init__(self, xml_var, value_type, required=True, default=None, var=None): Param.__init__(self, xml_var, value_type, required, default, var) self.type = 'attribute' def set_from_string(self, obj, value): setattr(obj, self.var, self.value_type.from_string(valu...
class ModelArguments(): model_name_or_path: str = field(metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}) config_name: Optional[str] = field(default=None, metadata={'help': 'Pretrained config name or path if not the same as model_name'}) tokenizer_name: Optional[s...
def test_render(multicvrp_env: MultiCVRP) -> None: key = jax.random.PRNGKey(0) reset_fn = jax.jit(multicvrp_env.reset) step_fn = jax.jit(multicvrp_env.step) (state, timestep) = reset_fn(key) viewer = MultiCVRPViewer(name='MultiCVRP', num_vehicles=multicvrp_env._num_vehicles, num_customers=multicvrp_...
class SpeechT5Model(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def download_voc2007(root): path_devkit = os.path.join(root, 'VOCdevkit') path_images = os.path.join(root, 'VOCdevkit', 'VOC2007', 'JPEGImages') tmpdir = os.path.join(root, 'tmp') if (not os.path.exists(root)): os.makedirs(root) if (not os.path.exists(path_devkit)): if (not os.path.e...
class AbstractRefTask(RefTask): def __init__(self): super(AbstractRefTask, self).__init__() (scenes, _, _, vocab, freq) = corpus.load_abstract() self.scenes = scenes self.n_features = (scenes[0].features.size * 2) self.vocab = vocab self.freq_vocab = freq self...
class Batch(object): def __init__(self, data=None, device=None, is_test=False): if (data is not None): self.batch_size = len(data) pre_src = [x[0] for x in data] pre_tgt = [x[1] for x in data] pre_segs = [x[2] for x in data] pre_clss = [x[3] for x ...
def register_annotations_file(filename: str, should_compile_handlers_for_already_imported_modules: bool=False) -> Set[str]: with open(filename, 'r') as f: source = f.read() modules = register_annotations_from_source(source, filename) if should_compile_handlers_for_already_imported_modules: c...
class ASPP(nn.Module): def __init__(self, num_classes, head=True): super(ASPP, self).__init__() self.conv_1x1_1 = nn.Conv2d(512, 256, kernel_size=1) self.bn_conv_1x1_1 = nn.BatchNorm2d(256) self.conv_3x3_1 = nn.Conv2d(512, 256, kernel_size=3, stride=1, padding=6, dilation=6) ...
(frozen=True) class ValidationConfig(JsonSerializable): n_cores: int bug_pattern: str def to_json(self) -> Any: return {'n_cores': self.n_cores, 'bug_pattern': self.bug_pattern} def from_json(cls, d: dict) -> 'ValidationConfig': return ValidationConfig(int(d['n_cores']), str(d['bug_patte...
def read_uiuc(auto_src, gold_src): path = os.path.join(auto_src, '*out') call = coreference_reading.read_uiuc_coref return multifile_process(path, call)
class ResNet(nn.Module): def __init__(self, block, num_block, num_classes=100): super().__init__() self.in_channels = 64 self.conv1 = nn.Sequential(nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True)) self.conv2_x = self._make_layer(block...
def test_PointwiseSemanticHead(): if (not torch.cuda.is_available()): pytest.skip('test requires GPU and torch+cuda') from mmdet3d.models.builder import build_head head_cfg = dict(type='PointwiseSemanticHead', in_channels=8, extra_width=0.2, seg_score_thr=0.3, num_classes=3, loss_seg=dict(type='Foca...
def video_record(filename, duration): print('recording video (.AVI)') print(('--> ' + filename)) t0 = time.time() video = cv2.VideoCapture(0) fourcc = cv2.VideoWriter_fourcc(*'XVID') frame_width = int(video.get(3)) frame_height = int(video.get(4)) out = cv2.VideoWriter(filename, cv2.Vide...
def load_airline_table(airline_table): callword_mapping = dict() skip_words = set((list(letters.values()) + list(numbers.values()))) for line in open(airline_table, 'r'): if (line.strip().split('\t')[0] == 'ICAO'): continue if (line.strip() == ''): continue ar...
class Client(ABC): def __init__(self, network_config, max_try=100): self.network_config = network_config self.socket = ClientSocket(network_config.SERVER_ADDR, network_config.SERVER_PORT) self.train_loader = None init_msg = self.socket.init_connections(max_try) self.client_id...