code
stringlengths
101
5.91M
class TPCheckpointWrapper(TorchWrapper): def __init__(self, mod, checkpoint_fn): super().__init__(mod) self.checkpoint_fn = checkpoint_fn def forward(self, *args, **kwargs): (flat_args, kwarg_keys) = _pack_kwargs(*args, **kwargs) def my_function(*inputs): (unpacked_ar...
def ReadGt_ctw(fileroot, filename): with open(((fileroot + filename) + '.txt')) as f: lst = f.readlines() return lst
def main(args): _start_() data_loader = _load_data() (corpus_dev, batch_idx_dev, en_batch_dev, processed_tree_dev) = data_loader.load_dev(args.dataset_dev) if (args.test == 'yes'): (corpus_test, batch_idx_test, en_batch_test, processed_tree_test) = data_loader.load_dev(args.dataset_test) els...
class Path(object): def db_root_dir(dataset): if (dataset == 'sceneflow'): return './dataset/SceneFlow/' elif (dataset == 'kitti15'): return './dataset/kitti2015/training/' elif (dataset == 'kitti12'): return './dataset/kitti2012/training/' elif (d...
def relative_path(path_map: Dict[(Path, Path)], filename: Path): for p in path_map: if (p in filename.parents): return (path_map[p] / filename.relative_to(p)) raise Exception()
def get_arg_parser(): parser = argparse.ArgumentParser() parser.add_argument('--data_location', help='Full path of train data', required=False, default='./data') parser.add_argument('--steps', help='set the number of steps on train dataset', type=int, default=0) parser.add_argument('--batch_size', help=...
class FaultTolerantDistributedSampler(DistributedSampler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.counter = 0 self.restarting = False def state_dict(self): return {'epoch': self.epoch, 'counter': self.counter} def load_state_dict(self, sta...
def prepare_parser(): usage = 'Parser for all scripts.' parser = ArgumentParser(description=usage) parser.add_argument('--dataset', type=str, default='I128_hdf5', help='Which Dataset to train on, out of I128, I256, C10, C100;Append "_hdf5" to use the hdf5 version for ISLVRC (default: %(default)s)') pars...
def random_function(image, function, prob, seed=None, **kwargs): with tf.name_scope(('random_' + function.__name__)): uniform_random = tf.random.uniform([], 0, 1.0, seed=seed) mirror_cond = tf.math.less(uniform_random, prob) result = tf.cond(mirror_cond, (lambda : function(image, **kwargs)),...
def FindNextMultiLineCommentEnd(lines, lineix): while (lineix < len(lines)): if lines[lineix].strip().endswith('*/'): return lineix lineix += 1 return len(lines)
def osnet_x1_0_ms25_a0d1(num_classes=1000, pretrained=True, loss='softmax', **kwargs): model = OSNet(num_classes, blocks=[OSBlock, OSBlock, OSBlock], layers=[2, 2, 2], channels=[64, 256, 384, 512], loss=loss, mixstyle_layers=['conv2', 'conv5'], mixstyle_alpha=0.1, **kwargs) if pretrained: init_pretraine...
def parse_args(): parser = argparse.ArgumentParser(description='Convert MMSeg to TorchScript') parser.add_argument('config', help='test config file path') parser.add_argument('--checkpoint', help='checkpoint file', default=None) parser.add_argument('--show', action='store_true', help='show TorchScript g...
def test_actionAngleTorus_AutoFitWarning(): from galpy.actionAngle import actionAngleTorus from galpy.potential import LogarithmicHaloPotential lp = LogarithmicHaloPotential(normalize=1.0, q=0.9) aAT = actionAngleTorus(pot=lp, tol=(10.0 ** (- 8.0))) (jr, jp, jz) = (0., 1., 0.6078445) (ar, ap, az...
def make_self_attn_gnn(): return self_attn_gnn(kq_dim=FLAGS.attn_kq_dim, v_dim=FLAGS.attn_v_dim, make_mlp_fn=partial(make_mlp_model, FLAGS.gnn_latent_dim, (FLAGS.node_embedding_dim / 2), FLAGS.gnn_num_layers, tf.nn.relu, FLAGS.gnn_l2_regularizer_weight, FLAGS.gnn_bias_init_stddev), kq_dim_division=True)
class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bnx1 = bn.BatchNorm2dEx(planes) self.conv2 = nn.Conv2...
def run_random(env_name): config = {'robot_base': 'xmls/point.xml', 'task': 'defense', 'goal_size': 0.5, 'observe_robbers': True, 'observe_hazards': True, 'constrain_hazards': True, 'constrain_indicator': False, 'lidar_num_bins': 16, 'hazards_num': 8, 'hazards_size': 0.3, 'robbers_num': 2, 'robbers_size': 0.3} ...
class Model(torch.nn.Module): _warn_for_unseparable_batches: Set[str] = set() def __init__(self, regularizer=None) -> None: super().__init__() self._regularizer = regularizer def get_regularization_penalty(self) -> Union[(float, torch.Tensor)]: if (self._regularizer is None): ...
def load_data(root_path, source_dir, target_dir, batch_size): kwargs = {'num_workers': 4, 'pin_memory': True} source_loader = load_training(root_path, source_dir, batch_size, kwargs) target_loader = load_training(root_path, target_dir, batch_size, kwargs) test_loader = load_testing(root_path, target_dir...
def collate_fn(batch): data = {} for key in ['x', 'x_attr', 'x_positions', 'x_centers', 'x_angles', 'x_velocity', 'x_velocity_diff', 'lane_positions', 'lane_centers', 'lane_angles', 'lane_attr', 'is_intersections']: data[key] = pad_sequence([b[key] for b in batch], batch_first=True) if ('x_scored' i...
class DistilBertOnnxConfig(OnnxConfig): def inputs(self) -> Mapping[(str, Mapping[(int, str)])]: return OrderedDict([('input_ids', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'})])
class Max(ZooKerasLayer): def __init__(self, dim, num_input_dims=INTMIN, return_value=True, input_shape=None, **kwargs): super(Max, self).__init__(None, dim, num_input_dims, return_value, (list(input_shape) if input_shape else None), **kwargs)
_model_architecture('s2t_conformer', 's2t_conformer') def conformer_base_architecture(args): args.attn_type = getattr(args, 'attn_type', None) args.pos_enc_type = getattr(args, 'pos_enc_type', 'abs') args.input_feat_per_channel = getattr(args, 'input_feat_per_channel', 80) args.input_channels = getattr(...
class rd_decoded_rm_depth_ahat(): def open(self, filename, chunk, profile): self._client = reader() self._client.open(filename, chunk) self._codec = hl2ss.decode_rm_depth_ahat(profile) self._codec.create() self.read() def read(self): data = self._client.read() ...
class TokenLengthAnalysis(): def __init__(self, file_paths, types, encoding_name='cl100k_base'): self.file_paths = file_paths self.types = types self.encoding_name = encoding_name def num_tokens_from_string(self, string): encoding = tiktoken.get_encoding(self.encoding_name) ...
class CSPDarkNet(object): __shared__ = ['norm_type', 'weight_prefix_name'] def __init__(self, depth=53, norm_type='bn', norm_decay=0.0, weight_prefix_name=''): assert (depth in [53]), 'unsupported depth value' self.depth = depth self.norm_type = norm_type self.norm_decay = norm_d...
_schema(UchannelLOSchema) class UchannelLO(BaseModel): def __init__(self, q, scale, **kwargs): self.q = q self.scale = scale super().__init__(q=q, scale=scale, **kwargs)
def read_matches_files(data_dir, matches_file): matches = [] with open(os.path.join(data_dir, matches_file), 'r') as f: for line in f: l = line.split() matches.append([int(l[0]), int(l[3]), int((l[1] == l[4]))]) return torch.LongTensor(matches)
_torch _vision class BridgeTowerImageProcessingTest(ImageProcessingSavingTestMixin, unittest.TestCase): image_processing_class = (BridgeTowerImageProcessor if is_vision_available() else None) def setUp(self): self.image_processor_tester = BridgeTowerImageProcessingTester(self) def image_processor_di...
class Image2D(Dataset): def __init__(self, dataset_path: str, transform: Callable=None): self.dataset_path = dataset_path self.input_path = os.path.join(dataset_path, 'img') self.images_list = os.listdir(self.input_path) if transform: self.transform = transform el...
class DeepText(nn.Module): def __init__(self, vocab_size: int, rnn_type: str='lstm', hidden_dim: int=64, n_layers: int=3, rnn_dropout: float=0.1, bidirectional: bool=False, use_hidden_state: bool=True, padding_idx: int=1, embed_dim: Optional[int]=None, embed_matrix: Optional[np.ndarray]=None, embed_trainable: bool=...
def is_div_level(maybe_div, level): if (maybe_div is None): return False return ((maybe_div.name == 'div') and ('level' in maybe_div.attrs) and (maybe_div.attrs['level'] == str(level)))
def get_only_chars(line): clean_line = '' line = line.replace('', '') line = line.replace("'", '') line = line.replace('-', ' ') line = line.replace('\t', ' ') line = line.replace('\n', ' ') line = line.lower() for char in line: if (char in 'qwertyuiopasdfghjklzxcvbnm '): ...
class Plateau(JavaValue): def __init__(self, monitor, factor=0.1, patience=10, mode='min', epsilon=0.0001, cooldown=0, min_lr=0.0, bigdl_type='float'): JavaValue.__init__(self, None, bigdl_type, monitor, factor, patience, mode, epsilon, cooldown, min_lr)
def get_metrics_names(metrics): if (len(metrics) == 0): return [] metrics_dict = next(iter(metrics.values())) return list(metrics_dict.keys())
class OptimizationArguments(): auto_distillation: bool = field(default=False, metadata={'help': 'Whether or not to apply distillation.'}) teacher_config_name: Optional[str] = field(default=None, metadata={'help': 'Pretrained config name or path if not the same as model_name'}) teacher_model_name_or_path: st...
def DenseNet(blocks, include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000, residuals=False, **kwargs): if (not ((weights in {'imagenet', None}) or os.path.exists(weights))): raise ValueError('The `weights` argument should be either `None` (random initializati...
def get_next_activity_model(max_case_length, vocab_size, output_dim, embed_dim=36, num_heads=4, ff_dim=64): inputs = layers.Input(shape=(max_case_length,)) x = TokenAndPositionEmbedding(max_case_length, vocab_size, embed_dim)(inputs) x = TransformerBlock(embed_dim, num_heads, ff_dim)(x) x = layers.Globa...
def detect_pattern_anomaly(y, yhat, th, dist_measure): anomaly_indexes = [] for (i, (y_i, yhat_i)) in enumerate(zip(y, yhat)): if (dist_measure.abs_dist(y_i, yhat_i) > th): anomaly_indexes.append(i) return anomaly_indexes
class CustomCallback(Callback): def on_train_end(self, logs=None): assert ('train_loss' in logs) assert ('val_loss' in logs) assert self.model def on_epoch_end(self, epoch, logs=None): assert ('train_loss' in logs) assert ('val_loss' in logs) assert self.model
def train_model_wrapper(config): datapath = config['datapath'] output = config['output'] appliance = config['appliance'] hparams = config['hparams'] doplot = config['doplot'] reload = config['reload'] tune_hparams = config['tune'] appliance['hparams']['F'] = tune_hparams['F'] applian...
def test_plot_projected(tmp_path, corpus): n = tn.Textnet(corpus.tokenized()) papers = n.project(node_type=tn.DOC) out = (tmp_path / 'plot-2.png') plot = papers.plot(show_clusters=True, label_nodes=True, target=str(out)) assert (len(plot._objects) > 0) assert (len(list(tmp_path.iterdir())) == 1)
def to_tensor(x, dtype=None) -> torch.Tensor: if isinstance(x, torch.Tensor): if (dtype is not None): x = x.type(dtype) return x if isinstance(x, np.ndarray): x = torch.from_numpy(x) if (dtype is not None): x = x.type(dtype) return x if isinsta...
def checkpoint_cb(checkpoint_path, steps_per_epoch=(- 1), num_epochs=10): checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(filepath=os.path.join(checkpoint_path, 'cp-{epoch:04d}.ckpt'), monitor='val_loss', verbose=0, save_best_only=False, save_weights_only=False, mode='auto', save_freq=('epoch' if (steps_pe...
_module() class VOCDataset(XMLDataset): CLASSES = ('aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor') def __init__(self, **kwargs): super(VOCDataset, self).__in...
def dump_json(filename, data): pathlib.Path(os.path.dirname(filename)).mkdir(parents=True, exist_ok=True) with open(filename, 'w') as f: json.dump(data, f, indent=2, sort_keys=True, cls=LogEncoder)
class IndexedRowTableLinearize(): def process_table(self, table_content: Dict): assert (('header' in table_content) and ('rows' in table_content)), self.PROMPT_MESSAGE table_str = (self.process_header(table_content['header']) + ' ') for (i, row_example) in enumerate(table_content['rows']): ...
def postprocess3D(data, isU=True, resFlag=0, num=None): x = np.linspace((- 50), 50, 48) y = np.linspace((- 50), 50, 48) z = np.linspace((- 50), 50, 48) (x, y, z) = np.meshgrid(x, y, z) appd = ['PeRCNNTruth'] uv = ['v', 'u'] values = data fig = go.Figure(data=go.Isosurface(x=x.flatten(), ...
_module class BFP(nn.Module): def __init__(self, in_channels, num_levels, refine_level=2, refine_type=None, conv_cfg=None, norm_cfg=None): super(BFP, self).__init__() assert (refine_type in [None, 'conv', 'non_local']) self.in_channels = in_channels self.num_levels = num_levels ...
class TestATSSHead(TestCase): def test_atss_head_loss(self): s = 256 img_metas = [{'img_shape': (s, s, 3), 'pad_shape': (s, s, 3), 'scale_factor': 1}] cfg = Config(dict(assigner=dict(type='ATSSAssigner', topk=9), allowed_border=(- 1), pos_weight=(- 1), debug=False)) atss_head = ATSSH...
def test_warn_internal_when_use_physical(): import warnings from galpy import potential from galpy.util import galpyWarning with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always', galpyWarning) potential.evaluateRforces(potential.MWPotential2014, 1.0, 0.0, use_phy...
class TestPSI(FLTest): def setUp(self) -> None: self.fl_server = FLServer() self.fl_server.set_port(self.port) self.fl_server.build() self.fl_server.start() def tearDown(self) -> None: self.fl_server.stop() def test_psi_get_salt(self): init_fl_context(1, self....
class Position(NamedTuple): row: chex.Array col: chex.Array def __eq__(self, other: 'Position') -> chex.Array: if (not isinstance(other, Position)): return NotImplemented return ((self.row == other.row) & (self.col == other.col)) def __add__(self, other: 'Position') -> 'Posit...
def test(model, test_loader): model.eval() test_loss = 0 correct = 0 with torch.no_grad(): for (data, target) in test_loader: if args.cuda: (data, target) = (data.cuda(), target.cuda()) (s_output, t_output) = model(data, data, target) test_loss...
def load_data_normalised(root_path): (data, labels) = load_data(root_path) data = ((data - data.mean(axis=0)) / data.std(axis=0)) return (data, labels)
class SqueezeNet(nn.Module): def __init__(self, version=1.0, num_classes=1000): super(SqueezeNet, self).__init__() if (version not in [1.0, 1.1]): raise ValueError('Unsupported SqueezeNet version {version}:1.0 or 1.1 expected'.format(version=version)) self.num_classes = num_class...
def overwrite_args_from_json(fpath, args): with open(fpath, 'r') as f: json_dict = json.load(f) key = 'args' if (key in json_dict): for kk in json_dict[key]: setattr(args, kk, json_dict[key][kk]) return json_dict
class QLinearVQ(nn.Linear): def __init__(self, in_features, out_features, bias=True, num_bits=8, num_bits_weight=8, num_bits_grad=None, perC=True, biprecision=False, measure=False, cal_qparams=False): super(QLinearVQ, self).__init__(in_features, out_features, bias) self.num_bits = num_bits s...
def test_game_2048__step_jit(game_2048: Game2048) -> None: key = jax.random.PRNGKey(0) (state, timestep) = game_2048.reset(key) action = jnp.argmax(state.action_mask) chex.clear_trace_counter() step_fn = jax.jit(chex.assert_max_traces(game_2048.step, n=1)) (new_state, next_timestep) = step_fn(st...
def main(): input_folder = '/mnt/SSD/xtwang/BasicSR_datasets/DIV2K800/DIV2K800' save_folder = '/mnt/SSD/xtwang/BasicSR_datasets/DIV2K800/DIV2K800_gray' mode = 'gray' compression_level = 3 n_thread = 20 if (not os.path.exists(save_folder)): os.makedirs(save_folder) print('mkdir [{...
class AStar(): __metaclass__ = ABCMeta __slots__ = () class SearchNode(): __slots__ = ('data', 'gscore', 'fscore', 'closed', 'came_from', 'out_openset') def __init__(self, data, gscore=Infinite, fscore=Infinite): self.data = data self.gscore = gscore self....
def find_intermediate_values(spin_df): spin_df = find_release_point(spin_df) spin_df = find_release_time(spin_df) spin_df = find_release_velocity_components(spin_df) spin_df = find_flight_time(spin_df) spin_df = find_average_velocity_components(spin_df) spin_df = find_average_velocity(spin_df) ...
class GaussianMixin(): def reset_variational_parameters(self): self.log_sigma2.data.uniform_((- 10), (- 10)) def log_alpha(self): return (self.log_sigma2 - (2 * torch.log((abs(self.weight) + 1e-12))))
def th_pack(tensor): batch_size = tensor.shape[0] padding = tensor.new_zeros((batch_size, 4, 3)) padding.requires_grad = False pack_list = [padding, tensor] pack_res = torch.cat(pack_list, 2) return pack_res
def get_flow_combinations_randomly_initalised(flow_names): if (type(flow_names) is list): flow_arr = [] easy_inv_flow_arr = [] for flow in flow_names: (flow_random, easy_inv_flow) = get_flow_combinations_randomly_initalised(flow) flow_arr.append(flow_random) ...
def _quantize(x, bin_edges): bin_edges = copy.copy(bin_edges) bin_edges = sorted(bin_edges) quantized = list(map((lambda y: bisect.bisect_right(bin_edges, y)), x)) return quantized
class TestLMPlots(): def test_save_rankings_plot(self, rankings_plot_data_1): lm_plots.plot_inner_token_rankings(**rankings_plot_data_1, save_file_path='./tmp/ranking_1.png') def test_save_ranking_watch_plot(self, ranking_watch_data_1): lm_plots.plot_inner_token_rankings_watch(**ranking_watch_da...
_module() class InstaBoost(object): def __init__(self, action_candidate=('normal', 'horizontal', 'skip'), action_prob=(1, 0, 0), scale=(0.8, 1.2), dx=15, dy=15, theta=((- 1), 1), color_prob=0.5, hflag=False, aug_ratio=0.5): try: import instaboostfast as instaboost except ImportError: ...
def patch_llama_for_ntk_scaled_rotary_embeddings(model, alpha): from .LlamaNTKScaledRotaryEmbedding import LlamaNTKScaledRotaryEmbedding for each in model.model.layers: each.self_attn.rotary_emb = LlamaNTKScaledRotaryEmbedding(each.self_attn.head_dim, alpha=alpha, device=each.self_attn.rotary_emb.inv_fr...
class CUBDataset(ConfounderDataset): def __init__(self, root_dir, target_name, confounder_names, augment_data=False, model_type=None): self.root_dir = root_dir self.target_name = target_name self.confounder_names = confounder_names self.model_type = model_type self.augment_da...
.parametrize('loss_class', [IoULoss, BoundedIoULoss, GIoULoss, DIoULoss, CIoULoss, MSELoss, L1Loss, SmoothL1Loss, BalancedL1Loss]) .parametrize('input_shape', [(10, 4), (0, 4)]) def test_regression_losses(loss_class, input_shape): pred = torch.rand(input_shape) target = torch.rand(input_shape) weight = torc...
def train(args, model): if (not osp.isdir(args.root)): os.makedirs(args.root) with open(osp.join(args.root, 'args.yaml'), 'w') as f: yaml.dump(args.__dict__, f) train_ds = CelebA(train=True) eval_ds = CelebA(train=False) train_loader = torch.utils.data.DataLoader(train_ds, batch_size...
.dataclass class FlaxNextSentencePredictorOutput(ModelOutput): logits: jnp.ndarray = None hidden_states: Optional[Tuple[jnp.ndarray]] = None attentions: Optional[Tuple[jnp.ndarray]] = None
def process(words, labels, tokenizer, vocabulary, max_seq_length): input_id = [] label_id = [] words = ((['[CLS]'] + words) + ['[SEP]']) labels = ((['O'] + labels) + ['O']) for word in words: token = tokenizer.tokenize(word) input_id.extend(token) input_id = tokenizer.convert_tok...
class Pybind11Extension(_Extension): def _add_cflags(self, flags: List[str]) -> None: self.extra_compile_args[:0] = flags def _add_ldflags(self, flags: List[str]) -> None: self.extra_link_args[:0] = flags def __init__(self, *args: Any, **kwargs: Any) -> None: self._cxx_level = 0 ...
def check_file(filepath, md5sum): try: md5 = hashlib.md5() with open(filepath, 'rb') as f: for chunk in iter(partial(f.read, 4096), b''): md5.update(chunk) return (md5.hexdigest() == md5sum) except FileNotFoundError: return False
class AutoModelForQuestionAnswering(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def test(): net = VGG('VGG11', input_size=32, num_class=10) print(net) x = torch.randn(128, 3, 96, 96) y = net(x) print(y.size())
def file_based_convert_examples_to_features(examples, label_list, max_seq_length, tokenizer, output_file): writer = tf.compat.v1.python_io.TFRecordWriter(output_file) for (ex_index, example) in enumerate(examples): if ((ex_index % 10000) == 0): tf.compat.v1.logging.info(('Writing example %d ...
def train_vanilla(args, io): train_loader = DataLoader(ModelNet40(args, partition='train'), num_workers=8, batch_size=args.batch_size, shuffle=True, drop_last=True) test_loader = DataLoader(ModelNet40(args, partition='test'), num_workers=8, batch_size=args.test_batch_size, shuffle=True, drop_last=False) dev...
class GetMatrix(nn.Module): def __init__(self, dim_in, dim_out): super(GetMatrix, self).__init__() self.get_gamma = nn.Conv2d(dim_in, dim_out, kernel_size=1, stride=1, padding=0, bias=False) self.get_beta = nn.Conv2d(dim_in, dim_out, kernel_size=1, stride=1, padding=0, bias=False) def fo...
class LookupDuplicateError(Exception): def __init__(self, message: str): self.message = message
def efficientnet_b5(in_size=(456, 456), **kwargs): return get_efficientnet(version='b5', in_size=in_size, model_name='efficientnet_b5', **kwargs)
def resnetbc14b_cub(num_classes=200, **kwargs): return get_resnet(num_classes=num_classes, blocks=14, bottleneck=True, conv1_stride=False, model_name='resnetbc14b_cub', **kwargs)
class ExampleClass(): def __init__(self, param1, param2, param3): self.attr1 = param1 self.attr2 = param2 self.attr3 = param3 self.attr4 = ['attr4'] self.attr5 = None def property1(self): return 'property1' def method1(self, param1, param2): return Tru...
class BasicTransformerBlock(nn.Module): def __init__(self, dim, n_heads, d_head, dropout=0.0, context_dim=None, gated_ff=True, checkpoint=True): super().__init__() self.attn1 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout) self.ff = FeedForward(dim, dropout=d...
def delete_oleans(lean_files: List[Path]): for file_path in lean_files: olean = file_path.with_suffix('.olean') if olean.exists(): olean.unlink()
class DataTrainingArguments(): data_dir: str = field(metadata={'help': 'The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task.'}) labels: Optional[str] = field(default=None, metadata={'help': 'Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.'}) ...
def test(args, model, device, x, y, criterion, task_id_nominal, curr_task_masks=None, mode='test'): model.eval() total_loss = 0 total_num = 0 correct = 0 r = np.arange(x.size(0)) np.random.shuffle(r) r = torch.LongTensor(r).to(device) with torch.no_grad(): for i in range(0, len(r...
class OneHotBool(enum.IntEnum): NONE = 0 TRUE = 1 FALSE = 2 def from_bool(b): if b: return OneHotBool.TRUE return OneHotBool.FALSE def __str__(self): return self.name def __repr__(self): return self.name
def main_worker(gpu, ngpus_per_node, args): global best_acc1 args.gpu = gpu if (args.multiprocessing_distributed and (args.gpu != 0)): def print_pass(*args): pass builtins.print = print_pass if (args.gpu is not None): print('Use GPU: {} for training'.format(args.gpu))...
class DPMSolverSinglestepScheduler(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_ba...
def add_data(filename, split, ours): for ls in open(filename): instance = json.loads(ls) db = instance['table_id'] question = instance['question'] phase = instance['phase'] query = Query.from_dict(instance['sql']) info = {'query-split': 'N/A', 'sentences': [{'question...
def collate(batch): databatch = [b[0] for b in batch] labelbatch = [b[1] for b in batch] lenbatch = [len(b[0][0][0]) for b in batch] databatchTensor = collate_tensors(databatch) labelbatchTensor = torch.as_tensor(labelbatch) lenbatchTensor = torch.as_tensor(lenbatch) maskbatchTensor = length...
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp10(): state = prototype_state() state['end_sym_utterance'] = '__eot__' state['unk_sym'] = 0 state['eos_sym'] = 1 state['eod_sym'] = (- 1) state['first_speaker_sym'] = (- 1) state['second_speaker_sym'] = (- 1) state['third_speaker_sym'] ...
def _isDissipative(obj): from .planarDissipativeForce import planarDissipativeForce from .Potential import flatten obj = flatten(obj) isList = isinstance(obj, list) if isList: isCons = [((not isinstance(p, DissipativeForce)) and (not isinstance(p, planarDissipativeForce))) for p in obj] ...
def auto_augment_policy_v0(hparams): policy = [[('Equalize', 0.8, 1), ('ShearY', 0.8, 4)], [('Color', 0.4, 9), ('Equalize', 0.6, 3)], [('Color', 0.4, 1), ('Rotate', 0.6, 8)], [('Solarize', 0.8, 3), ('Equalize', 0.4, 7)], [('Solarize', 0.4, 2), ('Solarize', 0.6, 2)], [('Color', 0.2, 0), ('Equalize', 0.8, 8)], [('Equ...
class AutoModelForNextSentencePrediction(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
def cwh_to_whc(img: torch.Tensor) -> torch.Tensor: if (len(img.shape) == 3): return img.permute(1, 2, 0) elif (len(img.shape) == 4): return img.permute(0, 2, 3, 1) else: raise ValueError(f'Invalid shape for channel conversion. Expected 3 or 4 dims, got {len(img.shape)} (shape={img.sh...
def sanity_check_labels(data_folder: Path, competitions: Optional[List[T4c22Competitions]]): summary = [] all_good = True if ((competitions is None) or (T4c22Competitions.CORE in competitions)): print(f'/ start core competition check') d = {} for city in CITIES: cc_sum = ...
class ModulatedDeformRoIPoolingPack(DeformRoIPooling): def __init__(self, spatial_scale, out_size, out_channels, no_trans, group_size=1, part_size=None, sample_per_part=4, trans_std=0.0, num_offset_fcs=3, num_mask_fcs=2, deform_fc_channels=1024): super(ModulatedDeformRoIPoolingPack, self).__init__(spatial_s...