code
stringlengths
101
5.91M
class DDIMSchedulerOutput(BaseOutput): prev_sample: torch.FloatTensor pred_original_sample: Optional[torch.FloatTensor] = None
def _sum_clones_gradients(clone_grads): sum_grads = [] for grad_and_vars in zip(*clone_grads): grads = [] var = grad_and_vars[0][1] for (g, v) in grad_and_vars: assert (v == var) if (g is not None): grads.append(g) if grads: if ...
def main(): args = get_args() labels = [' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', "'"] manifest = Manifest(args.dataset_dir, [args.manifest], labels, len(labels), normalize=True, max_duration=15.0) with open(os....
def run(args): (acc_db, loss_db, hessian_eig_db) = init_experiment(args) print('Loading {} tasks for {}'.format(args.tasks, args.dataset)) tasks = get_benchmark_data_loader(args)(args.tasks, args.batch_size) print('loaded all tasks!') model = get_benchmark_model(args) criterion = nn.CrossEntropy...
class TemplateHitFeaturizer(): def __init__(self, mmcif_dir: str, max_template_date: str, max_hits: int, kalign_binary_path: str, release_dates_path: Optional[str]=None, obsolete_pdbs_path: Optional[str]=None, strict_error_check: bool=False, _shuffle_top_k_prefiltered: Optional[int]=None, _zero_center_positions: bo...
def main(_): if (not FLAGS.dataset_name): raise ValueError('You must supply the dataset name with --dataset_name') if (not FLAGS.dataset_dir): raise ValueError('You must supply the dataset directory with --dataset_dir') if (FLAGS.dataset_name == 'cifar10'): download_and_convert_cifar...
class MultipleMetrics(object): def __init__(self, metrics: List[Union[(Metric, object)]], prefix: str=''): instantiated_metrics = [] for metric in metrics: if isinstance(metric, type): instantiated_metrics.append(metric()) else: instantiated_me...
class ChatCompletionRequest(BaseModel): model: str messages: List[ChatMessage] temperature: Optional[float] = None top_p: Optional[float] = None max_length: Optional[int] = None stream: Optional[bool] = False
def report_num_trainable_parameters(model: torch.nn.Module) -> int: assert isinstance(model, torch.nn.Module), 'Argument must be nn.Module' num_parameters = 0 for (name, p) in model.named_parameters(): if p.requires_grad: num_parameters += np.prod(list(p.size())) logger.info(...
def object_detect(args): mp.set_start_method('spawn', force=True) logger = logging.getLogger() cfg = setup_cfg(args) demo = UnifiedVisualizationDemo(cfg) if args.img_path: img_path = [args.img_path] else: img_folder = os.path.join(args.data_root, args.img_dir) img_list = ...
def _isint(string): return ((type(string) is int) or ((isinstance(string, _binary_type) or isinstance(string, _text_type)) and _isconvertible(int, string)))
class DummyDataset(Dataset): def __init__(self, images, labels, trsf, use_path=False): assert (len(images) == len(labels)), 'Data size error!' self.images = images self.labels = labels self.trsf = trsf self.use_path = use_path def __len__(self): return len(self.im...
def test_digits_sqrt_sample_sparse(): model = FeatureBasedSelection(100, 'sqrt', optimizer='sample', random_state=0) model.fit(X_digits_sparse) assert_array_equal(model.ranking, digits_sqrt_sample_ranking) assert_array_almost_equal(model.gains, digits_sqrt_sample_gains, 4) assert_array_almost_equal(...
class MetaSpecProp(SpecProp): def __init__(self, module, device='cpu'): self._device = device super().__init__(module) self.fake_module = None self.fake_mode = None def call_module(self, target, args, kwargs): assert isinstance(target, str) submod = self.fetch_att...
def download_azure(directory=None, raw_data=False): logger.info(f'downloading data into {directory}') downloader = BlobFileDownloader(directory) if raw_data: prefix = 'raw' else: prefix = 'train' downloader.download_blobs_in_container(prefix=prefix) logger.info('Extracting files....
def remove_weight_norm(module, name='weight'): for (k, hook) in module._forward_pre_hooks.items(): if (isinstance(hook, BoundedWeightNorm) and (hook.name == name)): hook.remove(module) del module._forward_pre_hooks[k] return module raise ValueError("weight_norm of '{}...
class DropBlock2d(nn.Module): def __init__(self, drop_prob=0.1, block_size=7, gamma_scale=1.0, with_noise=False, inplace=False, batchwise=False, fast=True): super(DropBlock2d, self).__init__() self.drop_prob = drop_prob self.gamma_scale = gamma_scale self.block_size = block_size ...
class TestClassifier(unittest.TestCase): def test_inspect(self): cba = CBA() test_dataframe = pd.read_csv(dataset_file, sep=';') transactions = TransactionDB.from_DataFrame(test_dataframe) cba.fit(transactions) clf = cba.clf inspect_df = clf.inspect() self.ass...
def adjust_shape(placeholder, data): if ((not isinstance(data, np.ndarray)) and (not isinstance(data, list))): return data if isinstance(data, list): data = np.array(data) placeholder_shape = [(x or (- 1)) for x in placeholder.shape.as_list()] assert _check_shape(placeholder_shape, data....
def backprop(dataset, model, optimizer): total = 0 for feat in dataset: feature = feat[0] feature = torch.tensor(feature, dtype=torch.float) y_pred = model(feature) y_true = feat[1] optimizer.zero_grad() loss = custom_loss(y_pred, y_true, model.name) loss....
def assert_type_bin_pack_state(state: State) -> None: jax.tree_util.tree_map((lambda leaf: chex.assert_type(leaf, jnp.int32)), (state.container, state.ems, state.items, state.items_location, state.sorted_ems_indexes)) jax.tree_util.tree_map((lambda leaf: chex.assert_type(leaf, bool)), (state.ems_mask, state.ite...
def batch_shuffle(x): batch_size_this = x.shape[0] (all_xs, batch_size_all) = concat_all_gather(x) all_xs_concat = torch.cat(all_xs, dim=0) total_bs = sum(batch_size_all) rank = dist.get_rank() assert (batch_size_all[rank] == batch_size_this) idx_range = (sum(batch_size_all[:rank]), sum(batc...
class PyTorchMultiTargetInferSentModelModule(torch.nn.Module): def __init__(self, W_emb, max_len, rnn_size=300, hidden_size=300, dropout=0.2, regularization=1e-06, trainable_embeddings=False, learning_rate=0.001, pool_type='max', use_umls_attention=False, **kwargs): super(PyTorchMultiTargetInferSentModelMod...
class M4COCRVQADataset(M4CTextVQADataset): def __init__(self, dataset_type, imdb_file_index, config, *args, **kwargs): super().__init__(dataset_type, imdb_file_index, config, *args, **kwargs) self._name = 'm4c_ocrvqa'
class HAIKU(AbstractTask): name = 'haiku' metric = [metrics.calculate_rouge] metric_names = ['rouge'] split_to_data_split = {'train': 'train', 'validation': 'validation'} def load_dataset(self, split: int): haiku = DatasetDict() with open('./data/manual/ct0_data/haiku/haiku/do_nothin...
def squeeze_if_one(arr): if (arr.shape[(- 1)] == 1): return np.squeeze(arr, axis=(- 1)) else: return arr
def exp_param_defaults(exp_params): defaults = dict(subset_algos=False, error_metric=None, compute_quantum_fixed=False, score_dir=None, slowdown_factor=1, plot=False, movie=False, use_db=False, strategy='stack-meta', super_fast_subset=1000, super_fast_timeout=np.inf, one_shot_timeout=0.333, anytime_timeout=1, use_d...
class SumOfLosses(Loss): def __init__(self, l1, l2): name = '{} + {}'.format(l1.__name__, l2.__name__) super().__init__(name=name) self.l1 = l1 self.l2 = l2 def __call__(self, *inputs): return (self.l1.forward(*inputs) + self.l2.forward(*inputs))
class PCQM4MEvaluator(): def __init__(self): pass def eval(self, input_dict): assert ('y_pred' in input_dict) assert ('y_true' in input_dict) (y_pred, y_true) = (input_dict['y_pred'], input_dict['y_true']) assert ((isinstance(y_true, np.ndarray) and isinstance(y_pred, np....
def init_randomizer(base_seed=1234): global _MDPRInstance assert (_MDPRInstance is None), 'Repeatedly initializing multiple dimension parallel randomizer.' _MDPRInstance = MultiDimParallelRandomizer(base_seed)
def get_fcn8sd(backbone, num_classes, aux=False, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs): net = FCN8sd(backbone=backbone, num_classes=num_classes, aux=aux, **kwargs) if pretrained: if ((model_name is None) or (not model_name)): raise ValueErro...
class NautilusBound(): def compute(cls, points, log_l, log_l_min, log_v_target, enlarge_per_dim=1.1, n_points_min=None, split_threshold=100, n_networks=4, neural_network_kwargs={}, pool=None, rng=None): bound = cls() bound.n_dim = points.shape[1] bound.neural_bounds = [] multi_ellips...
class TestCollectResults(unittest.TestCase): def test_format_mean(self): self.assertEqual(collect_results.format_mean([0.1, 0.2, 0.3], False)[2], '20.0 +/- 4.7') self.assertEqual(collect_results.format_mean([0.1, 0.2, 0.3], True)[2], '20.0 $\\pm$ 4.7') def test_print_table_non_latex(self): ...
def TranslateY(img, v, max_v, bias=0): v = (_float_parameter(v, max_v) + bias) if (random.random() < 0.5): v = (- v) v = int((v * img.size[1])) return img.transform(img.size, PIL.Image.AFFINE, (1, 0, 0, 0, 1, v))
class TestRecurrentEncoder(TensorTestCase): def setUp(self): self.emb_size = 10 self.num_layers = 3 self.hidden_size = 7 seed = 42 torch.manual_seed(seed) def test_recurrent_encoder_size(self): for bidirectional in [True, False]: directional_factor = (...
_model def res2net50_26w_4s(pretrained=False, num_classes=1000, in_chans=3, **kwargs): default_cfg = default_cfgs['res2net50_26w_4s'] res2net_block_args = dict(scale=4) model = ResNet(Bottle2neck, [3, 4, 6, 3], base_width=26, num_classes=num_classes, in_chans=in_chans, block_args=res2net_block_args, **kwarg...
def preprocess_for_train(image, labels, bboxes, xs, ys, out_shape, data_format='NHWC', scope='ssd_preprocessing_train'): fast_mode = False with tf.name_scope(scope, 'ssd_preprocessing_train', [image, labels, bboxes]): if (image.get_shape().ndims != 3): raise ValueError('Input must be of size...
def get_api_response(model, tokenizer, content: str, max_tokens=None): if ('en' == lang_opt): system_role_content = 'You are a helpful and creative assistant for writing novel.' elif ('zh1' == lang_opt): system_role_content = 'You are a helpful and creative assistant for writing novel. ...
class Derivative(PdeNode): def __init__(self, T: Union[(str, Symbol, float, int)], p: Union[(str, Symbol)], S: Union[(str, Symbol, float, int)]=0.0, dim=3, time=True): super().__init__() self.T = T self.S = S self.dim = dim self.time = time (x, y, z) = symbols('x y z'...
def list_python_files_in_repository(): source_code_files = [] for (path, subdirs, files) in os.walk('.'): if ('templates' in path): continue for name in files: if (('.py' in name) and ('.pyc' not in name)): path_to_files = os.path.join(path, name) ...
def _iterate_marked(cfg, config_mods): for (path, value) in iterate_flattened_separately(cfg, ['__doc__']): if (value is PATHCHANGE): (yield (path, PathEntry(key=path.rpartition('.')[2], added=(path in config_mods.added), modified=(path in config_mods.modified), typechanged=config_mods.typechang...
def main(_): if (not FLAGS.data_path): raise ValueError('Must set --data_path to PTB data directory') if (not os.path.exists(os.path.dirname(FLAGS.save_path))): try: os.makedirs(os.path.dirname(FLAGS.save_path)) except OSError as exc: if (exc.errno != errno.EEXIST...
def embed_all(inputs, count, size): out = [] with tf.variable_scope('embed_all') as scope: for inp in inputs: (t_emb, _) = net.embed(inp, count, size) t_pool = tf.reduce_mean(t_emb, axis=(- 2)) out.append(t_pool) scope.reuse_variables() return out
def common_arg_parser(): parser = arg_parser() parser.add_argument('--env', help='environment ID', type=str, default='Reacher-v2') parser.add_argument('--env_type', help='type of environment, used when the environment type cannot be automatically determined', type=str) parser.add_argument('--seed', help...
(autouse=True) def _requests_prevent_head(monkeypatch: MonkeyPatch, thrower: Callable, logging_side_effect: Callable) -> MagicMock: mock = MagicMock(side_effect=logging_side_effect(f'requests.head', after=thrower)) monkeypatch.setattr(requests, 'head', mock) return mock
def _aspect_preserving_resize(image, resize_min): shape = tf.shape(input=image) (height, width) = (shape[0], shape[1]) (new_height, new_width) = _smallest_size_at_least(height, width, resize_min) return tf.image.resize(image, [new_height, new_width], method=tf.image.ResizeMethod.BILINEAR)
class MeanAggregator(nn.Module): def __init__(self, features, cuda=False, gcn=False): super(MeanAggregator, self).__init__() self.features = features self.cuda = cuda self.gcn = gcn def forward(self, nodes, to_neighs, num_sample=10): _set = set if (not (num_sample...
(inp1=arrays(shape=(3, 10), dtype=np.float, elements=hypothesis.strategies.floats((- 1000), 1000)), inp2=arrays(shape=(3, 10), dtype=np.float, elements=hypothesis.strategies.floats((- 1000), 1000))) (max_examples=500) def test_logsumexp2_numerical_stability(inp1, inp2): t1_ = tf.constant(inp1) t2_ = tf.constant...
.parametrize('metric_name, sklearn_metric, torch_metric', [('MulticlassAccuracy', accuracy_score, Accuracy(task='multiclass', num_classes=3, average='micro')), ('MulticlassPrecision', precision_score, Precision(task='multiclass', num_classes=3, average='macro')), ('MulticlassRecall', recall_score, Recall(task='multicla...
def make_dir(dirname): try: os.makedirs(dirname) except OSError as exc: if (exc.errno == errno.EEXIST): pass else: raise Exception(('Unable to create directory: ' + dirname))
def get_each_ood_task_log_path(args): if args['test']: save_dir = os.path.join((args['OOD_each_task_result_output_dir'] + '_test'), os.path.basename(args['checkpoint']), args['ID_name']) else: save_dir = os.path.join((args['OOD_each_task_result_output_dir'] + '_full'), os.path.basename(args['che...
class GPT2Tokenizer(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, error...
class KeepName(): def __init__(self, transform): self.transform = transform def __call__(self, file_name): return (file_name, self.transform(file_name))
def _get_image_size(img): if TF._is_pil_image(img): return img.size elif (isinstance(img, torch.Tensor) and (img.dim() > 2)): return img.shape[(- 2):][::(- 1)] else: raise TypeError('Unexpected type {}'.format(type(img)))
def sample(things: List, sample_size: int=None) -> List: random_sample_size = len(things) if (sample_size is not None): random_sample_size = min(sample_size, len(things)) if (random_sample_size == len(things)): sample_images = things else: sample_images = random.sample(things, ra...
class Observation(NamedTuple): coordinates: chex.Array position: chex.Numeric trajectory: chex.Array action_mask: chex.Array
class HermitianFilter(Filter): def __init__(self, N, K, eta, mu, dt=1.0): Filter.__init__(self, N, dt=dt) for param in [K, eta, mu]: if ((np.size(param) != 1) and (np.size(param) != N)): raise ValueError('Parameters should be either scalar or of size N') if (np.si...
class FFN(nn.Module): def __init__(self, embed_dims, feedforward_channels, num_fcs=2, act_cfg=dict(type='ReLU', inplace=True), dropout=0.0, add_residual=True): super(FFN, self).__init__() assert (num_fcs >= 2), f'num_fcs should be no less than 2. got {num_fcs}.' self.embed_dims = embed_dims ...
class CompositeAudioWaveformTransform(CompositeAudioTransform): def from_config_dict(cls, config=None): return super()._from_config_dict(cls, 'waveform', get_audio_waveform_transform, CompositeAudioWaveformTransform, config) def __call__(self, x, sample_rate): for t in self.transforms: ...
class StreamingPlot(): def __init__(self, plot_title: str='Pareto front approximation', reference_front: List[S]=None, reference_point: list=None, axis_labels: list=None): self.plot_title = plot_title self.axis_labels = axis_labels if (reference_point and (not isinstance(reference_point[0], ...
class UNet(nn.Module): def __init__(self, n_channels, n_classes, bilinear=True): super(UNet, self).__init__() self.n_channels = n_channels self.n_classes = n_classes self.bilinear = bilinear self.inc = DoubleConv(n_channels, 64) self.down1 = Down(64, 128) self...
class TestFileIO(unittest.TestCase): _tmpdir: Optional[str] = None _tmpfile: Optional[str] = None _tmpfile_contents = 'Hello, World' def setUpClass(cls) -> None: cls._tmpdir = tempfile.mkdtemp() with open(os.path.join(cls._tmpdir, 'test.txt'), 'w') as f: cls._tmpfile = f.name...
def _fuse_mha(graph: Graph): pattern = {'patterns': {'in': [[(0, 'Matmul'), (1, 'Softmax'), (2, 'Matmul')]], 'out': [[(0, 'MultiHeadAttention')]]}, 'search_mode': 'op_type', 'node_names': {0: 0}, 'input_tensors': {0: [[{0: [0]}], [[0], 1]]}, 'output_tensors': {0: [[{2: [0]}, {2: [1]}, {2: [2]}], [[0, 1, 2], 3]]}, '...
def train_all_epochs(opt, model, optimizer, train_sampler, train_loader, criterion, val_loader, num_train_samples=None, no_acc_eval=False, save_all_ranks=False, training_status_info=None, save_params=True): timer_start = time.time() if (training_status_info is None): training_status_info = {} tr...
class AutoModelForAudioClassification(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def create_exp_dir(dir_path, scripts_to_save=None, debug=False): if debug: print('Debug Mode : no experiment dir created') return functools.partial(logging, log_path=None, log_=False) if (not os.path.exists(dir_path)): os.makedirs(dir_path) print('Experiment dir : {}'.format(dir_path...
def test_convnext_learning_rate_decay_optimizer_constructor(): model = ConvNeXtExampleModel() optimizer_cfg = dict(type='AdamW', lr=base_lr, betas=(0.9, 0.999), weight_decay=0.05) stagewise_paramwise_cfg = dict(decay_rate=decay_rate, decay_type='stage_wise', num_layers=6) optim_constructor = LearningRat...
def activ_dispatch(activ, norm=None): return {'none': nn.Identity, 'relu': nn.ReLU, 'lrelu': partial(nn.LeakyReLU, negative_slope=0.2)}[activ.lower()]
def get_sources_from_sys_modules(globs, base_path): return get_sources_from_modules(iterate_sys_modules(), base_path)
def assemble_circuits(circuits, run_config, qobj_id, qobj_header): qobj_config = QasmQobjConfig() if run_config: qobj_config = QasmQobjConfig(**run_config.to_dict()) experiments = [] max_n_qubits = 0 max_memory_slots = 0 for circuit in circuits: n_qubits = 0 memory_slots ...
class CEGAT(MessagePassing): def __init__(self, in_dim, hid_dim, out_dim, num_layers, heads, output_heads, dropout, Normalization='bn'): super(CEGAT, self).__init__() self.convs = nn.ModuleList() self.normalizations = nn.ModuleList() if (Normalization == 'bn'): self.convs...
class FlaxFeedForward(nn.Module): dim: int dropout: float = 0.0 dtype: jnp.dtype = jnp.float32 def setup(self): self.net_0 = FlaxGEGLU(self.dim, self.dropout, self.dtype) self.net_2 = nn.Dense(self.dim, dtype=self.dtype) def __call__(self, hidden_states, deterministic=True): ...
def check_plot_figsize(figsize): if (not isinstance(figsize, tuple)): raise TypeError((f"'figsize' must be a tuple with 2 elements, got {type(figsize)}." + PLOT_FIGSIZE_INFO)) if (len(figsize) != 2): raise ValueError((f"'figsize' must be a tuple with 2 elements, got {len(figsize)} elements." + P...
class Total_Yngve_Depth(object): def __init__(self, sentence_objs): self.sentence_objs = sentence_objs def handle(self): total_all_yngve_depth = 0 for so in self.sentence_objs: total_all_yngve_depth += total_yngve_depth(so.yngve_tree_root) num_sentences = len(self.sen...
class Mixed(torch.nn.Module): def __init__(self, in_channels, out_channels): super(Mixed, self).__init__() self.branch_0 = Unit3Dpy(in_channels, out_channels[0], kernel_size=(1, 1, 1)) branch_1_conv1 = Unit3Dpy(in_channels, out_channels[1], kernel_size=(1, 1, 1)) branch_1_conv2 = Uni...
def get_auto_estimator(backend='torch'): loss = ('mse' if backend.startswith('keras') else torch.nn.MSELoss()) auto_tcn = AutoTCN(input_feature_num=input_feature_dim, output_target_num=output_feature_dim, past_seq_len=past_seq_len, future_seq_len=future_seq_len, optimizer='Adam', loss=loss, metric='mse', backen...
def plot_roc(thr_unc_lst, thr_pred_lst, res_dct, metric, fname_out): plt.figure(figsize=(10, 10)) for (i_unc, thr_unc) in enumerate(thr_unc_lst): logger.info(f'Unc Thr: {thr_unc}') tpr_vals = np.array([np.nanmean(res_dct['tpr'][i_unc][i_pred]) for i_pred in range(len(thr_pred_lst))]) fdr...
_request def s3_get(url, temp_file): import boto3 s3_resource = boto3.resource('s3') (bucket_name, s3_path) = split_s3_path(url) s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
class Track(): def __init__(self, mean, covariance, track_id, n_init, max_age, feature=None): self.mean = mean self.covariance = covariance self.track_id = track_id self.hits = 1 self.age = 1 self.time_since_update = 0 self.state = TrackState.Tentative ...
_registry(dataset_type='ImageRecord', framework='tensorflow, tensorflow_itex', dataset_format='') class TensorflowImageRecord(IterableDataset): def __new__(cls, root, transform=None, filter=None): from tensorflow.python.platform import gfile glob_pattern = os.path.join(root, '*-*-of-*') file...
class LabeledExamplePlotter(): def __init__(self, example: LabeledExample): self.example = example def _plot_audio(self, audio: ndarray) -> None: plt.title(str(self)) plt.xlabel('time / samples (sample rate {}Hz)'.format(self.example.sample_rate)) plt.ylabel('y') plt.plot...
def loss_unsup_data(im1_0, im2_0, flow_f5, flow_f4, flow_f3, flow_f2, flow_f1, flow_f0, flow_b5, flow_b4, flow_b3, flow_b2, flow_b1, flow_b0, cbn, vmap_f, vmap_b, w5, w4, w3, w2, w1, occt): im1_1 = gaussian_smooth.gauss_conv(im1_0, size=5, nsig=3, name='pyr1_1') im2_1 = gaussian_smooth.gauss_conv(im2_0, size=5,...
def image_stats(image, mask=None): (l, a, b) = cv2.split(image) if (mask is not None): (l, a, b) = (l.reshape((- 1)), a.reshape((- 1)), b.reshape((- 1))) mask = mask.reshape((- 1)) (l, a, b) = (l[mask], a[mask], b[mask]) (lMean, lStd) = (l.mean(), l.std()) (aMean, aStd) = (a.mean...
def prepare_dataset(sentences, word_to_id, char_to_id, tag_to_id, ctc_pred_dict, lower=True): def f(x): return (x.lower() if lower else x) data = [] hands = hand_features_to_idx(sentences) for (i, s) in enumerate(sentences): str_words = [w[0] for w in s] words = [word_to_id[(f(w)...
class PairwiseRankingLoss(nn.Module): def __init__(self, margin): super(PairwiseRankingLoss, self).__init__() self.margin = margin def forward(self, anchor1, anchor2, img_sentc, sent_imgc): cost_sent = torch.clamp(((self.margin - anchor1) + img_sentc), min=0.0).sum() cost_img = t...
class RandomVerticalFlip(object): def __call__(self, img): if (random.random() < 0.5): return F.vflip(img) return img
class BasicGRUCell(tf.contrib.rnn.RNNCell): def __init__(self, num_units, activation=tf.tanh, layer_norm=False): self._num_units = num_units self._activation = activation self._layer_norm = layer_norm def state_size(self): return self._num_units def output_size(self): ...
class Conv2d(AbstractFourierBasis): def __init__(self, kernel: kernels.Conv2d, num_bases: int, filters: tf.Tensor=None, biases: tf.Tensor=None, name: str=None): super().__init__(name=name, kernel=kernel, num_bases=num_bases) self._filters = filters self._biases = biases def __call__(self...
def main(): (args, args_dict) = parse_input(eval=False) log_device(args) model = get_model(args) model.cuda(args.c_cudaid) model = DDP(model, device_ids=[args.c_cudaid]) best_state_dict = deepcopy(model.state_dict()) (optimizer, lr_scheduler) = get_optimizer(args, model) loss = get_loss(...
def convert_result_list(outputs): if isinstance(outputs, torch.Tensor): return [outputs] ret = [] for sub in outputs: ret += convert_result_list(sub) return ret
def base_lm_architecture(args): if hasattr(args, 'decoder_final_norm'): args.no_decoder_final_norm = (not args.decoder_final_norm) args.dropout = getattr(args, 'dropout', 0.1) args.attention_dropout = getattr(args, 'attention_dropout', 0.0) args.decoder_embed_dim = getattr(args, 'decoder_embed_d...
def process_line(line): (image_name, label) = line.strip().split(' ') label = int(label) return (image_name, label)
class BasicBlock(nn.Module): def __init__(self, in_planes, out_planes, stride, droprate=0.0): super(BasicBlock, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.relu1 = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding...
class QuantizeWrapper(QuantizeWrapperBase): def __init__(self, layer, **kwargs): super().__init__(layer, **kwargs) self.kernel = 'kernel' self.kernel_weights = None self.channel_axis = kwargs.get('axis', (- 1)) if (self._layer_class == 'DepthwiseConv2D'): self.ker...
class MLP(nn.Module): def __init__(self, in_channels, hidden_channels, out_channels, num_layers, dropout=0.5, is_bns=True): super(MLP, self).__init__() self.lins = nn.ModuleList() self.is_bns = is_bns if is_bns: self.bns = nn.ModuleList() if (num_layers == 1): ...
def build_train_meta(args): train_meta_root = os.path.join(args.saving_dir, 'meta') content_font_name = os.path.basename(args.content_font) save_path = os.path.join(train_meta_root, 'train.json') meta_file = os.path.join(train_meta_root, 'trainset_dict.json') with open(meta_file, 'r') as f_in: ...
def collect_trajectory(agent, reward): if (reward < 0): agent.replay_buffer.clear() elif (reward > 0): agent.replay_buffer.add(agent._last_observation, agent.action, reward, False) while (agent.replay_buffer.size() > 0): experience = agent.replay_buffer.get_sample() ...
def rotate(molecule, angle, axis, fix_com=False): c = molecule.GetConformers()[0] d = np.array(c.GetPositions()) ori_mean = np.mean(d, 0, keepdims=True) if fix_com: d = (d - ori_mean) atoms = [] for i in range(len(d)): atoms.append(Atom('C', d[i])) atoms = Atoms(atoms) at...
class GateConfigSchema(BaseSchema): name = String(required=True) parameters = List(String(), required=True) qasm_def = String(required=True) coupling_map = List(List(Integer(), validate=Length(min=1)), validate=Length(min=1)) latency_map = List(List(Integer(validate=OneOf([0, 1])), validate=Length(m...
class CompositeTask(abstract_task.AbstractTask): def __init__(self, *tasks, timeout_steps=np.inf): self._tasks = tasks self._timeout_steps = timeout_steps def reset(self, state, meta_state): for task in self._tasks: task.reset(state, meta_state) def reward(self, state, me...