code
stringlengths
101
5.91M
class ThresholdParameter(message.Message): __metaclass__ = reflection.GeneratedProtocolMessageType DESCRIPTOR = _THRESHOLDPARAMETER
(version='2.0') class TensorflowModelZooBertDataLoader(DefaultDataLoader): def _generate_dataloader(self, dataset, batch_size, last_batch, collate_fn, sampler, batch_sampler, num_workers, pin_memory, shuffle, distributed): if shuffle: logging.warning('Shuffle is not supported yet in TensorflowBe...
class ResNeXtUnit(nn.Module): def __init__(self, in_channels, out_channels, stride, cardinality, bottleneck_width): super(ResNeXtUnit, self).__init__() self.resize_identity = ((in_channels != out_channels) or (stride != 1)) self.body = ResNeXtBottleneck(in_channels=in_channels, out_channels=...
def restore_all_mat_props() -> None: for (mat_name, mat_props) in _SAVED_MATERIALS.items(): set_mat_props(mat_name, mat_props)
class MatrixTypeNode(ExprNode): def __init__(self, parse_info=None, raw_text=None): super().__init__(IRNodeType.MatrixType, parse_info=parse_info, raw_text=raw_text) self.id1 = None self.id2 = None self.type = None
class KerasONNXRuntimeINCMetic(ONNXRuntimeINCMetic): def stack(self, preds, labels): (preds, labels) = super().stack(preds, labels) preds = tf.convert_to_tensor(preds) labels = tf.convert_to_tensor(labels) return (preds, labels) def to_scalar(self, tensor): return float(t...
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer, pattern, if_all): if label_list: label_map = {label: i for (i, label) in enumerate(label_list)} else: label_map = None max_len_count = 0 features = [] tokenslist = [] if (((pattern['max_combined_att...
class _3DUNET_PyTorch_SUT(): def __init__(self, model, preprocessed_data_dir, performance_count, folds, checkpoint_name): print('Loading PyTorch model...') self.model = model self.device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu')) print('Constructing SUT...') ...
def eval_func_onnx(model, dataloader, metric, postprocess=None): metric.reset() sess = ort.InferenceSession(model.SerializeToString(), providers=ort.get_available_providers()) input_names = [i.name for i in sess.get_inputs()] for (input_data, label) in dataloader: output = sess.run(None, dict(zi...
_processor('blip_question') class BlipQuestionProcessor(BaseProcessor): def __init__(self, max_words=50): self.max_words = max_words def __call__(self, question): return self.pre_question(question) def from_config(cls, cfg=None): if (cfg is None): cfg = OmegaConf.create()...
def main(): parser = argparse.ArgumentParser() parser.add_argument('network') parser.add_argument('network_trainer') parser.add_argument('task', help='can be task name or task id') parser.add_argument('fold', help="0, 1, ..., 5 or 'all'") parser.add_argument('-val', '--validation_only', help='us...
def hard_intersection(left: TBoxTensor, right: TBoxTensor) -> TBoxTensor: t1 = left t2 = right z = torch.max(t1.z, t2.z) Z = torch.min(t1.Z, t2.Z) return left.from_zZ(z, Z)
def collate_wrapper(x, y, edge_index, edge_attr, device, return_y=True): x = torch.tensor(x, dtype=torch.float, device=device) y = torch.tensor(y, dtype=torch.float, device=device) x = x.transpose(dim0=1, dim1=0) y_T_first = y.transpose(dim0=1, dim1=0) T = x.size()[0] N = x.size()[1] sequenc...
class Dictionary(object): def __init__(self, save_dir): self.idx2token = {} self.token2idx = {} self.word_freq = {} self.special = [] self.save_dir = save_dir def save(self, save_dir=None): if (not (save_dir is None)): self.save_dir = save_dir ...
def cdeint_gde(dX_dt, z0, func_f, func_g, t, adjoint=True, **kwargs): control_gradient = dX_dt(torch.zeros(1, dtype=z0.dtype, device=z0.device)) if (control_gradient.shape[:(- 1)] != z0.shape[:(- 1)]): raise ValueError('dX_dt did not return a tensor with the same number of batch dimensions as z0. dX_dt ...
class MultiInputSequential(nn.Sequential): def forward(self, *input): multi_inp = False if (len(input) > 1): multi_inp = True (_, edge_index) = (input[0], input[1]) for module in self._modules.values(): if multi_inp: if hasattr(module, 'wei...
def read_labeled(file): labeled_edges = {} sent_id = None sent_edges = [] for line in open(file): if line.startswith('# sent_id'): sent_id = line.strip().split(' = ')[(- 1)] if ((line.strip() == '') and (sent_id is not None)): labeled_edges[sent_id] = sent_edges ...
def convert_stockholm_to_a3m(stockholm_format: str, max_sequences: Optional[int]=None) -> str: descriptions = {} sequences = {} reached_max_sequences = False for line in stockholm_format.splitlines(): reached_max_sequences = (max_sequences and (len(sequences) >= max_sequences)) if (line....
def canon_input_planes(fen): fen = maybe_flip_fen(fen, is_black_turn(fen)) return all_input_planes(fen)
class TestTransformerDecoder(TensorTestCase): def setUp(self): self.emb_size = 12 self.num_layers = 3 self.hidden_size = 12 self.ff_size = 24 self.num_heads = 4 self.dropout = 0.0 seed = 42 torch.manual_seed(seed) def test_transformer_decoder_freez...
def _linear(args, output_size, bias, bias_initializer=tf.zeros_initializer(), scope=None, kernel_initializer=initializer(), reuse=None): if ((args is None) or (nest.is_sequence(args) and (not args))): raise ValueError('`args` must be specified') if (not nest.is_sequence(args)): args = [args] ...
class TestOptions(BaseOptions): def initialize(self, parser): BaseOptions.initialize(self, parser) parser.add_argument('--results_dir', type=str, default='./results/', help='saves results here.') parser.add_argument('--which_epoch', type=str, default='latest', help='which epoch to load? set ...
def get_labels(input_shape, xs): label = [0, 0] if (input_shape == (1,)): ys = (0 if (np.sin(xs) <= 0) else 1) label[ys] = 1 elif (input_shape == (2,)): ys = (int(np.round(xs[0])) ^ int(np.round(xs[1]))) label[ys] = 1 return label
def build_dataloader(dataset, imgs_per_gpu, workers_per_gpu, num_gpus=1, dist=True, shuffle=True, seed=None, **kwargs): (rank, world_size) = get_dist_info() if dist: if shuffle: sampler = DistributedGroupSampler(dataset, imgs_per_gpu, world_size, rank) else: sampler = Dis...
def override(interface_class): def overrider(method): invalidInputError((method.__name__ in dir(interface_class)), "method.__name__ doesn't exist in interface_class") return method return overrider
def Float2BFloat16Bytes(float_data): int_datas = [] for value in float_data: bytes = struct.pack('f', value) int_data = struct.unpack('i', bytes)[0] int_datas.append((int_data >> 16)) return np.array(int_datas).astype(np.uint16).tobytes()
def get_net(cfg: dict) -> nn.ModuleDict: reg.trigger_nets() reg.trigger_decoders() nets = {k: get_cls(reg.NET_REG, type=k, **kw) for (k, kw) in cfg.items() if (kw is not None)} return nn.ModuleDict(OrderedDict(nets))
class Sample(object): def __init__(self): self.itemSeq = [] self.target = [] self.action = [] self.reward = [] self.clicked = {} def genSample_pred(self, item, reward, action, warmup, real_num_label, rec_len, add_end=True): length = len(item) for j in rang...
class DynamicsTest(test_util.JAXMDTestCase): _parameters(test_util.cases_from_list(({'testcase_name': '_dim={}_dtype={}'.format(dim, dtype.__name__), 'spatial_dimension': dim, 'dtype': dtype} for dim in SPATIAL_DIMENSION for dtype in DTYPE))) def test_gradient_descent(self, spatial_dimension, dtype): ke...
def _gen_missing_api(api, mod_name): def _missing_api(*args, **kwargs): raise ImportError(('API "%s" is not supported by backend "%s". You can switch to other backends by setting the DDE_BACKEND environment.' % (api, mod_name))) return _missing_api
class TestBuilder(unittest.TestCase): SHAPE_LARGE = (100, 100, 3) SHAPE_SMALL = (15, 15, 3) _conv_args = dict(kernel_size=3, padding='same', activation='relu') def _get_attention(self): return Sequential([Conv2D(8, input_shape=self.SHAPE_SMALL, **self._conv_args), MaxPool2D(), Conv2D(8, **self._...
class LossStatistics(): def __init__(self, loss=0.0, n_tokens=0, n_batch=0, forward_time=0.0, loss_compute_time=0.0, backward_time=0.0): self.loss = loss if math.isnan(loss): raise ValueError('Loss is NaN') self.n_tokens = n_tokens self.n_batch = n_batch self.forw...
def format_attention(attention, layers=None, heads=None): if layers: attention = [attention[layer_index] for layer_index in layers] squeezed = [] for layer_attention in attention: if (len(layer_attention.shape) != 4): raise ValueError('The attention tensor does not have the corre...
def random_split(valid_pct: float, *arrs: NPArrayableList) -> SplitArrayList: assert ((valid_pct >= 0) and (valid_pct <= 1)), 'Validation set percentage should be between 0 and 1' is_train = (np.random.uniform(size=(len(arrs[0]),)) > valid_pct) return arrays_split(is_train, *arrs)
def ensure_optimizer_ckpt_params_order(param_groups_names, checkpoint): assert (len(param_groups_names) == len(checkpoint['optimizer']['param_groups'])) param_lens = (len(g) for g in param_groups_names) saved_lens = (len(g['params']) for g in checkpoint['optimizer']['param_groups']) if any(((p_len != s_...
def test_print_log_silent(capsys, caplog): print_log('welcome', logger='silent') (out, _) = capsys.readouterr() assert (out == '') assert (len(caplog.records) == 0)
def linear_quantize(input, scale, zero_point, inplace=False): if (len(input.shape) == 4): scale = scale.view((- 1), 1, 1, 1) zero_point = zero_point.view((- 1), 1, 1, 1) elif (len(input.shape) == 2): scale = scale.view((- 1), 1) zero_point = zero_point.view((- 1), 1) if inpla...
def train(train_loader, val_loader, trainval_loader, tracking_module, lr_scheduler, start_iter, tb_logger): global best_mota batch_time = AverageMeter(config.print_freq) data_time = AverageMeter(config.print_freq) losses = AverageMeter(config.print_freq) tracking_module.model.train() logger = lo...
def get_credentials(): credentials = tools.get_credentials_file() session_credentials = get_session_credentials() for credentials_key in credentials: session_value = session_credentials.get(credentials_key) if ((session_value is False) or session_value): credentials[credentials_k...
class vgg_ex(nn.Module): def __init__(self, cfg, incs=512, padding=1, dilation=1): super(vgg_ex, self).__init__() self.cfg = cfg layers = [] for v in self.cfg: conv2d = nn.Conv2d(incs, v, kernel_size=3, padding=padding, dilation=dilation, bias=False) layers +=...
def set_graph_training(graph, train=True): for e in graph.edges: module = graph.edges[e]['module'] if isinstance(module, Segment): set_graph_training(module.G, train=train) elif train: graph.edges[e]['module'].train() else: graph.edges[e]['module']...
class WideResNet(nn.Module): def __init__(self, depth=34, num_classes=10, widen_factor=10, dropRate=0.0): super(WideResNet, self).__init__() nChannels = [16, (16 * widen_factor), (32 * widen_factor), (64 * widen_factor)] assert (((depth - 4) % 6) == 0) n = ((depth - 4) / 6) b...
def convert_imagenet_to_tf_records(raw_data_dir: str, output_dir: str) -> None: import tensorflow as tf random.seed(0) def make_shuffle_idx(n): order = list(range(n)) random.shuffle(order) return order training_files = tf.gfile.Glob(os.path.join(raw_data_dir, TRAINING_DIRECTORY, ...
def test_dyhead(): s = 64 in_channels = 8 out_channels = 16 feat_sizes = [(s // (2 ** i)) for i in range(4)] feats = [torch.rand(1, in_channels, feat_sizes[i], feat_sizes[i]) for i in range(len(feat_sizes))] neck = DyHead(in_channels=in_channels, out_channels=out_channels, num_blocks=3) outs...
class RiRUnit(nn.Module): def __init__(self, in_channels, out_channels, stride): super(RiRUnit, self).__init__() self.resize_identity = ((in_channels != out_channels) or (stride != 1)) self.res_pass_conv = conv3x3(in_channels=in_channels, out_channels=out_channels, stride=stride) sel...
def build(post_processing_config): if (not isinstance(post_processing_config, post_processing_pb2.PostProcessing)): raise ValueError('post_processing_config not of type post_processing_pb2.Postprocessing.') non_max_suppressor_fn = _build_non_max_suppressor(post_processing_config.batch_non_max_suppressio...
def preprocess_save_to_queue(preprocess_fn, q, list_of_lists, output_files, segs_from_prev_stage, classes, transpose_forward): errors_in = [] for (i, l) in enumerate(list_of_lists): try: output_file = output_files[i] print('preprocessing', output_file) (d, _, dct) = p...
def get_pkg_version(frontend_pkg): try: import importlib.metadata return importlib.metadata.version(frontend_pkg) except ModuleNotFoundError: pass import pkg_resources try: return pkg_resources.get_distribution(frontend_pkg).version except pkg_resources.DistributionNo...
class XLMProphetNetTokenizer(metaclass=DummyObject): _backends = ['sentencepiece'] def __init__(self, *args, **kwargs): requires_backends(self, ['sentencepiece'])
class MetaBatchNorm2d(MetaModule): def __init__(self, *args, **kwargs): super().__init__() ignore = nn.BatchNorm2d(*args, **kwargs) self.num_features = ignore.num_features self.eps = ignore.eps self.momentum = ignore.momentum self.affine = ignore.affine self.t...
def dobldobl_clear(): from phcpy.phcpy2c3 import py2c_numbtrop_dobldobl_clear py2c_numbtrop_dobldobl_clear()
def get_video_to_frame_path_fn(fn_type: str='idx', zeros: int=8, incr: int=1) -> Callable: if (fn_type == 'idx'): def fn(video_path, frame_idx): return f'{video_path}/{(frame_idx + incr):0{zeros}d}.jpg' return fn else: raise NotImplementedError(f'{fn_type} unknown.')
class CLIPImageDataset(torch.utils.data.Dataset): def __init__(self, data): self.data = data self.preprocess = self._transform_test(224) def _transform_test(self, n_px): return Compose([Resize(n_px, interpolation=Image.BICUBIC), CenterCrop(n_px), (lambda image: image.convert('RGB')), ToT...
_type def gaussian_noise(image, stddev_max=0.1): stddev = tf.random.uniform([], 0.0, stddev_max) noise = tf.random.normal(shape=tf.shape(image), mean=0, stddev=stddev) image = (image + noise) return image
class Mixed3a(nn.Module): def __init__(self): super(Mixed3a, self).__init__() self.maxpool = nn.MaxPool2d(3, stride=2) self.conv = BasicConv2d(64, 96, kernel_size=3, stride=2) def forward(self, x): x0 = self.maxpool(x) x1 = self.conv(x) out = torch.cat((x0, x1), 1...
class SPAdaIN(nn.Module): def __init__(self, norm, input_nc, planes): super(SPAdaIN, self).__init__() self.conv_weight = nn.Conv1d(input_nc, planes, 1) self.conv_bias = nn.Conv1d(input_nc, planes, 1) self.norm = norm(planes) def forward(self, x, addition): x = self.norm(x...
class DataLoader(): def load_data_oss(file_paths): all_problem_solutions = [] for file_path in file_paths: with open(file_path, 'r') as file: for line in file: line = line.strip() if (not line): continue ...
def main(folder, version): folder_name = os.path.basename(folder) for index_file in glob.glob('{}/**/*.html'.format(folder), recursive=True): update_version_link(version, folder_name, index_file) update_source_url(version, folder_name, index_file)
class HessianVectorProduct(abc.ABC): def __init__(self, num_slices=1): self._target = None self._reg_coeff = None self._hvp_fun = None self._num_slices = num_slices def update_hvp(self, f, target, inputs, reg_coeff, name=None): def build_eval(self, inputs): def _eval(...
def quaddobl_clear(): from phcpy.phcpy2c3 import py2c_numbtrop_quaddobl_clear py2c_numbtrop_quaddobl_clear()
class DisparitySampleRangeHead(nn.Module): def __init__(self, max_disp): super(DisparitySampleRangeHead, self).__init__() self.max_disp = max_disp def forward(self, stage, disparity_sample_number, left, min_disparity=None, max_disparity=None): device = left.device (B, _, H, W) = ...
def python_3000_raise_comma(logical_line): match = RAISE_COMMA_REGEX.match(logical_line) if (match and (not RERAISE_COMMA_REGEX.match(logical_line))): (yield ((match.end() - 1), 'W602 deprecated form of raising exception'))
def _numpy_inference(model, input_sample_list, batch_size): if (batch_size is None): return model(*input_sample_list) else: yhat_list = [] sample_num = input_sample_list[0].shape[0] if (sample_num <= batch_size): return model(*input_sample_list) else: ...
.parametrize('stability_threshold', [0.1, 0.01]) .parametrize('x_lim', [(0, 0.6), ((- 0.2), 0.8)]) .parametrize('which_energy', ['true', 'pred']) .parametrize('backend', ['plotly', 'matplotlib']) def test_hist_classified_stable_vs_hull_dist(stability_threshold: float, x_lim: tuple[(float, float)], which_energy: Literal...
class BertLMHeadModel(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
def get_optimizer(p, model, cluster_head_only=False): if cluster_head_only: for (name, param) in model.named_parameters(): if ('cluster_head' in name): param.requires_grad = True else: param.requires_grad = False params = list(filter((lambda p:...
class VLBartCOCOCaption(VLBart): def __init__(self, config): super().__init__(config) def train_step(self, batch): device = next(self.parameters()).device vis_feats = batch['vis_feats'].to(device) input_ids = batch['input_ids'].to(device) vis_pos = batch['boxes'].to(devic...
class TrainFromScratch(Algorithm): def __init__(self, **kwargs): super().__init__(**kwargs) self.trainable = False self.baselearner = self.baselearner_fn(**self.baselearner_args).to(self.dev) self.model = self.baselearner_fn(**self.baselearner_args).to(self.dev) def evaluate(self...
def set_exec_mode(line_: str) -> None: usage = f'Usage: %flow mode [{ExecutionMode.NORMAL}|{ExecutionMode.REACTIVE}]' try: exec_mode = ExecutionMode(line_.strip()) except ValueError: warn(usage) return flow_ = flow() flow_.mut_settings.exec_mode = exec_mode if (exec_mode ...
def get_indent(line: str) -> str: search = _re_indent.search(line) return ('' if (search is None) else search.groups()[0])
class StreamToLogger(object): def __init__(self, logger, log_level=logging.INFO): self.terminal = sys.stdout self.logger = logger self.log_level = log_level self.linebuf = '' def __getattr__(self, attr): return getattr(self.terminal, attr) def write(self, buf): ...
class Soft(nn.Module): def __init__(self): super(Soft, self).__init__() gaussian_kernel = np.float32(gkern(31, 4)) gaussian_kernel = gaussian_kernel[(np.newaxis, np.newaxis, ...)] self.gaussian_kernel = Parameter(torch.from_numpy(gaussian_kernel)) def forward(self, attention): ...
class TestLayerWithParam(unittest.TestCase): def setUp(self): net_file = python_param_net_file() self.net = caffe.Net(net_file, caffe.TRAIN) os.remove(net_file) def test_forward(self): x = 8 self.net.blobs['data'].data[...] = x self.net.forward() for y in ...
class InvertedDoublePendulumEnv(mujoco_env.MujocoEnv, utils.EzPickle): def __init__(self): mujoco_env.MujocoEnv.__init__(self, 'inverted_double_pendulum.xml', 5) utils.EzPickle.__init__(self) def step(self, action): self.do_simulation(action, self.frame_skip) ob = self._get_obs()...
class MultiScaleD(nn.Module): def __init__(self, channels, resolutions, num_discs=1, proj_type=2, cond=0, separable=False, patch=False, **kwargs): super().__init__() assert (num_discs in [1, 2, 3, 4]) self.disc_in_channels = channels[:num_discs] self.disc_in_res = resolutions[:num_di...
class FNetForPreTraining(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class HumanoidMimic(env.Env): def __init__(self, system_config, reference_traj, obs_type='timestamp', cyc_len=None, reward_scaling=1.0, rot_weight=1.0, vel_weight=0.0, ang_weight=0.0): super().__init__(config=get_system_cfg(system_config)) self.reference_qp = deserialize_qp(reference_traj) s...
def get_parser(): parser = argparse.ArgumentParser(description='writes text from binarized file to stdout') parser.add_argument('--dataset-impl', help='dataset implementation', choices=['raw', 'lazy', 'cached', 'mmap'], default='lazy') parser.add_argument('--dict', metavar='FP', help='dictionary containing ...
class Blip2QFormerModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def vggcam(nb_classes, input_shape=(3, None, None), num_input_channels=1024): model = Sequential() model.add(ZeroPadding2D((1, 1), input_shape=input_shape)) model.add(Convolution2D(64, 3, 3, activation='relu')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(64, 3, 3, activation='relu')) ...
def get_bigdl_conf(): jar_dir = os.path.abspath((__file__ + '/../../../')) conf_paths = glob.glob(os.path.join(jar_dir, 'share/*/conf/*.conf')) return conf_paths[0]
def objects365v2_classes() -> list: return ['Person', 'Sneakers', 'Chair', 'Other Shoes', 'Hat', 'Car', 'Lamp', 'Glasses', 'Bottle', 'Desk', 'Cup', 'Street Lights', 'Cabinet/shelf', 'Handbag/Satchel', 'Bracelet', 'Plate', 'Picture/Frame', 'Helmet', 'Book', 'Gloves', 'Storage box', 'Boat', 'Leather Shoes', 'Flower',...
class TFAutoModelForMaskedLM(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
class TFTapasForSequenceClassification(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def process_units(units, reduce=False): if (not reduce): return units out = [u for (i, u) in enumerate(units) if ((i == 0) or (u != units[(i - 1)]))] return out
class AlphaLayer(nn.Module): def __init__(self, channels, min_width, max_width, offset, prob_type='exp'): super(AlphaLayer, self).__init__() assert (prob_type in ['exp', 'sigmoid']) self.prob_type = prob_type self.channels = channels ch_indice = self._get_ch_indice(min_width,...
class NumpyArrayFormatterState(TemporalFeatureFormatterState): def to_tensor(self, features: np.ndarray) -> torch.Tensor: return torch.from_numpy(features) def to_internal_type(self, features: torch.Tensor) -> TemporalFeatures: return features.cpu().numpy()
class FullyConnectedLatentVariable(LatentVariable): def __init__(self, latent_config): super(FullyConnectedLatentVariable, self).__init__(latent_config) self._construct(latent_config) def _construct(self, latent_config): self.inference_procedure = latent_config['inference_procedure'] ...
def adverb_freq(s, tokens=None): if (tokens == None): tokens = word_tokenize(s) pos = pos_tag(tokens) adverbs = [] for [token, tag] in pos: part = map_tag('en-ptb', 'universal', tag) if (part == 'ADV'): adverbs.append(token) if (len(tokens) == 0): return f...
def important_spans(data, output, tgt_codes, pred_codes, s, dicts, filter_size, true_str, pred_str, spans_file, fps=False): (ind2w, ind2c, desc_dict) = (dicts['ind2w'], dicts['ind2c'], dicts['desc']) for p_code in pred_codes: if ((output[0][p_code] > 0.5) and (fps ^ (p_code in tgt_codes))): ...
class InputFeatures(object): def __init__(self, input_ids, input_mask, segment_ids, label_ids, boxes, actual_bboxes, file_name, page_size): assert (0 <= all(boxes) <= 1000), 'Error with input bbox ({}): the coordinate value is not between 0 and 1000'.format(boxes) self.input_ids = input_ids ...
class ConditionalEntropyAsyncProcess(GPUAsyncProcess): def __init__(self, *args, **kwargs): super(ConditionalEntropyAsyncProcess, self).__init__(*args, **kwargs) self.phase_bins = kwargs.get('phase_bins', 10) self.mag_bins = kwargs.get('mag_bins', 5) self.max_phi = kwargs.get('max_ph...
def _check_sha1(file_name, sha1_hash): sha1 = hashlib.sha1() with open(file_name, 'rb') as f: while True: data = f.read(1048576) if (not data): break sha1.update(data) return (sha1.hexdigest() == sha1_hash)
_torch _vision class LevitImageProcessingTest(ImageProcessingSavingTestMixin, unittest.TestCase): image_processing_class = (LevitImageProcessor if is_vision_available() else None) def setUp(self): self.image_processor_tester = LevitImageProcessingTester(self) def image_processor_dict(self): ...
class QuantizedData(object): def __init__(self): self._data = None self._scale = 0 self._zero = 0 self._minval = 0.0 self._maxval = 0.0 def data(self): return self._data def scale(self): return self._scale def zero(self): return self._zero ...
def main(): args = parser.parse_args() train_loader = loaddata.getTrainingData(args, args.batch_size) gmm_dict = fit_gmm(train_loader, args) gmm_path = 'gmm.pkl' joblib.dump(gmm_dict, gmm_path) print('Dumped at {}'.format(gmm_path))
class TextProcessor(): phonemes = (['<pad>', '<unk>'] + ['AA0', 'AA1', 'AA2', 'AE0', 'AE1', 'AE2', 'AH0', 'AH1', 'AH2', 'AO0', 'AO1', 'AO2', 'AW0', 'AW1', 'AW2', 'AY0', 'AY1', 'AY2', 'B', 'CH', 'D', 'DH', 'EH0', 'EH1', 'EH2', 'ER0', 'ER1', 'ER2', 'EY0', 'EY1', 'EY2', 'F', 'G', 'HH', 'IH0', 'IH1', 'IH2', 'IY0', 'IY1...
def train_one_epoch(model, optimizer, train_loader, model_func, lr_scheduler, accumulated_iter, optim_cfg, rank, tbar, total_it_each_epoch, dataloader_iter, tb_log=None, leave_pbar=False): if (total_it_each_epoch == len(train_loader)): dataloader_iter = iter(train_loader) if (rank == 0): pbar = ...
def add_suffix2name(ori_model, suffix='__', verify=False): special_ops = ('If', 'Loop') for node in ori_model.graph.node: if (node.op_type in special_ops): warnings.warn(f'This model has special op: {node.op_type}.') return ori_model model = copy.deepcopy(ori_model) def n...
class ListPop(ListRemove): def process_arg(self, pop_pos: int) -> None: self.remove_pos = pop_pos