code
stringlengths
101
5.91M
def oe_to_igraph(inputs, output, size_dict, weight_nodes='const', weight_edges='log'): import igraph as ig G = ig.Graph() ind2terms = defaultdict(list) for (i, term) in enumerate(inputs): nweight = calc_node_weight_float(term, size_dict, weight_nodes) G.add_vertex(str(i), weight=nweight)...
class Total_Phonation_Time(object): def __init__(self, sentence_objs, **kwArgs): self.sentence_objs = sentence_objs def handle(self): tot_speech_time = 0 for so in self.sentence_objs: tot_speech_time += so.speech_time return tot_speech_time
def get_target_updates(vars, target_vars, tau): logger.info('setting up target updates ...') soft_updates = [] init_updates = [] assert (len(vars) == len(target_vars)) for (var, target_var) in zip(vars, target_vars): logger.info(' {} <- {}'.format(target_var.name, var.name)) init_up...
def CreateDataset(opt): dataset = None from data.aligned_dataset_test import AlignedDataset dataset = AlignedDataset() print(('dataset [%s] was created' % dataset.name())) dataset.initialize(opt) return dataset
class CamembertModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class TestGetRNNCell(tf.test.TestCase): def test_single_layer(self): cell = training_utils.get_rnn_cell(cell_class='BasicLSTMCell', cell_params={'num_units': 16}, num_layers=1) self.assertIsInstance(cell, tf.contrib.rnn.BasicLSTMCell) self.assertEqual(cell.output_size, 16) def test_multi...
def train_model(args): CEMBED_SIZE = args.CEMBED_SIZE WEMBED_SIZE = args.WEMBED_SIZE HIDDEN_SIZE = args.HIDDEN_SIZE MLP_SIZE = args.MLP_SIZE SPARSE = args.SPARSE TIMEOUT = args.TIMEOUT num_train_files = 0 best_dev = 0.0 best_test = 0.0 batch_trains = [] if args.train: ...
class TensorCollector(CollectorBase): def __init__(self, include_nodes, qtensor_to_tensor, tensor_to_node): self.tensors_dicts = [] self.include_nodes = include_nodes self.qtensor_to_tensor = qtensor_to_tensor self.tensor_to_node = tensor_to_node rest = (set(self.include_node...
class AtariEnv(gym.Env, utils.EzPickle): metadata = {'render.modes': ['human', 'rgb_array']} def __init__(self, game='pong', obs_type='ram', frameskip=(2, 5), repeat_action_probability=0.0): utils.EzPickle.__init__(self, game, obs_type) assert (obs_type in ('ram', 'image')) self.game_pat...
_model def regnetx_002(pretrained=False, **kwargs): return _regnet('regnetx_002', pretrained, **kwargs)
def merge_valid_test_messup(mess_up_train_valid, mess_up_train_test): merged_mess = [] for s in set((list(mess_up_train_valid.keys()) + list(mess_up_train_test.keys()))): if (not s): continue valid = mess_up_train_valid.get(s, set()) test = mess_up_train_test.get(s, set()) ...
class InputDataFields(object): image = 'image' original_image = 'original_image' key = 'key' source_id = 'source_id' filename = 'filename' groundtruth_image_classes = 'groundtruth_image_classes' groundtruth_boxes = 'groundtruth_boxes' groundtruth_classes = 'groundtruth_classes' groun...
def is_dogmatic(a): if isinstance(a, (DogmaticDict, DogmaticList)): return True elif isinstance(a, dict): return any((is_dogmatic(v) for v in a.values())) elif isinstance(a, (list, tuple)): return any((is_dogmatic(v) for v in a))
class ScenarioTask(ABSTask): def __init__(self, obstacles_manager: ObstaclesManager, robot_manager: RobotManager, scenario_path: str): super().__init__(obstacles_manager, robot_manager) self.scenario = ArenaScenario() self.scenario.loadFromFile(scenario_path) self.pedsim_manager = No...
def build_decoder(opt, encoder_word_emb_weight, device, rl_model=None): if opt.dec_feature: n_all_feat = len(opt.feat_vocab) feat_vocab = opt.feat_vocab[(n_all_feat - opt.dec_feature):] else: feat_vocab = None d_enc_model = (opt.d_enc_model if (not opt.pretrained) else 768) n_enc...
def filter_tuples(tuples, max_len, min_len): filtered_tuples = [] for item in tuples: if ((len(item[0]) >= min_len) and (len(item[0]) <= max_len) and (len(item[5]) >= min_len) and (len(item[5]) <= max_len)): filtered_tuples.append(item) return filtered_tuples
def _set_plot_properties(properties): if ('xlim' in properties): plt.xlim(properties['xlim']) if ('ylim' in properties): plt.ylim(properties['ylim']) if ('xlabel' in properties): plt.xlabel(properties['xlabel']) if ('ylabel' in properties): plt.ylabel(properties['ylabel']...
def train(train_data, test_data=None): G = train_data[0] features = train_data[1] id_map = train_data[2] class_map = train_data[4] if isinstance(list(class_map.values())[0], list): num_classes = len(list(class_map.values())[0]) else: num_classes = len(set(class_map.values())) ...
class History(): def __init__(self, state, next_state, action, reward): self.state = state self.action = action self.reward = reward self.next_state = next_state
def make_env(env_name: str, seed: int, save_folder: Optional[str]=None, add_episode_monitor: bool=True, action_repeat: int=1, frame_stack: int=1, from_pixels: bool=False, pixels_only: bool=True, image_size: int=84, sticky: bool=False, gray_scale: bool=False, flatten: bool=True) -> gym.Env: all_envs = gym.envs.regis...
('torch.distributed._broadcast_coalesced', mock) ('torch.distributed.broadcast', mock) ('torch.nn.parallel.DistributedDataParallel._ddp_init_helper', mock) def test_is_module_wrapper(): class Model(nn.Module): def __init__(self): super().__init__() self.conv = nn.Conv2d(2, 2, 1) ...
class FlaxMT5EncoderModel(metaclass=DummyObject): _backends = ['flax'] def __init__(self, *args, **kwargs): requires_backends(self, ['flax'])
class MT5Config(PretrainedConfig): model_type = 'mt5' keys_to_ignore_at_inference = ['past_key_values'] def __init__(self, vocab_size=250112, d_model=512, d_kv=64, d_ff=1024, num_layers=8, num_decoder_layers=None, num_heads=6, relative_attention_num_buckets=32, relative_attention_max_distance=128, dropout_r...
class Discriminator(BaseNetwork): def __init__(self, in_channels, use_sigmoid=True, use_spectral_norm=True, init_weights=True): super(Discriminator, self).__init__() self.use_sigmoid = use_sigmoid self.conv1 = self.features = nn.Sequential(spectral_norm(nn.Conv2d(in_channels=in_channels, out...
class SmallNN(nn.Module, metaclass=Named): def __init__(self, dim_in=768, num_classes=4, k=512): super().__init__() self.num_classes = num_classes self.net = nn.Sequential(nn.Linear(dim_in, k), nn.ReLU(), nn.Dropout(0.5), nn.Linear(k, k), nn.ReLU(), nn.Dropout(0.5), nn.Linear(k, num_classes)...
def so3_rotation(x, alpha, beta, gamma): b = (x.size()[(- 1)] // 2) x_size = x.size() Us = _setup_so3_rotation(b, alpha, beta, gamma, device_type=x.device.type, device_index=x.device.index) x = SO3_fft_real.apply(x) Fz_list = [] begin = 0 for l in range(b): L = ((2 * l) + 1) ...
class FastRCNNPredictor(nn.Module): def __init__(self, in_channels, num_classes): super(FastRCNNPredictor, self).__init__() self.cls_score = nn.Linear(in_channels, num_classes) self.bbox_pred = nn.Linear(in_channels, (num_classes * 4)) def forward(self, x): if (x.dim() == 4): ...
def process_data_single(args, f, eos_token_ids): print('running') BOS_TOKEN = 0 with open(os.path.join(args.cur_dir, f), 'rb') as fd: data = pickle.load(fd) (attentions, pred_distb, logits, input_doc) = (data['attentions'], data['pred_distributions'], data['logits'], data['input_doc']) times...
def Perlin(nrow, specs={}): size = specs.get('size', 5) base = specs.get('base', 0) assert (size > 0) x = y = np.linspace(0, size, nrow) n = [[noise.pnoise2(i, j, repeatx=size, repeaty=size, base=base) for j in y] for i in x] m = (n - np.min(n)) landscape = np.array(np.round((m * 7)), dtype=...
def check_tree(json_file_path, gt_info, pred_info): if (len(gt_info) != len(pred_info)): logging.error('ERROR while processing {}, ERR_CODE={}, message:{}'.format(json_file_path, 2, 'number of nodes not equal')) return 2 parent_ids = {} for i in range(len(pred_info)): parent_ids[i] =...
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('experiment', help='name of the experiment that is being run') parser.add_argument('dataset', help='.h5 File containing the train/valid/test datasets') parser.add_argument('--results_dir', default='/shared/results', help='Directory...
def require_torch_bf16_gpu(test_case): return unittest.skipUnless(is_torch_bf16_gpu_available(), 'test requires torch>=1.10, using Ampere GPU or newer arch with cuda>=11.0')(test_case)
def conv2d(inputs, num_output_channels, kernel_size, scope, stride=[1, 1], padding='SAME', data_format='NHWC', use_xavier=True, stddev=0.001, weight_decay=None, activation_fn=tf.nn.relu, bn=False, bn_decay=None, is_training=None): with tf.variable_scope(scope) as sc: (kernel_h, kernel_w) = kernel_size ...
def analyze(airline_table, text_file, callword_mapping=dict()): skip_words = set((list(letters.values()) + list(numbers.values()))) text_file_lines = [] with open(text_file) as f: for line in f: text_file_lines.append(((' ' + line) + ' ')) for callword in tqdm(load_callwords(airline_...
def test_hourglass_backbone(): with pytest.raises(AssertionError): HourglassNet(num_stacks=0) with pytest.raises(AssertionError): HourglassNet(stage_channels=[256, 256, 384, 384, 384], stage_blocks=[2, 2, 2, 2, 2, 4]) with pytest.raises(AssertionError): HourglassNet(downsample_times=...
def generate_xml(name, lines, img_size, class_sets, doncateothers=True): doc = Document() def append_xml_node_attr(child, parent=None, text=None): ele = doc.createElement(child) if (not (text is None)): text_node = doc.createTextNode(text) ele.appendChild(text_node) ...
def record_request(request_url: str, request_body: Dict, user_id: str): mysqldb = MysqlDb() mysqldb._set_db('requests') SHA_TZ = timezone(timedelta(hours=8), name='Asia/Shanghai') utc_now = datetime.datetime.utcnow().replace(tzinfo=timezone.utc) beijing_time = utc_now.astimezone(SHA_TZ).strftime('%Y...
def build_categorical_crossentropy(weights=None): def categorical_crossentropy(y_true, y_pred): y_pred /= K.sum(y_pred, axis=(- 1), keepdims=True) y_pred = K.clip(y_pred, K.epsilon(), (1.0 - K.epsilon())) loss = (y_true * K.log(y_pred)) if (weights is not None): loss = (l...
class CategoricalGRUPolicy(StochasticPolicy): def __init__(self, env_spec, name='CategoricalGRUPolicy', hidden_dim=32, hidden_nonlinearity=tf.nn.tanh, hidden_w_init=tf.initializers.glorot_uniform(seed=deterministic.get_tf_seed_stream()), hidden_b_init=tf.zeros_initializer(), recurrent_nonlinearity=tf.nn.sigmoid, re...
def optimizer(optim, eta, loss_fn, at_step, decay_rate): global_step = tf.Variable(0, trainable=False) optz = optim if (optim == 'Adadelta'): optz = (lambda lr: tf.train.AdadeltaOptimizer(lr, 0.95, 1e-06)) lr_decay_fn = None elif (optim == 'Momentum'): optz = (lambda lr: tf.train...
class mobilenetv1(Network): def __init__(self): Network.__init__(self) self._feat_stride = [16] self._feat_compress = [(1.0 / float(self._feat_stride[0]))] self._depth_multiplier = cfg.MOBILENET.DEPTH_MULTIPLIER self._net_conv_channels = 512 self._fc7_channels = 1024 ...
class XMLCNN_encoder(nn.Module): def __init__(self, dropout, labels_num, dynamic_pool_length, bottleneck_dim, num_filters, vocab_size=None, emb_size=None, emb_trainable=True, emb_init=None, padding_idx=0, **kwargs): super(XMLCNN_encoder, self).__init__() if (emb_init is not None): if (vo...
class DogsDataModule(pl.LightningDataModule): def __init__(self, args): super().__init__() self.data_root = args.data_root self.batch_size = args.batch_size self.num_workers = args.num_workers self.train_dataset = DogsDataset(args.data_root, args.resolution, 'train', use_flip...
class _DeepIndepMixtureNormal(DeepConditional): def __init__(self, backbone: nn.Module, mean_head: nn.ModuleList, logstd_head: nn.Module, component_head: nn.Module): super().__init__() self.backbone = backbone self.mean_head = mean_head self.logstd_head = logstd_head self.com...
def train_svm(): output_dir = os.path.join(FLAGS.output_dir, FLAGS.category) log_dir = os.path.join(output_dir, 'log') if tf.gfile.Exists(log_dir): tf.gfile.DeleteRecursively(log_dir) tf.gfile.MakeDirs(log_dir) (train_data, train_labels) = data_io.getAll(FLAGS.data_path, cube_len=FLAGS.cube_...
def _get_ngrams_with_counter(segment: Sequence[str], max_order: List[int]) -> collections.Counter: ngram_counts = collections.Counter() for order in xrange(1, (max_order + 1)): for i in xrange(0, ((len(segment) - order) + 1)): ngram = tuple(segment[i:(i + order)]) ngram_counts[ng...
def main(): args = parser.parse_args() if args.log_path: set_logger(args.log_path) save_folder = args.pruning_ratio_to_acc_record_file.rsplit('/', 1)[0] with open(args.baseline_acc_file, 'r') as jsonfile: json_data = json.load(jsonfile) criterion_acc = float(json_data[args.datase...
def test_test_quasiisothermaldf_setup_profileAsQuantity(): from galpy.actionAngle import actionAngleAdiabatic from galpy.df import quasiisothermaldf from galpy.orbit import Orbit from galpy.potential import MWPotential aA = actionAngleAdiabatic(pot=MWPotential, c=True) (ro, vo) = (7.0, 250.0) ...
class TestCasePlus(unittest.TestCase): def setUp(self): self.teardown_tmp_dirs = [] def get_auto_remove_tmp_dir(self, tmp_dir=None, after=True, before=False): if (tmp_dir is not None): path = Path(tmp_dir).resolve() if (not tmp_dir.startswith('./')): raise...
def hanoi(height, start=1, end=3): steps = [] if (height > 0): helper = (({1, 2, 3} - {start}) - {end}).pop() steps.extend(hanoi((height - 1), start, helper)) steps.append((start, end)) steps.extend(hanoi((height - 1), helper, end)) return steps
def instances2dict(imageFileList, verbose=False): imgCount = 0 instanceDict = {} if (not isinstance(imageFileList, list)): imageFileList = [imageFileList] if verbose: print('Processing {} images...'.format(len(imageFileList))) for imageFileName in imageFileList: img = Image.o...
def UpdateIncludeState(filename, include_state, io=codecs): headerfile = None try: headerfile = io.open(filename, 'r', 'utf8', 'replace') except IOError: return False linenum = 0 for line in headerfile: linenum += 1 clean_line = CleanseComments(line) match = _...
def test_is_tree_with_leaves_of_type(jax_tree: Dict, np_tree: Dict, jax_and_numpy_tree: Dict) -> None: assert pytree_test_utils.is_tree_with_leaves_of_type(jax_tree, jnp.ndarray) assert pytree_test_utils.is_tree_with_leaves_of_type(np_tree, np.ndarray) assert (not pytree_test_utils.is_tree_with_leaves_of_ty...
def get_color_distortion(s=1.0): color_jitter = transforms.ColorJitter((0.8 * s), (0.8 * s), (0.8 * s), (0.2 * s)) rnd_color_jitter = transforms.RandomApply([color_jitter], p=0.8) rnd_gray = transforms.RandomGrayscale(p=0.2) color_distort = transforms.Compose([rnd_color_jitter, rnd_gray]) return col...
def rotateX(angle): phi = ((angle * math.pi) / 180) return np.array([[1, 0, 0], [0, math.cos(phi), (- math.sin(phi))], [0, math.sin(phi), math.cos(phi)]])
def save_labels(dataset_list, output_dir): if is_main_process(): logger = logging.getLogger(__name__) ids_to_labels = {} for dataset in dataset_list: if hasattr(dataset, 'categories'): ids_to_labels.update(dataset.categories) else: logg...
def to_x1y1x2y2(obj): x1 = obj['x'] y1 = obj['y'] x2 = (obj['x'] + obj['w']) y2 = (obj['y'] + obj['h']) return [x1, y1, x2, y2]
def evaluate_sessions(pr, metrics, test_data, train_data, items=None, cut_off=20, session_key='SessionId', item_key='ItemId', time_key='Time'): actions = len(test_data) sessions = len(test_data[session_key].unique()) count = 0 print('START evaluation of ', actions, ' actions in ', sessions, ' sessions')...
class PhantomEnv(gym.Env): class Step(NamedTuple): observations: Dict[(AgentID, Any)] rewards: Dict[(AgentID, float)] terminations: Dict[(AgentID, bool)] truncations: Dict[(AgentID, bool)] infos: Dict[(AgentID, Any)] def __init__(self, num_steps: int, network: Optional[Ne...
def test_check_parameters_min_values_int(): x = torch.tensor([1, 6, 24], dtype=torch.int32) dtypes = [torch.bool] _check_parameter(x, 'x', min_value=1) _check_parameter(x, 'x', min_value=(- 1.0)) assert_raises(ValueError, _check_parameter, x, 'x', min_value=2) assert_raises(ValueError, _check_pa...
def gen_state_dict(weights_path): st = torch.load(weights_path) st_ks = list(st.keys()) st_vs = list(st.values()) state_dict = {} for (st_k, st_v) in zip(st_ks, st_vs): state_dict[st_k.replace('module.', '')] = st_v return state_dict
def _get_graph_from_original_keras_v2(model, output_dir): from tensorflow.lite.python.convert import OpsSet from tensorflow.lite.python.util import get_grappler_config, model_input_signature, run_graph_optimizations, trace_model_call from tensorflow.python.eager import def_function from tensorflow.pytho...
class Encoder(nn.Module): def __init__(self, din=32, hidden_dim=128): super(Encoder, self).__init__() self.fc = nn.Linear(din, hidden_dim) def forward(self, x): embedding = F.relu(self.fc(x)) return embedding
def _identify_bool_attributes_with_defaults(attributes, attr_name, attr_value, default=True): output = default if ((attr_name in attributes) and (attributes[attr_name] != attr_value)): output = (not default) return output
class GeomtricFixedGridODESolver(metaclass=abc.ABCMeta): order: int def __init__(self, func, y0, step_size=None, grid_constructor=None, interp='linear', perturb=False, **unused_kwargs): self.func = func self.y0 = y0 self.dtype = y0.dtype self.device = y0.device self.step_...
class HyperConv(nn.Module): def __init__(self, levels, in_channels: int, out_channels: int, kernel_size: _size_2_t, stride: _size_2_t=1, padding: _size_2_t=0, dilation: _size_2_t=1, groups: int=1, padding_mode: str='zeros', device='cpu'): super(HyperConv, self).__init__() self.levels = levels ...
.slow def test_extended_orbital_matrix_ferminet_can_be_evaluated(): (key, init_pos, slog_psis) = _make_extended_orbital_matrix_ferminets() [_jit_eval_model_and_verify_output_shape(key, init_pos, slog_psi) for slog_psi in slog_psis]
class DataCollatorForWholeWordMask(): def __init__(self, *args, **kwargs): requires_pytorch(self)
def test_print_log_logger(caplog): print_log('welcome', logger='mmcv') assert (caplog.record_tuples[(- 1)] == ('mmcv', logging.INFO, 'welcome')) print_log('welcome', logger='mmcv', level=logging.ERROR) assert (caplog.record_tuples[(- 1)] == ('mmcv', logging.ERROR, 'welcome')) with tempfile.NamedTemp...
def test_fs_observer_completed_event_updates_run(dir_obs, sample_run): (basedir, obs) = dir_obs _id = obs.started_event(**sample_run) run_dir = basedir.join(_id) obs.completed_event(stop_time=T2, result=42) run = json.loads(run_dir.join('run.json').read()) assert (run['stop_time'] == T2.isoforma...
class TimeColumn(ProgressColumn): max_refresh = 0.5 def render(self, task): elapsed_time = _format_time(task.elapsed) eta = _format_time(task.time_remaining) speed = (f'{task.speed:.2f}/s' if task.speed else '?/s') return Text(f'[{elapsed_time}<{eta}, {speed}]', style='progress.r...
class _RenameConverter(): RENAME: List[Tuple[(str, str)]] = [] def upgrade(cls, cfg: CN) -> None: for (old, new) in cls.RENAME: _rename(cfg, old, new) def downgrade(cls, cfg: CN) -> None: for (old, new) in cls.RENAME[::(- 1)]: _rename(cfg, new, old)
def test_stl_bind_global(): import pybind11_cross_module_tests as cm with pytest.raises(RuntimeError) as excinfo: cm.register_nonlocal_map() assert (str(excinfo.value) == 'generic_type: type "NonLocalMap" is already registered!') with pytest.raises(RuntimeError) as excinfo: cm.register_n...
class RobertaConfig(BertConfig): model_type = 'roberta' def __init__(self, pad_token_id=1, bos_token_id=0, eos_token_id=2, **kwargs): super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
def build_encoder_w2v(tparams, options): opt_ret = dict() trng = RandomStreams(1234) embedding = tensor.tensor3('embedding', dtype='float32') x_mask = tensor.matrix('x_mask', dtype='float32') proj = get_layer(options['encoder'])[1](tparams, embedding, None, options, prefix='encoder', mask=x_mask) ...
_registry(operator_type='MergedEmbeddingbag') class MergedEmbeddingbag(Operator): def __init__(self): super().__init__()
def initialize_network(params, device, state=None, runtime=None): if params: network_cls = NETWORKS[params.pop('type')] else: network_cls = NETWORKS[state['net']['type']] if state: return network_cls.initialize_from_state(state, device, params, runtime) return network_cls.initial...
class CLIPImageProjection(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch']) def from_config(cls, *args, **kwargs): requires_backends(cls, ['torch']) def from_pretrained(cls, *args, **kwargs): requires_backends(cl...
class BaseModel(ABC): check_optional_config = False config = None model = None def fit_eval(self, data, validation_data=None, **kwargs): invalidInputError(False, 'not implement') def save(self, checkpoint): pass def restore(self, checkpoint): pass def get_model(self):...
def lpips(input0, input1, model='net-lin', net='alex', version=0.1): batch_shape = tf.shape(input0)[:(- 3)] input0 = tf.reshape(input0, tf.concat([[(- 1)], tf.shape(input0)[(- 3):]], axis=0)) input1 = tf.reshape(input1, tf.concat([[(- 1)], tf.shape(input1)[(- 3):]], axis=0)) input0 = tf.transpose(input0...
class OpenAIGPTTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ['input_ids', 'attention_mask'] def __init__(self, vocab_file, merges_file, ...
class _num_class_mixin(): _model: nn.Module def num_classes(self): return get_model(self._model).num_classes
class ArgMutate(ExternalCallHandler): def handle(self) -> None: for mutated_sym in self.arg_syms: if ((mutated_sym is None) or mutated_sym.is_anonymous): continue mutated_sym.update_deps(set(), overwrite=False, mutated=True)
def refine_entity(entity): entity = re.sub('-LRB- .+ -RRB-$', '', entity) entity = re.sub('LRB .+ RRB$', '', entity) entity = re.sub('\\(.*\\)', '', entity) entity = re.sub('_', ' ', entity) entity = re.sub('\\s+', ' ', entity) return entity.strip()
_grad() def evaluate(data_loader, model, device, amp=True, choices=None, mode='super', retrain_config=None, is_visual_prompt_tuning=False, is_adapter=False, is_LoRA=False, is_prefix=False): criterion = torch.nn.CrossEntropyLoss() metric_logger = utils.MetricLogger(delimiter=' ') header = 'Test:' model....
def disable_running_stats(model): def _disable(module): if isinstance(module, nn.BatchNorm2d): module.backup_momentum = module.momentum module.momentum = 0 model.apply(_disable)
class SpatialShareConvolution(Layer): def __init__(self, n_input_plane, n_output_plane, kernel_w, kernel_h, stride_w=1, stride_h=1, pad_w=0, pad_h=0, n_group=1, propagate_back=True, wRegularizer=None, bRegularizer=None, init_weight=None, init_bias=None, init_grad_weight=None, init_grad_bias=None, with_bias=True, bi...
class PillowCodec(Codec): fmt = None def name(self): raise NotImplementedError() def _load_img(self, img): return read_image(img) def _run(self, img, quality, return_rec=False, return_metrics=True): start = time.time() tmp = io.BytesIO() img.save(tmp, format=self....
def test_UnetFCAM(): import datetime as dt cuda = '1' DEVICE = torch.device(('cuda:{}'.format(cuda) if torch.cuda.is_available() else 'cpu')) encoders = dlib.encoders.get_encoder_names() encoders = [constants.INCEPTIONV3, constants.VGG16, constants.RESNET50] SZ = 224 in_channels = 3 bsz ...
class DataProcessor(object): def get_conll_train_examples(self, data_dir): return self._create_examples(self._read_pkl(os.path.join(data_dir, 'conll_train.pkl')), 'conll_train') def get_conll_dev_examples(self, data_dir): return self._create_examples(self._read_pkl(os.path.join(data_dir, 'conll_...
def _latex_line_begin_tabular(colwidths, colaligns): alignment = {'left': 'l', 'right': 'r', 'center': 'c', 'decimal': 'r'} tabular_columns_fmt = ''.join([alignment.get(a, 'l') for a in colaligns]) return (('\\begin{tabular}{' + tabular_columns_fmt) + '}\n\\hline')
class Block(nn.Module): def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=True, drop_path=0.0, norm_layer=nn.LayerNorm, act_layer=nn.GELU, use_rel_pos=False, rel_pos_zero_init=True, window_size=0, use_residual_block=False, input_size=None): super().__init__() self.norm1 = norm_layer(dim) ...
def filter_exists(filenames, base_path): full_paths = [os.path.join(base_path, 'configs', fl) for fl in filenames] full_paths = [fl for fl in full_paths if os.path.exists(fl)] return full_paths
def get_glow_cnn(num_input_channels, num_hidden_channels, num_output_channels, zero_init_output): conv1 = nn.Conv2d(in_channels=num_input_channels, out_channels=num_hidden_channels, kernel_size=3, padding=1, bias=False) bn1 = nn.BatchNorm2d(num_hidden_channels) conv2 = nn.Conv2d(in_channels=num_hidden_chann...
class Predictor(BasePredictor): def setup(self): args = parse_args(parse=False, backbone='t5-base', load='VL-T5/snap/pretrain/VLT5/Epoch30') args.gpu = 0 self.trainer = Trainer(args, train=False) OBJ_URL = ' ATTR_URL = ' self.object_ids = get_data(OBJ_URL) sel...
class GraphConvolution(nn.Module): def __init__(self, in_feature, out_feature, bias=True): super(GraphConvolution, self).__init__() self.in_features = in_feature self.out_features = out_feature self.weight = Parameter(torch.FloatTensor(in_feature, out_feature)) if bias: ...
def _get_bin_idx(label): if (label == 5.0): return (bins - 1) else: return (np.where((bins_edges > label))[0][0] - 1)
def parseArgs(): parser = argparse.ArgumentParser(description='Write image label path pairs of train and valid sets to txt file.') parser.add_argument('-d', dest='data_home', type=str, default='./', help='dataset home directory.') parser.add_argument('-t', dest='useTrain', help='use train set directory.', a...
def createModel(net, domain, domain_name): (net_weights, net_create) = net domain.name = domain_name net = net_create(num_classes).infer(input_dims) net.load_state_dict(net_weights.state_dict()) model = Top(args, net, domain) model.clip_norm() if h.use_cuda: model.cuda() model.op...
class BertConfig(PretrainedConfig): model_type = 'bert' def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initia...