code
stringlengths
17
6.64M
def compute_cls_reg_metrics(predictions, labels): predictions = np.array(predictions) labels = np.array(labels) correct = ((np.array(predictions) * np.array(labels)) > 0) positive = (np.array(labels) < 0) acc = correct.mean() recall = ((correct * positive).sum() / (positive.sum() + np.spacing(...
def gather_dict_keys_on_main(d): "\n each process has dictionary with different keys, gather all keys on main process\n e.g. P1: {'6ij6': ...}\n P2: {'4me3': ...}\n ret: P1: {'6ij6': ..., '4me3': ...}\n P2: None\n " ws = get_world_size() if (ws == 1): return d all_d...
def param_groups_weight_decay(model: nn.Module, weight_decay=1e-05, no_weight_decay_list=()): no_weight_decay_list = set(no_weight_decay_list) decay = [] no_decay = [] for (name, param) in model.named_parameters(): if (not param.requires_grad): continue if ((param.ndim <= 1...
def adjust_learning_rate(optimizer, epoch, args): 'Decay the learning rate with half-cycle cosine after warmup' if (epoch < args.warmup_epochs): lr = ((args.lr * epoch) / args.warmup_epochs) else: lr = (args.min_lr + (((args.lr - args.min_lr) * 0.5) * (1.0 + math.cos(((math.pi * (epoch - a...
class SmoothedValue(object): 'Track a series of values and provide access to smoothed values over a\n window or the global series average.\n ' def __init__(self, window_size=20, fmt=None): if (fmt is None): fmt = '{median:.4f} ({global_avg:.4f})' self.deque = deque(maxlen=wi...
class MetricLogger(object): def __init__(self, delimiter='\t'): self.meters = defaultdict(SmoothedValue) self.delimiter = delimiter def update(self, **kwargs): for (k, v) in kwargs.items(): if (v is None): continue if isinstance(v, torch.Tensor...
def setup_for_distributed(is_master): '\n This function disables printing when not in master process\n ' builtin_print = builtins.print def print(*args, **kwargs): force = kwargs.pop('force', False) force = (force or (get_world_size() > 8)) if (is_master or force): ...
def is_dist_avail_and_initialized(): if (not dist.is_available()): return False if (not dist.is_initialized()): return False return True
def get_world_size(): if (not is_dist_avail_and_initialized()): return 1 return dist.get_world_size()
def get_rank(): if (not is_dist_avail_and_initialized()): return 0 return dist.get_rank()
def is_main_process(): return (get_rank() == 0)
def save_on_master(*args, **kwargs): if is_main_process(): torch.save(*args, **kwargs)
def init_distributed_mode(args): if args.dist_on_itp: args.rank = int(os.environ['OMPI_COMM_WORLD_RANK']) args.world_size = int(os.environ['OMPI_COMM_WORLD_SIZE']) args.gpu = int(os.environ['OMPI_COMM_WORLD_LOCAL_RANK']) args.dist_url = ('tcp://%s:%s' % (os.environ['MASTER_ADDR'], ...
class NativeScalerWithGradNormCount(): state_dict_key = 'amp_scaler' def __init__(self): self._scaler = torch.cuda.amp.GradScaler() def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True): self._scaler.scale(loss).backward(create_graph=c...
def get_grad_norm_(parameters, norm_type: float=2.0) -> torch.Tensor: if isinstance(parameters, torch.Tensor): parameters = [parameters] parameters = [p for p in parameters if (p.grad is not None)] norm_type = float(norm_type) if (len(parameters) == 0): return torch.tensor(0.0) dev...
def save_model(args, epoch, model, model_without_ddp, optimizer, loss_scaler): output_dir = Path(args.output_dir) epoch_name = str(epoch) if True: checkpoint_paths = [(output_dir / ('checkpoint-%s.pth' % epoch_name))] for checkpoint_path in checkpoint_paths: to_save = {'model':...
def load_model(args, model_without_ddp, optimizer, loss_scaler): if (args.finetune and (not args.resume)): print(f'Loading finetune checkpoint from {args.finetune}') checkpoint = torch.load(args.finetune, map_location='cpu') if ('module.' in list(checkpoint['model'].keys())[0]): ...
def all_reduce_mean(x): world_size = get_world_size() if (world_size > 1): x_reduce = torch.tensor(x).cuda() dist.all_reduce(x_reduce) x_reduce /= world_size return x_reduce.item() else: return x
class MutateEverything(nn.Module): def __init__(self, args): super().__init__() self.args = args self.backbone = create_backbone(args) self.aa_expansion = create_aa_expander(args, self.backbone) self.single_decoder = create_single_decoder(args) self.multi_decoder =...
def mem_inputs_to_device(batch, device, args): if (args.backbone == 'af'): x = [{k: v.to(device, non_blocking=True) for (k, v) in x.items()} for x in batch['af_inputs']] elif ('esm' in args.backbone): x = batch['tokens'].to(device, non_blocking=True) return x
class FFNLayer(nn.Module): def __init__(self, d_model, dim_feedforward=2048, dropout=0.0, activation='relu', normalize_before=False): super().__init__() self.linear1 = nn.Linear(d_model, dim_feedforward) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_feedforward, ...
def _get_activation_fn(activation): 'Return an activation function given a string' if (activation == 'relu'): return F.relu if (activation == 'gelu'): return F.gelu if (activation == 'glu'): return F.glu raise RuntimeError(f'activation should be relu/gelu, not {activation}....
def set_inf(c, inf): for (k, v) in c.items(): if isinstance(v, mlc.ConfigDict): set_inf(v, inf) elif (k == 'inf'): c[k] = inf
def enforce_config_constraints(config): def string_to_setting(s): path = s.split('.') setting = config for p in path: setting = setting[p] return setting mutually_exclusive_bools = [('model.template.average_templates', 'model.template.offload_templates'), ('globals...
def model_config(name, train=False, low_prec=False, long_sequence_inference=False): c = copy.deepcopy(config) if (name == 'initial_training'): pass elif (name == 'finetuning'): c.data.train.crop_size = 384 c.data.train.max_extra_msa = 5120 c.data.train.max_msa_clusters = 51...
class Dropout(nn.Module): '\n Implementation of dropout with the ability to share the dropout mask\n along a particular dimension.\n\n If not in training mode, this module computes the identity function.\n ' def __init__(self, r: float, batch_dim: Union[(int, List[int])]): '\n Args...
class DropoutRowwise(Dropout): '\n Convenience class for rowwise dropout as described in subsection\n 1.11.6.\n ' __init__ = partialmethod(Dropout.__init__, batch_dim=(- 3))
class DropoutColumnwise(Dropout): '\n Convenience class for columnwise dropout as described in subsection\n 1.11.6.\n ' __init__ = partialmethod(Dropout.__init__, batch_dim=(- 2))
class AuxiliaryHeads(nn.Module): def __init__(self, config): super(AuxiliaryHeads, self).__init__() self.plddt = PerResidueLDDTCaPredictor(**config['lddt']) self.distogram = DistogramHead(**config['distogram']) self.masked_msa = MaskedMSAHead(**config['masked_msa']) self.e...
class PerResidueLDDTCaPredictor(nn.Module): def __init__(self, no_bins, c_in, c_hidden): super(PerResidueLDDTCaPredictor, self).__init__() self.no_bins = no_bins self.c_in = c_in self.c_hidden = c_hidden self.layer_norm = LayerNorm(self.c_in) self.linear_1 = Linear...
class DistogramHead(nn.Module): '\n Computes a distogram probability distribution.\n\n For use in computation of distogram loss, subsection 1.9.8\n ' def __init__(self, c_z, no_bins, **kwargs): '\n Args:\n c_z:\n Input channel dimension\n no_bins:\...
class TMScoreHead(nn.Module): '\n For use in computation of TM-score, subsection 1.9.7\n ' def __init__(self, c_z, no_bins, **kwargs): '\n Args:\n c_z:\n Input channel dimension\n no_bins:\n Number of bins\n ' super(TMSco...
class MaskedMSAHead(nn.Module): '\n For use in computation of masked MSA loss, subsection 1.9.9\n ' def __init__(self, c_m, c_out, **kwargs): '\n Args:\n c_m:\n MSA channel dimension\n c_out:\n Output channel dimension\n ' ...
class ExperimentallyResolvedHead(nn.Module): '\n For use in computation of "experimentally resolved" loss, subsection\n 1.9.10\n ' def __init__(self, c_s, c_out, **kwargs): '\n Args:\n c_s:\n Input channel dimension\n c_out:\n Number...
class OuterProductMean(nn.Module): '\n Implements Algorithm 10.\n ' def __init__(self, c_m, c_z, c_hidden, eps=0.001): '\n Args:\n c_m:\n MSA embedding channel dimension\n c_z:\n Pair embedding channel dimension\n c_hidden:\n...
class PairTransition(nn.Module): '\n Implements Algorithm 15.\n ' def __init__(self, c_z, n): '\n Args:\n c_z:\n Pair transition channel dimension\n n:\n Factor by which c_z is multiplied to obtain hidden channel\n dimens...
def script_preset_(model: torch.nn.Module): "\n TorchScript a handful of low-level but frequently used submodule types \n that are known to be scriptable.\n\n Args:\n model: \n A torch.nn.Module. It should contain at least some modules from \n this repository, or this functio...
def _get_module_device(module: torch.nn.Module) -> torch.device: "\n Fetches the device of a module, assuming that all of the module's\n parameters reside on a single device\n\n Args:\n module: A torch.nn.Module\n Returns:\n The module's device\n " return next(module.parameters())...
def _trace_module(module, batch_dims=None): if (batch_dims is None): batch_dims = () n_seq = 10 n_res = 10 device = _get_module_device(module) def msa(channel_dim): return torch.rand((*batch_dims, n_seq, n_res, channel_dim), device=device) def pair(channel_dim): retur...
def _script_submodules_helper_(model, types, attempt_trace, to_trace): for (name, child) in model.named_children(): if ((types is None) or any((isinstance(child, t) for t in types))): try: scripted = torch.jit.script(child) setattr(model, name, scripted) ...
def _trace_submodules_(model, types, batch_dims=None): for (name, child) in model.named_children(): if any((isinstance(child, t) for t in types)): traced = _trace_module(child, batch_dims=batch_dims) setattr(model, name, traced) else: _trace_submodules_(child, t...
def script_submodules_(model: nn.Module, types: Optional[Sequence[type]]=None, attempt_trace: Optional[bool]=True, batch_dims: Optional[Tuple[int]]=None): '\n Convert all submodules whose types match one of those in the input \n list to recursively scripted equivalents in place. To script the entire\n mo...
def fix_pdb(pdbfile, alterations_info): 'Apply pdbfixer to the contents of a PDB file; return a PDB string result.\n\n 1) Replaces nonstandard residues.\n 2) Removes heterogens (non protein residues) including water.\n 3) Adds missing residues and missing atoms within existing residues.\n 4) Adds hydr...
def clean_structure(pdb_structure, alterations_info): 'Applies additional fixes to an OpenMM structure, to handle edge cases.\n\n Args:\n pdb_structure: An OpenMM structure to modify and fix.\n alterations_info: A dict that will store details of changes made.\n ' _replace_met_se(pdb_structure,...
def _remove_heterogens(fixer, alterations_info, keep_water): 'Removes the residues that Pdbfixer considers to be heterogens.\n\n Args:\n fixer: A Pdbfixer instance.\n alterations_info: A dict that will store details of changes made.\n keep_water: If True, water (HOH) is not considered to be a he...
def _replace_met_se(pdb_structure, alterations_info): 'Replace the Se in any MET residues that were not marked as modified.' modified_met_residues = [] for res in pdb_structure.iter_residues(): name = res.get_name_with_spaces().strip() if (name == 'MET'): s_atom = res.get_atom(...
def _remove_chains_of_length_one(pdb_structure, alterations_info): 'Removes chains that correspond to a single amino acid.\n\n A single amino acid in a chain is both N and C terminus. There is no force\n template for this case.\n\n Args:\n pdb_structure: An OpenMM pdb_structure to modify and fix.\n ...
class AmberRelaxation(object): 'Amber relaxation.' def __init__(self, *, max_iterations: int, tolerance: float, stiffness: float, exclude_residues: Sequence[int], max_outer_iterations: int, use_gpu: bool): 'Initialize Amber Relaxer.\n\n Args:\n max_iterations: Maximum number of L-BFGS...
def overwrite_pdb_coordinates(pdb_str: str, pos) -> str: pdb_file = io.StringIO(pdb_str) structure = PdbStructure(pdb_file) topology = openmm_app.PDBFile(structure).getTopology() with io.StringIO() as f: openmm_app.PDBFile.writeFile(topology, pos, f) return f.getvalue()
def overwrite_b_factors(pdb_str: str, bfactors: np.ndarray) -> str: 'Overwrites the B-factors in pdb_str with contents of bfactors array.\n\n Args:\n pdb_str: An input PDB string.\n bfactors: A numpy array with shape [1, n_residues, 37]. We assume that the\n B-factors are per residue; i.e. tha...
def assert_equal_nonterminal_atom_types(atom_mask: np.ndarray, ref_atom_mask: np.ndarray): 'Checks that pre- and post-minimized proteins have same atom set.' oxt = residue_constants.atom_order['OXT'] no_oxt_mask = np.ones(shape=atom_mask.shape, dtype=np.bool) no_oxt_mask[(..., oxt)] = False np.tes...
class ArgparseAlphabetizer(HelpFormatter): '\n Sorts the optional arguments of an argparse parser alphabetically\n ' @staticmethod def sort_actions(actions): return sorted(actions, key=attrgetter('option_strings')) def add_arguments(self, actions): actions = ArgparseAlphabe...
def remove_arguments(parser, args): for arg in args: for action in parser._actions: opts = vars(action)['option_strings'] if (arg in opts): parser._handle_conflict_resolve(None, [(arg, action)])
class EarlyStoppingVerbose(EarlyStopping): "\n The default EarlyStopping callback's verbose mode is too verbose.\n This class outputs a message only when it's getting ready to stop. \n " def _evalute_stopping_criteria(self, *args, **kwargs): (should_stop, reason) = super()._evalute_s...
def get_checkpoint_fn(): deepspeed_is_configured = (deepspeed_is_installed and deepspeed.checkpointing.is_configured()) if deepspeed_is_configured: checkpoint = deepspeed.checkpointing.checkpoint else: checkpoint = torch.utils.checkpoint.checkpoint return checkpoint
@torch.jit.ignore def checkpoint_blocks(blocks: List[Callable], args: BLOCK_ARGS, blocks_per_ckpt: Optional[int]) -> BLOCK_ARGS: '\n Chunk a list of blocks and run each chunk with activation\n checkpointing. We define a "block" as a callable whose only inputs are\n the outputs of the previous block.\n\n ...
def _fetch_dims(tree): shapes = [] tree_type = type(tree) if (tree_type is dict): for v in tree.values(): shapes.extend(_fetch_dims(v)) elif ((tree_type is list) or (tree_type is tuple)): for t in tree: shapes.extend(_fetch_dims(t)) elif (tree_type is torch....
@torch.jit.ignore def _flat_idx_to_idx(flat_idx: int, dims: Tuple[int]) -> Tuple[int]: idx = [] for d in reversed(dims): idx.append((flat_idx % d)) flat_idx = (flat_idx // d) return tuple(reversed(idx))
@torch.jit.ignore def _get_minimal_slice_set(start: Sequence[int], end: Sequence[int], dims: int, start_edges: Optional[Sequence[bool]]=None, end_edges: Optional[Sequence[bool]]=None) -> Sequence[Tuple[int]]: " \n Produces an ordered sequence of tensor slices that, when used in\n sequence on a tenso...
@torch.jit.ignore def _chunk_slice(t: torch.Tensor, flat_start: int, flat_end: int, no_batch_dims: int) -> torch.Tensor: '\n Equivalent to\n \n t.reshape((-1,) + t.shape[no_batch_dims:])[flat_start:flat_end]\n\n but without the need for the initial reshape call, which can be \n ...
def chunk_layer(layer: Callable, inputs: Dict[(str, Any)], chunk_size: int, no_batch_dims: int, low_mem: bool=False, _out: Any=None, _add_into_out: bool=False) -> Any: '\n Implements the "chunking" procedure described in section 1.11.8.\n\n Layer outputs and inputs are assumed to be simple "pytrees,"\n c...
class ChunkSizeTuner(): def __init__(self, max_chunk_size=512): self.max_chunk_size = max_chunk_size self.cached_chunk_size = None self.cached_arg_data = None def _determine_favorable_chunk_size(self, fn, args, min_chunk_size): logging.info('Tuning chunk size...') if ...
class ExponentialMovingAverage(): '\n Maintains moving averages of parameters with exponential decay\n\n At each step, the stored copy `copy` of each parameter `param` is\n updated as follows:\n\n `copy = decay * copy + (1 - decay) * param`\n\n where `decay` is an attribute of the ExponentialMo...
class ParamType(Enum): LinearWeight = partial((lambda w: w.transpose((- 1), (- 2)))) LinearWeightMHA = partial((lambda w: w.reshape(*w.shape[:(- 2)], (- 1)).transpose((- 1), (- 2)))) LinearMHAOutputWeight = partial((lambda w: w.reshape(*w.shape[:(- 3)], (- 1), w.shape[(- 1)]).transpose((- 1), (- 2)))) ...
@dataclass class Param(): param: Union[(torch.Tensor, List[torch.Tensor])] param_type: ParamType = ParamType.Other stacked: bool = False
def process_translation_dict(d, top_layer=True): flat = {} for (k, v) in d.items(): if (type(v) == dict): prefix = (_NPZ_KEY_PREFIX if top_layer else '') sub_flat = {(prefix + '/'.join([k, k_prime])): v_prime for (k_prime, v_prime) in process_translation_dict(v, top_layer=False...
def stacked(param_dict_list, out=None): '\n Args:\n param_dict_list:\n A list of (nested) Param dicts to stack. The structure of\n each dict must be the identical (down to the ParamTypes of\n "parallel" Params). There must be at least one dict\n in the list.\n...
def assign(translation_dict, orig_weights): for (k, param) in translation_dict.items(): with torch.no_grad(): weights = torch.as_tensor(orig_weights[k]) (ref, param_type) = (param.param, param.param_type) if param.stacked: weights = torch.unbind(weights,...
def generate_translation_dict(model, version): LinearWeight = (lambda l: Param(l, param_type=ParamType.LinearWeight)) LinearBias = (lambda l: Param(l)) LinearWeightMHA = (lambda l: Param(l, param_type=ParamType.LinearWeightMHA)) LinearBiasMHA = (lambda b: Param(b, param_type=ParamType.LinearBiasMHA)) ...
def import_jax_weights_(model, npz_path, version='model_1'): data = np.load(npz_path) translations = generate_translation_dict(model, version) flat = process_translation_dict(translations) keys = list(data.keys()) flat_keys = list(flat.keys()) incorrect = [k for k in flat_keys if (k not in key...
class AttentionCoreFunction(torch.autograd.Function): @staticmethod def forward(ctx, q, k, v, bias_1=None, bias_2=None): if ((bias_1 is None) and (bias_2 is not None)): raise ValueError('bias_1 must be specified before bias_2') if (q.dtype not in SUPPORTED_DTYPES): rai...
def is_main_process(): return (int(os.getenv('LOCAL_RANK', '0')) == 0)
class PerformanceLoggingCallback(Callback): def __init__(self, log_file, global_batch_size, warmup_steps: int=0, profile: bool=False): logger.init(backends=[JSONStreamBackend(Verbosity.VERBOSE, log_file), StdOutBackend(Verbosity.VERBOSE)]) self.warmup_steps = warmup_steps self.global_batc...
class AlphaFoldLRScheduler(torch.optim.lr_scheduler._LRScheduler): " Implements the learning rate schedule defined in the AlphaFold 2\n supplement. A linear warmup is followed by a plateau at the maximum\n learning rate and then exponential decay.\n \n Note that the initial learning r...
def is_fp16_enabled(): fp16_enabled = (torch.get_autocast_gpu_dtype() == torch.float16) fp16_enabled = (fp16_enabled and torch.is_autocast_enabled()) return fp16_enabled
def count_models_to_evaluate(openfold_checkpoint_path, jax_param_path): model_count = 0 if openfold_checkpoint_path: model_count += len(openfold_checkpoint_path.split(',')) if jax_param_path: model_count += len(jax_param_path.split(',')) return model_count
def get_model_basename(model_path): return os.path.splitext(os.path.basename(os.path.normpath(model_path)))[0]
def make_output_directory(output_dir, model_name, multiple_model_mode): if multiple_model_mode: prediction_dir = os.path.join(output_dir, 'predictions', model_name) else: prediction_dir = os.path.join(output_dir, 'predictions') os.makedirs(prediction_dir, exist_ok=True) return predicti...
def load_models_from_command_line(config, model_device, openfold_checkpoint_path, jax_param_path, output_dir): multiple_model_mode = (count_models_to_evaluate(openfold_checkpoint_path, jax_param_path) > 1) if multiple_model_mode: logger.info(f'evaluating multiple models') if jax_param_path: ...
def parse_fasta(data): data = re.sub('>$', '', data, flags=re.M) lines = [l.replace('\n', '') for prot in data.split('>') for l in prot.strip().split('\n', 1)][1:] (tags, seqs) = (lines[::2], lines[1::2]) tags = [t.split()[0] for t in tags] return (tags, seqs)
def update_timings(timing_dict, output_file=os.path.join(os.getcwd(), 'timings.json')): '\n Write dictionary of one or more run step times to a file\n ' if os.path.exists(output_file): with open(output_file, 'r') as f: try: timings = json.load(f) except js...
def run_model(model, batch, tag, output_dir): with torch.no_grad(): template_enabled = model.config.template.enabled model.config.template.enabled = (template_enabled and any([('template_' in k) for k in batch])) logger.info(f'Running inference for {tag}...') t = time.perf_counter(...
def prep_output(out, batch, feature_dict, feature_processor, config_preset, multimer_ri_gap, subtract_plddt): plddt = out['plddt'] plddt_b_factors = numpy.repeat(plddt[(..., None)], residue_constants.atom_type_num, axis=(- 1)) if subtract_plddt: plddt_b_factors = (100 - plddt_b_factors) templa...
def relax_protein(config, model_device, unrelaxed_protein, output_directory, output_name, cif_output): amber_relaxer = relax.AmberRelaxation(use_gpu=(model_device != 'cpu'), **config.relax) t = time.perf_counter() visible_devices = os.getenv('CUDA_VISIBLE_DEVICES', default='') if ('cuda' in model_devi...
def seed_globally(seed=None): if ('PL_GLOBAL_SEED' not in os.environ): if (seed is None): seed = random.randint(0, np.iinfo(np.uint32).max) os.environ['PL_GLOBAL_SEED'] = str(seed) logging.info(f'os.environ["PL_GLOBAL_SEED"] set to {seed}') with SuppressLogging(logging.INFO...
def _superimpose_np(reference, coords): '\n Superimposes coordinates onto a reference by minimizing RMSD using SVD.\n\n Args:\n reference:\n [N, 3] reference array\n coords:\n [N, 3] array\n Returns:\n A tuple of [N, 3] superimpos...
def _superimpose_single(reference, coords): reference_np = reference.detach().cpu().numpy() coords_np = coords.detach().cpu().numpy() (superimposed, rmsd) = _superimpose_np(reference_np, coords_np) return (coords.new_tensor(superimposed), coords.new_tensor(rmsd))
def superimpose(reference, coords, mask): '\n Superimposes coordinates onto a reference by minimizing RMSD using SVD.\n\n Args:\n reference:\n [*, N, 3] reference tensor\n coords:\n [*, N, 3] tensor\n mask:\n [*, N] tensor...
class SuppressStdout(): def __enter__(self): self.stdout = sys.stdout dev_null = open('/dev/null', 'w') sys.stdout = dev_null def __exit__(self, typ, value, traceback): fp = sys.stdout sys.stdout = self.stdout fp.close()
class SuppressLogging(): def __init__(self, level): self.level = level def __enter__(self): logging.disable(self.level) def __exit__(self, typ, value, traceback): logging.disable(logging.NOTSET)
def add(m1, m2, inplace): if (not inplace): m1 = (m1 + m2) else: m1 += m2 return m1
def permute_final_dims(tensor: torch.Tensor, inds: List[int]): zero_index = ((- 1) * len(inds)) first_inds = list(range(len(tensor.shape[:zero_index]))) return tensor.permute((first_inds + [(zero_index + i) for i in inds]))
def flatten_final_dims(t: torch.Tensor, no_dims: int): return t.reshape((t.shape[:(- no_dims)] + ((- 1),)))
def masked_mean(mask, value, dim, eps=0.0001): mask = mask.expand(*value.shape) return (torch.sum((mask * value), dim=dim) / (eps + torch.sum(mask, dim=dim)))
def pts_to_distogram(pts, min_bin=2.3125, max_bin=21.6875, no_bins=64): boundaries = torch.linspace(min_bin, max_bin, (no_bins - 1), device=pts.device) dists = torch.sqrt(torch.sum(((pts.unsqueeze((- 2)) - pts.unsqueeze((- 3))) ** 2), dim=(- 1))) return torch.bucketize(dists, boundaries)
def dict_multimap(fn, dicts): first = dicts[0] new_dict = {} for (k, v) in first.items(): all_v = [d[k] for d in dicts] if (type(v) is dict): new_dict[k] = dict_multimap(fn, all_v) else: new_dict[k] = fn(all_v) return new_dict
def one_hot(x, v_bins): reshaped_bins = v_bins.view((((1,) * len(x.shape)) + (len(v_bins),))) diffs = (x[(..., None)] - reshaped_bins) am = torch.argmin(torch.abs(diffs), dim=(- 1)) return nn.functional.one_hot(am, num_classes=len(v_bins)).float()
def batched_gather(data, inds, dim=0, no_batch_dims=0): ranges = [] for (i, s) in enumerate(data.shape[:no_batch_dims]): r = torch.arange(s) r = r.view(*(*((1,) * i), (- 1), *((1,) * ((len(inds.shape) - i) - 1)))) ranges.append(r) remaining_dims = [slice(None) for _ in range((len(d...
def dict_map(fn, dic, leaf_type): new_dict = {} for (k, v) in dic.items(): if (type(v) is dict): new_dict[k] = dict_map(fn, v, leaf_type) else: new_dict[k] = tree_map(fn, v, leaf_type) return new_dict
def tree_map(fn, tree, leaf_type): if isinstance(tree, dict): return dict_map(fn, tree, leaf_type) elif isinstance(tree, list): return [tree_map(fn, x, leaf_type) for x in tree] elif isinstance(tree, tuple): return tuple([tree_map(fn, x, leaf_type) for x in tree]) elif isinstan...