code
stringlengths
101
5.91M
class C51(DQN): def __init__(self, c: int, h: int, w: int, action_shape: Sequence[int], num_atoms: int=51, device: Union[(str, int, torch.device)]='cpu') -> None: self.action_num = np.prod(action_shape) super().__init__(c, h, w, [(self.action_num * num_atoms)], device) self.num_atoms = num_a...
def WithParams(t, p): t = _to_tactic(t, None) return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
def test_compound_open(model=None): if (model is None): model = SimpleModel() state = build_initial_state(model)[0] open_transition = parse_transitions.OpenConstituent('ROOT', 'S') assert open_transition.is_legal(state, model) shift = parse_transitions.Shift() close_transition = parse_tr...
_data_model class BufferBinding(): def __init__(self, j: Dict[(str, Any)]) -> None: binding = j['binding'] buffer = j['buffer'] self.binding: int = int(binding) self.buffer: Buffer = Buffer(buffer)
class AutoModel(): def __init__(self): raise EnvironmentError('AutoModel is designed to be instantiated using the `AutoModel.from_pretrained(pretrained_model_name_or_path)` or `AutoModel.from_config(config)` methods.') _list_option_in_docstrings(MODEL_MAPPING, use_model_types=False) def from_config(...
def register_Ns3EpcX2SapSecondaryHandoverParams_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::EpcX2Sap::SecondaryHandoverParams const &', 'arg0')]) cls.add_instance_attribute('imsi', 'uint64_t', is_const=False) cls.add_instance_attribute('oldCellId', 'uint16_t', is_...
class PointNet2ClsSsg(nn.Module): def __init__(self, num_classes=40): super(PointNet2ClsSsg, self).__init__() self.sa1 = PointNetSetAbstraction(npoint=512, radius=0.2, nsample=32, in_channel=3, mlp=[64, 64, 128], group_all=False) self.sa2 = PointNetSetAbstraction(npoint=128, radius=0.4, nsam...
def build_generic_retinanet_model(model, add_conv_body_func, freeze_conv_body=False): def _single_gpu_build_func(model): (blobs, dim, spatial_scales) = add_conv_body_func(model) if (not model.train): model.conv_body_net = model.net.Clone('conv_body_net') retinanet_heads.add_fpn_r...
def _squared_error(trajectory1: np.ndarray, trajectory2: np.ndarray) -> np.ndarray: (trajectory1, trajectory2) = pad_shorter_trajectory(trajectory1, trajectory2) return np.power((trajectory1 - trajectory2), 2).sum((- 1))
class AMR(object): def __init__(self, node_list=None, node_value_list=None, relation_list=None, attribute_list=None): if (node_list is None): self.nodes = [] self.root = None else: self.nodes = node_list[:] if (len(node_list) != 0): sel...
class OBJReconverter(): def __init__(self): self.vertex_dict = OrderedDict() self.PRECISION = 1e-05 self.eps = 1e-07 self.x_axis = gp_Dir(1.0, 0.0, 0.0) def convert_curve(self, curve): json_curve = {} if (curve.type == 'circle'): json_curve['type'] = '...
def __compare_weight_handler__(compare, weight, weight_type): valid_dict = {'class_weight': compare.classes, 'class_benchmark_weight': CLASS_BENCHMARK_SCORE_DICT.keys(), 'overall_benchmark_weight': OVERALL_BENCHMARK_SCORE_DICT.keys()} error_dict = {'class_weight': COMPARE_CLASS_WEIGHT_ERROR, 'class_benchmark_we...
class SPSA(WrappedOptimizerBase): def __init__(self, options: dict=None, callback=default_callback): super().__init__() self.set_callback(callback) if (options is None): options = {} self.options = options self.maxiter = options.get('maxiter', 100) self.bl...
_args('v', 'i', 'v', 'v', 'v', 'v') def zeros_like(g, input, dtype=None, layout=None, device=None, pin_memory=False, memory_format=None): shape = g.op('Shape', input) if (dtype is None): dtype = 6 return g.op('ConstantOfShape', shape, value_t=torch.tensor([0], dtype=sym_help.scalar_type_to_pytorch_t...
def run_resnet50_epoch(train_model, batch_size, epoch_size, skip_first_n_iter=0): epoch_iters = int((epoch_size / batch_size)) prefix = '{}_{}'.format(train_model._device_prefix, train_model._devices[0]) train_time = 0.0 train_examples = 0 for i in range(epoch_iters): timeout = (600.0 if (i ...
def resolve_cache_dir(env_variable='MMF_CACHE_DIR', default='mmf'): try: from torch.hub import _get_torch_home torch_cache_home = _get_torch_home() except ImportError: torch_cache_home = os.path.expanduser(os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'tor...
def parse_args(): parser = argparse.ArgumentParser(description='Finetune a transformers model on a text classification task (NER) with accelerate library') parser.add_argument('--dataset_name', type=str, default=None, help='The name of the dataset to use (via the datasets library).') parser.add_argument('--...
def get_run_config(params_dict: DictConfig) -> Generator[(DictConfig, None, None)]: params = flatten_sweep_params(params_dict) combinations = list(itertools.product(*convert_to_tuple(params.values()))) keys = params.keys() for combination in combinations: run_config = DictConfig({}) for ...
class Launcher(TmuxLauncher): def options(self): opt = Options() opt.set(dataroot='/mnt/localssd/datasets/afhq/afhq/train', dataset_mode='imagefolder', checkpoints_dir='./checkpoints/', num_gpus=8, batch_size=32, preprocess='resize', load_size=256, crop_size=256) return [opt.specify(name='af...
def register_Ns3OlsrTopologyTuple_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_output_stream_operator() cls.add_constructor([]) cls.add_constructor([param('ns3::olsr::TopologyTuple const &', 'arg0')]) cls.add_instance_attribute('destAddr', 'ns3::Ipv4Address', is_const=...
def format_instructions(instructions: str) -> str: if (len(instructions) > 0): instructions += '\n' return instructions
def collect_log_folders(log_dir): tasks = {} for filename in os.listdir(log_dir): if (filename == 'latest'): continue splited = filename.split('-') if (len(splited) != 5): raise Exception(f'Unexpected log name {filename}.') (task_name, number_of_nodes, obj...
def main(): args = sys.argv[1:] if (len(args) == 1): parse(args[0]) else: usage()
def test_get_time_line_value_no_interpolation(sequence_factory): config.configuration.statistics_output.timeline_interval = 1 config.configuration.statistics_output.timeline_interpolation = False start_time = time.time_ns() sequence_factory.set_start_time(start_time) sequence_factory._time_stamps = ...
class RteProcessor(DataProcessor): def get_train_examples(self, data_dir): return self._create_examples(self._read_tsv(os.path.join(data_dir, 'train.tsv')), 'train') def get_dev_examples(self, data_dir): return self._create_examples(self._read_tsv(os.path.join(data_dir, 'dev.tsv')), 'dev') d...
def get_results(out, err): loss_pattern = '^Final loss. Train: (\\d.\\d+) Dev: (\\d.\\d+) Test: (\\d.\\d+)$' acc_pattern = '^Final acc. Train: (\\d.\\d+) Dev: (\\d.\\d+) Test: (\\d.\\d+)$' output = out.decode().split('\n') try: m = re.match(loss_pattern, output[(- 3)]) (train_loss, dev_l...
def move_drone(drone_dir_x, drone_dir_y, speed): global current_x_drone global current_y_drone if (distance_2d(current_x_drone, current_y_drone, drone_dir_x, drone_dir_y) >= 1): theta = math.atan2((drone_dir_y - current_y_drone), ((drone_dir_x - current_x_drone) + 1e-06)) next_x = (current_x...
def ref_nearest_interpolate_3d(x, output_size, align_corners, half_pixel, half_pixel_for_nn): oshape = output_size ishape = x.shape[(- 3):] xx = x.reshape((- 1), *ishape) ib = np.arange(xx.shape[0]) scale = (compute_scale_for_nn(ishape[0], oshape[0], align_corners, half_pixel_for_nn), compute_scale_...
def RealSort(ctx=None): ctx = _get_ctx(ctx) return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
_criterion('label_smoothed_cross_entropy_with_reg') class LabelSmoothedCrossEntropyCriterionWithReg(LabelSmoothedCrossEntropyCriterion): def __init__(self, args, task): super().__init__(args, task) self.reg_lambda_hidden = args.reg_lambda_hidden self.reg_lambda_div = args.reg_lambda_div ...
class CandidatePreferences(object): def __init__(self, prefer_binary=False, allow_all_prereleases=False): self.allow_all_prereleases = allow_all_prereleases self.prefer_binary = prefer_binary
def _init_logger(path=None, stdout='tqdm', level='INFO'): level = _get_level(level) logger = logging.getLogger(ROOT_NAME) logger.propagate = False logger.setLevel(1) _set_stdout_handler(logger, stdout, level) if (path is not None): _add_file_handler(logger, path, level) return logger
def run_eval(model_type: str, task: str, from_pretrained: str, split: str='test', batch_size: int=1024, model_config_file: typing.Optional[str]=None, data_dir: str='./data', no_cuda: bool=False, seed: int=42, tokenizer: str='iupac', num_workers: int=8, debug: bool=False, metrics: typing.Tuple[(str, ...)]=(), log_level:...
def nnb_template_command(args): if (len(args.files) >= 2): output = args.files.pop() resolve_file_format(args, args.files) if (args.import_format not in nnabla.utils.converter.formats.import_name): print('Import format ({}) is not supported.'.format(args.import_format)) ...
def test_model(model: nn.Module, test_set: data.DataLoader, number_of_classes: int) -> (score.FloatScore, score.DictScore): model.eval() def test_average() -> score.FloatScore: correct = 0 total = 0 with torch.set_grad_enabled(False): for (inputs, yreal) in tqdm(test_set, uni...
def test_optimal(): envs = [StrictTMazeEnv(init_reward_side=i, n_trials=100) for i in [1, 0, 1, 0]] evaluator = MultiEnvEvaluator(make_net, activate_net, envs=envs, batch_size=4, max_env_steps=1600) fitness = evaluator.eval_genome(None, None) assert (fitness == 98.8)
def per_class_iu(hist): return (np.diag(hist) / (((hist.sum(1) + 1e-08) + hist.sum(0)) - np.diag(hist)))
class ChemProtProcessor(BlueBERTProcessor): def get_labels(self): return ['CPR:3', 'CPR:4', 'CPR:5', 'CPR:6', 'CPR:9', 'false']
class ProbablisticCAE(nn.Module): in_num = 1 out_num = 1 def __init__(self, in_ch_size=3, out_ch_size=3, row_size=1, col_size=20, level_back=5, downsample=True, k_sizes=(1, 3, 5), ch_range=(64, 256), c=None, delta_init_factor=0.0): super(ProbablisticCAE, self).__init__() self.in_ch_size = in...
def sample_code_chunk(code, size): assert ((size > 0) and (size <= len(code))) start = np.random.randint(((len(code) - size) + 1)) end = (start + size) return (code[start:end], start, end)
.parametrize('ctx, func_name', ctxs) .parametrize('seed', [313]) .parametrize('ishape, index', [([10], [[0]]), ([10], [[1, 5, 8]]), ([10], [[(- 1), (- 5), (- 8)]]), ([3, 4], [[0]]), ([3, 4], [[0], [0]]), ([3, 4], [[0, 1], [0, 2]]), ([3, 4], [[0, (- 1)], [0, (- 2)]]), ([2, 3, 4], [[0]]), ([2, 3, 4], [[0], [1]]), ([2, 3,...
def save_training_checkpoint(epoch, model, optimizer, best_f1, filename): state = {'epoch': (epoch + 1), 'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict(), 'best_f1': best_f1} torch.save(state, filename)
def extract_sp_S1_models(layout): wandb_dir = RESULT_PATH.format(layout=layout) runs = glob.glob(f'{wandb_dir}/run*') run_ids = [x.split('-')[(- 1)] for x in runs] print(runs) print(run_ids) api = wandb.Api() i = 0 for run_id in run_ids: run = api.run(f'{WANDB_NAME}/Overcooked/{r...
def load_combined_test_data_wov(output_path: str): id_p_te = load_data_tensors_TW(join(output_path, 'vectors', 'test', 'identifiers_param_test_datapoints_x.npy')) id_r_te = load_data_tensors_TW(join(output_path, 'vectors', 'test', 'identifiers_ret_test_datapoints_x.npy')) id_v_te = load_data_tensors_TW(join...
def add_fast_rcnn_losses(model): (cls_prob, loss_cls) = model.net.SoftmaxWithLoss((['cls_score', 'labels_int32'] + (['label_loss_weights'] if cfg.TRAIN.CLS_SIZE_WEIGHTED_LOSS else [])), ['cls_prob', 'loss_cls'], scale=(1.0 / cfg.NUM_GPUS)) loss_bbox = model.net.SmoothL1Loss(['bbox_pred', 'bbox_targets', 'bbox_i...
def options(opt): assert (default_profile in profiles) opt.add_option('-d', '--build-profile', action='store', default=default_profile, help=('Specify the build profile. Build profiles control the default compilation flags used for C/C++ programs, if CCFLAGS/CXXFLAGS are not set in the environment. [Allowed Va...
_python_op() def resize_fn(config, frame: sp.FrameType) -> sp.FrameType: return cv2.resize(frame, (config.args['width'], config.args['height']))
def ShearY(img, v): assert ((- 0.3) <= v <= 0.3) if (random_mirror and (random.random() > 0.5)): v = (- v) return img.transform(img.size, PIL.Image.AFFINE, (1, 0, 0, v, 1, 0))
class STFTLoss(torch.nn.Module): def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann_window'): super(STFTLoss, self).__init__() self.fft_size = fft_size self.shift_size = shift_size self.win_length = win_length self.register_buffer('window', getattr...
def extract_masks(segmentations, target_vectors): device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu')) (batch_size, num_classes, h, w) = segmentations.size() target_masks = torch.empty(batch_size, h, w, device=device) non_target_masks = torch.empty(batch_size, h, w, device=device) ...
class ScipyNelderMeadTuner(Tuner): def tune_impl(self, **kwargs): if ('init_method' in kwargs): init_method = kwargs['init_method'] else: init_method = 'average' if (self.start_config is not None): config = self.start_config elif (init_method is 'a...
class Mask(nn.Module): def __init__(self, dict_size=12099): super(Mask, self).__init__() self.name = 'Baseline' self.encoder = Encoder() self.embs = nn.ModuleList([nn.Embedding(dict_size, 1000)]) self.cas = nn.ModuleList([CrossAtt(vis_dim=2048, lang_dim=1000)]) self.d...
def clean_up() -> None: base = Path('.') [p.unlink() for p in base.glob('run.log')] [p.unlink() for p in base.glob('*.npy')]
def test(tmp_path): filename = os.path.join(tmp_path, 'whatever.parquet') original = ak.Record({'x': 1, 'y': [1, 2, 3], 'z': 'THREE'}) assert (ak.from_arrow(ak.to_arrow(original)).to_list() == original.to_list()) assert (ak.from_arrow(ak.to_arrow_table(original)).to_list() == original.to_list()) ak....
class CommandContextMixIn(object): def __init__(self): super(CommandContextMixIn, self).__init__() self._in_main_context = False self._main_context = ExitStack() def main_context(self): assert (not self._in_main_context) self._in_main_context = True try: ...
def from_major_code(mc, final_descent=False): if (not mc): w = [] else: w = [len(mc)] for i in reversed(range(1, len(mc))): d = Permutation(w, check=False).descents(final_descent=final_descent) d.reverse() a = [x for x in range(1, (len(w) + 1)) if (x not in d)] ...
class AutoModelForTableQuestionAnswering(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class TensorPipeAgentRpcTest(RpcAgentTestFixture): def test_mismatched_type_for_options(self): rpc_backend_options = FooBackendOptions(self.init_method) with self.assertRaisesRegex(TypeError, '`rpc_backend_options` must be a `TensorPipeRpcBackendOptions`'): rpc.init_rpc(name=worker_name(...
class ResidualCNN(nn.Module): def __init__(self, in_channels, out_channels, kernel, stride, dropout, n_feats): super(ResidualCNN, self).__init__() self.cnn1 = nn.Conv2d(in_channels, out_channels, kernel, stride, padding=(kernel // 2)) self.cnn2 = nn.Conv2d(out_channels, out_channels, kernel,...
class DotprodAttention(nn.Module): def __init__(self): super().__init__() def forward(self, feature, aspect_v, dmask): Q = aspect_v Q = Q.unsqueeze(2) dot_prod = torch.bmm(feature, Q) dmask = dmask.unsqueeze(2) attention_weight = mask_logits(dot_prod, dmask) ...
def mvRotate(speed, angle, clockwise, verbose=0): print(stopper) if (stopper == False): return vel_msg = Twist() rospy.loginfo('Rotate {0} degree with {1} degree/sec Clockwise = {2}'.format(speed, angle, clockwise)) angular_speed = (((speed * 2) * PI) / 360) relative_angle = (((angle * 2...
class GaussianMLPBaseModule(nn.Module): def __init__(self, input_dim, output_dim, hidden_sizes=(32, 32), hidden_nonlinearity=torch.tanh, hidden_w_init=nn.init.xavier_uniform_, hidden_b_init=nn.init.zeros_, output_nonlinearity=None, output_w_init=nn.init.xavier_uniform_, output_b_init=nn.init.zeros_, learn_std=True,...
def create_X_y(): X = np.array([[(- 1), 1], [(- 0.75), 0.5], [(- 1.5), 1.5], [1, 1], [0.75, 0.5], [1.5, 1.5], [1, (- 1)], [(- 0.5), 0.5], [0.5, 0.5], [0, (- 1)], [0.75, (- 0.5)], [0.0, 0.0], [(- 1), (- 1)], [0, (- 0.5)], [1, (- 1)]]) y = np.array([0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0]) return (X, y)
class AlexnetCifar10Model(model.Model): def __init__(self): super(AlexnetCifar10Model, self).__init__('alexnet', 32, 128, 0.1) def add_inference(self, cnn): cnn.conv(64, 5, 5, 1, 1, 'SAME', stddev=0.05) cnn.mpool(3, 3, 2, 2, mode='SAME') cnn.lrn(depth_radius=4, bias=1.0, alpha=(0...
class EllipticCurveHom_sum(EllipticCurveHom): _degree = None _phis = None def __init__(self, phis, domain=None, codomain=None): phis = tuple(phis) if ((not phis) and ((domain is None) or (codomain is None))): raise ValueError('need either phis or both domain and codomain') ...
class PredictionToGroundTruthSampler(): def __init__(self, dataset_name: str=''): self.dataset_name = dataset_name self._samplers = {} self.register_sampler('pred_boxes', 'gt_boxes', None) self.register_sampler('pred_classes', 'gt_classes', None) self.register_sampler('scores...
class DiverseBeamDecoder(BeamDecoder): name = 'diverse_beam' def __init__(self, decoder_args): super(DiverseBeamDecoder, self).__init__(decoder_args) assert (not self.gumbel) self.beam_size = decoder_args.beam self.num_groups = decoder_args.diversity_groups self.lmbda = d...
def count_entity_freq(data_path): entity_freq = collections.defaultdict(dict) label_map = collections.defaultdict(dict) with open(data_path, 'r') as f: lines = f.readlines() for line in lines: if ((len(line) < 2) or ('-DOCSTART-' in line)): continue line = line.strip(...
def convert_ts_unix(fname: str, outname: str): TIME_FORMAT = '%Y-%m-%d' with open(outname, 'w') as outf: write = csv.writer(outf) fields = ['ts', 'user_id', 'genre', 'weight'] write.writerow(fields) with open(fname, 'r') as csv_file: csv_reader = csv.reader(csv_file, ...
def _compute_variables(df: EDAFrame, cfg: Config) -> Dict[(str, Any)]: data: Dict[(str, Any)] = {} if cfg.variables.enable: for col in df.columns: try: dtype = df.get_eda_dtype(col) if (df.get_missing_cnt(col) == df.shape[0]): srs = df.get_...
_optimizer('radam') class FairseqRAdam(FairseqOptimizer): def __init__(self, args, params): super().__init__(args, params) self._optimizer = RAdam(params, **self.optimizer_config) self._optimizer.name = ((args.tb_tag + '_') + self._optimizer.name) def add_args(parser): parser.add...
.parametrize('statement_type,value', [(stmt.IntPrimitiveStatement, 42), (stmt.FloatPrimitiveStatement, 42.23), (stmt.StringPrimitiveStatement, 'foo'), (stmt.BytesPrimitiveStatement, b'test'), (stmt.BooleanPrimitiveStatement, True), (stmt.ComplexPrimitiveStatement, (4 + 3j))]) def test_primitive_statement_value(statemen...
class FlaxBigBirdForNaturalQuestions(FlaxBigBirdForQuestionAnswering): module_class = FlaxBigBirdForNaturalQuestionsModule
def apply_fixes(args, tmpdir): invocation = [args.clang_apply_replacements_binary] if args.format: invocation.append('-format') if args.style: invocation.append(('-style=' + args.style)) invocation.append(tmpdir) subprocess.call(invocation)
class IndexedRawTextDataset(FairseqDataset): def __init__(self, path, dictionary, append_eos=True, reverse_order=False): self.tokens_list = [] self.lines = [] self.sizes = [] self.append_eos = append_eos self.reverse_order = reverse_order self.read_data(path, dictiona...
def nes_op_ray_tracing(x_0, num_points, nes_op, target_front=0.01, solver='specified steps', direction='backward', velocity='interpolation', **kwargs): assert (solver in solvers_list), ("Two solvers are supported: 'specified steps' and 'scipy'. " + 'Instead {} is passed.'.format(solver)) assert (direction in di...
class TFDistilBertForTokenClassification(): def __init__(self, *args, **kwargs): requires_tf(self) def from_pretrained(self, *args, **kwargs): requires_tf(self)
def showLight(): os.chdir('./medirl-master/Code/') VideoDir = './medirl-master/videos/crash-video' videos = glob.glob((VideoDir + '/*.mp4')) for v in videos: cap = cv2.VideoCapture(v) while cap.isOpened(): (ret, frame) = cap.read() blur_frame = cv2.medianBlur(fram...
class LSTM(nn.Module): def __init__(self, c_mid, base_ch=256, num_layers=2, bidirectional=True): super(LSTM, self).__init__() self.rnn = nn.LSTM(c_mid, hidden_size=base_ch, num_layers=num_layers, bidirectional=bidirectional) self.out_channels = (base_ch * (1 + int(bidirectional))) def fo...
def prepare_annos(dir_to_video): vids = os.listdir(dir_to_video) video_files = glob.glob(os.path.join(dir_to_video, '*')) vid2annos = {vid[:(- 4)]: {} for vid in vids} for video_file in video_files: vid = video_file.split('/')[(- 1)][:(- 4)] (vid2annos[vid]['duration'], vid2annos[vid]['n...
def open(domain_filename=None, task_filename=None): task_filename = (task_filename or options.task) domain_filename = (domain_filename or options.domain) domain_pddl = parse_pddl_file('domain', domain_filename) task_pddl = parse_pddl_file('task', task_filename) return parsing_functions.parse_task(do...
def main(): parser = get_arg_parser() opt = parser.parse_args() opt.enable_lidar = True kitti360_sequence_ids = ['1538', '1728', '1908', '3353'] nerf_mvl_sequence_ids = ['bollard', 'car', 'pedestrian', 'pier', 'plant', 'tire', 'traffic_cone', 'warning_sign', 'water_safety_barrier'] if (opt.datal...
_grad() def convert_hifigan_checkpoint(checkpoint_path, stats_path, pytorch_dump_folder_path, config_path=None, repo_id=None): if (config_path is not None): config = SpeechT5HifiGanConfig.from_pretrained(config_path) else: config = SpeechT5HifiGanConfig() model = SpeechT5HifiGan(config) ...
def postprocess_image(image, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]): image = UnNormalize(mean, std)(image) return (image * 255).squeeze(0).transpose(1, 2, 0).numpy().astype(np.uint8)
def _test_reshape_output_and_gradient(old_shape, new_shape, expected_shape=None, arg_shape=True, in_place=False, expected_gradient=None): devices = [core.DeviceOption(caffe2_pb2.CPU, 0)] if (workspace.NumGpuDevices() > 0): devices.append(core.DeviceOption(workspace.GpuDeviceType, 0)) for device_opt ...
def grail_enum_one_hop_one_entity_candidates(entity: str, use_master=True): if (CacheBackend.cache is not None): (in_relations_e, out_relations_e) = CacheBackend.cache.query_relations(entity) else: (in_relations_e, out_relations_e) = get_adjacent_relations(entity) (in_relations_e, out_relati...
class AADGenerator(nn.Module): def __init__(self, c_id=256): super(AADGenerator, self).__init__() self.up1 = nn.ConvTranspose2d(c_id, 1024, kernel_size=2, stride=1, padding=0) self.AADBlk1 = AAD_ResBlk(1024, 1024, 1024, c_id) self.AADBlk2 = AAD_ResBlk(1024, 1024, 2048, c_id) ...
class SortingHelpFormatter(HelpFormatter): def add_arguments(self, actions): actions = sorted(actions, key=attrgetter('option_strings')) super(SortingHelpFormatter, self).add_arguments(actions)
def register_Ns3QosTxop_methods(root_module, cls): cls.add_instance_attribute('m_aMpduEnabled', 'std::map< ns3::Mac48Address, bool >', is_const=False) cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) cls.add_constructor([]) cls.add_method('IsQosTxop', 'bool', [], is_const=True, is_virtual=...
class ResnetMemongerTest(hu.HypothesisTestCase): (with_shapes=st.booleans(), **hu.gcs_cpu_only) (max_examples=2, deadline=None) def test_resnet_shared_grads(self, with_shapes, gc, dc): results = utils.test_shared_grads(with_shapes, resnet.create_resnet50, 'gpu_0/conv1_w', 'gpu_0/last_out_L1000') ...
def tf_efficientnet_b4(pretrained=False, **kwargs): kwargs['bn_eps'] = BN_EPS_TF_DEFAULT kwargs['pad_type'] = 'same' model = _gen_efficientnet('tf_efficientnet_b4', channel_multiplier=1.4, depth_multiplier=1.8, pretrained=pretrained, **kwargs) return model
class Window(): def __init__(self, title='PIL', width=None, height=None): self.hwnd = Image.core.createwindow(title, self.__dispatcher, (width or 0), (height or 0)) def __dispatcher(self, action, *args): return getattr(self, ('ui_handle_' + action))(*args) def ui_handle_clear(self, dc, x0, y...
def add_optimization_args(parser): group = parser.add_argument_group('optimization') gen_parser_from_dataclass(group, OptimizationConfig()) return group
def barrier(group=group.WORLD): assert (torch.distributed._initialized == _INITIALIZED_PG), 'collective only supported in process-group mode' return torch._C._dist_barrier(group)
def srwl_opt_setup_mask(_delta, _atten_len, _thick, _hx, _hy, _pitch_x, _pitch_y, _mask_Nx, _mask_Ny, _grid_nx, _grid_ny, _grid_sh, _grid_dx, _grid_dy=0, _grid_angle=0, _mask_x0=0, _mask_y0=0): input_parms = {'type': 'mask', 'refractiveIndex': _delta, 'attenuationLength': _atten_len, 'maskThickness': _thick, 'gridS...
def map_to_limited_gpus(func, configs, NUM_AVAIALBLE_GPUS, CUDA_VISIBLE_DEVICES=None): with Manager() as manager: q = manager.Queue() if CUDA_VISIBLE_DEVICES: for i in CUDA_VISIBLE_DEVICES: q.put(i) else: for i in range(NUM_AVAIALBLE_GPUS): ...
def pre_build_hook(build_ext, ext): from scipy._build_utils.compiler_helper import get_cxx_std_flag, try_add_flag, try_compile, has_flag cc = build_ext._cxx_compiler args = ext.extra_compile_args std_flag = get_cxx_std_flag(build_ext._cxx_compiler) if (std_flag is not None): args.append(std_...
def register_Ns3HtCapabilities_methods(root_module, cls): cls.add_output_stream_operator() cls.add_constructor([param('ns3::HtCapabilities const &', 'arg0')]) cls.add_constructor([]) cls.add_method('DeserializeInformationField', 'uint8_t', [param('ns3::Buffer::Iterator', 'start'), param('uint8_t', 'leng...
class CNN_Encoder(nn.Module): def __init__(self, ch, num_pitch, latent_dim): super(CNN_Encoder, self).__init__() self.first_layer = CNNBlock(num_pitch, ch, kernel_size=3, padding=1) self.cnn_layer = nn.ModuleList([CNNBlock(ch, ch, kernel_size=3, stride=2, padding=1) for i in range(2)]) ...
class VirtualSplitWeightsNode(VirtualSplitNode): def __init__(self, origin_node: BaseNode): super().__init__(origin_node) self.name = (origin_node.name + VIRTUAL_WEIGHTS_SUFFIX) self.candidates_quantization_cfg = origin_node.get_unique_weights_candidates() for c in self.candidates_qu...