code
stringlengths
17
6.64M
def patch_llama_for_linear_scaled_rotary_embeddings(model, scale): from .LlamaLinearScaledRotaryEmbedding import LlamaLinearScaledRotaryEmbedding for each in model.model.layers: each.self_attn.rotary_emb = LlamaLinearScaledRotaryEmbedding(each.self_attn.head_dim, scale=scale, device=each.self_attn.rot...
def patch_llama_for_part_ntk_scaled_rotary_embeddings(model, scale): from .LlamaPartNTKScaledRotaryEmbedding import LlamaPartNTKScaledRotaryEmbedding for each in model.model.layers: each.self_attn.rotary_emb = LlamaPartNTKScaledRotaryEmbedding(each.self_attn.head_dim, scale=scale, device=each.self_att...
def patch_llama_for_yarn_scaled_rotary_embeddings(model, scale, original_max_position_embeddings): from .LlamaYaRNScaledRotaryEmbedding import LlamaYaRNScaledRotaryEmbedding for each in model.model.layers: each.self_attn.rotary_emb = LlamaYaRNScaledRotaryEmbedding(each.self_attn.head_dim, scale=scale,...
def patch_gptneox_for_scaled_rotary_embeddings(model): from .GPTNeoXDynamicScaledRotaryEmbedding import GPTNeoXDynamicScaledRotaryEmbedding for each in model.gpt_neox.layers: each.attention.rotary_emb = GPTNeoXDynamicScaledRotaryEmbedding(each.attention.rotary_ndims, model.config.max_position_embeddin...
def patch_gptneox_for_ntk_scaled_rotary_embeddings(model, alpha): from .GPTNeoXNTKScaledRotaryEmbedding import GPTNeoXNTKScaledRotaryEmbedding for each in model.gpt_neox.layers: each.attention.rotary_emb = GPTNeoXNTKScaledRotaryEmbedding(each.attention.rotary_ndims, model.config.max_position_embedding...
def patch_gptneox_for_longer_sequences(model, max_positions): for each in model.gpt_neox.layers: each.attention.bias = torch.tril(torch.ones((max_positions, max_positions), dtype=each.attention.bias.dtype, device=each.attention.bias.device)).view(1, 1, max_positions, max_positions)
def patch_llama_for_rerope(model, training_length, window): from .LlamaReRoPE import forward_with_rerope for each in model.model.layers: def forward(*args, **kwargs): return forward_with_rerope(each.self_attn, *args, **kwargs) each.self_attn.training_length = int(training_length) ...
def main(args): if ((args.dataset is None) or (len(args.dataset[0]) == 0)): raise RuntimeError('No datasets provided') datasets = args.dataset[0] splits = [(x.split(',')[1] if (len(x.split(',')) == 2) else '') for x in datasets] datasets = [x.split(',')[0] for x in datasets] tokenizer = Au...
def main(args): dataset = load_dataset(args.dataset, split='train') def truncate(sample): sample['input_ids'] = sample['input_ids'][0:args.truncate] sample['labels'] = sample['labels'][0:args.truncate] sample['attention_mask'] = sample['attention_mask'][0:args.truncate] return...
class SimCLR(nn.Module): 'Simple SIMCLR implementation.' def __init__(self, base_network_output_size, nce_logits_output_size, classifier_output_size): 'SimCLR model.\n\n :param base_network_output_size: output-size of resnet50 embedding\n :param nce_logits_output_size: output-size to us...
def build_lr_schedule(optimizer, last_epoch=(- 1)): ' adds a lr scheduler to the optimizer.\n\n :param optimizer: nn.Optimizer\n :returns: scheduler\n :rtype: optim.lr_scheduler\n\n ' if (args.lr_update_schedule == 'fixed'): sched = optim.lr_scheduler.LambdaLR(optimizer, (lambda epoch: 1.0...
def build_optimizer(model, last_epoch=(- 1)): ' helper to build the optimizer and wrap model\n\n :param model: the model to wrap\n :returns: optimizer wrapping model provided\n :rtype: nn.Optim\n\n ' optim_map = {'rmsprop': optim.RMSprop, 'adam': optim.Adam, 'adadelta': optim.Adadelta, 'sgd': opti...
def build_train_and_test_transforms(): 'Returns torchvision OR nvidia-dali transforms.\n\n :returns: train_transforms, test_transforms\n :rtype: list, list\n\n ' resize_shape = (args.image_size_override, args.image_size_override) if ('dali' in args.task): import nvidia.dali.ops as ops ...
def build_loader_model_grapher(args): 'builds a model, a dataloader and a grapher\n\n :param args: argparse\n :param transform: the dataloader transform\n :returns: a dataloader, a grapher and a model\n :rtype: list\n\n ' (train_transform, test_transform) = build_train_and_test_transforms() ...
def lazy_generate_modules(model, loader): ' A helper to build the modules that are lazily compiled\n\n :param model: the nn.Module\n :param loader: the dataloader\n :returns: None\n :rtype: None\n\n ' model.eval() for (augmentation1, augmentation2, labels) in loader: with torch.no_g...
def register_plots(loss, grapher, epoch, prefix='train'): " Registers line plots with grapher.\n\n :param loss: the dict containing '*_mean' or '*_scalar' values\n :param grapher: the grapher object\n :param epoch: the current epoch\n :param prefix: prefix to append to the plot\n :returns: None\n ...
def register_images(output_map, grapher, prefix='train'): " Registers image with grapher. Overwrites the existing image due to space.\n\n :param output_map: the dict containing '*_img' of '*_imgs' as keys\n :param grapher: the grapher object\n :param prefix: prefix to attach to images\n :returns: None...
def _extract_sum_scalars(v1, v2): 'Simple helper to sum values in a struct using dm_tree.' def chk(c): 'Helper to check if we have a primitive or tensor' return (not isinstance(c, (int, float, np.int32, np.int64, np.float32, np.float64))) v1_detached = (v1.detach() if chk(v1) else v1) ...
def execute_graph(epoch, model, loader, grapher, optimizer=None, prefix='test'): " execute the graph; wphen 'train' is in the name the model runs the optimizer\n\n :param epoch: the current epoch number\n :param model: the torch model\n :param loader: the train or **TEST** loader\n :param grapher: the...
def train(epoch, model, optimizer, train_loader, grapher, prefix='train'): ' Helper to run execute-graph for the train dataset\n\n :param epoch: the current epoch\n :param model: the model\n :param test_loader: the train data-loader\n :param grapher: the grapher object\n :param prefix: the default ...
def test(epoch, model, test_loader, grapher, prefix='test'): ' Helper to run execute-graph for the test dataset\n\n :param epoch: the current epoch\n :param model: the model\n :param test_loader: the test data-loaderpp\n :param grapher: the grapher object\n :param prefix: the default prefix; useful...
def init_multiprocessing_and_cuda(rank, args_from_spawn): 'Sets the appropriate flags for multi-process jobs.' if args_from_spawn.multi_gpu_distributed: os.environ['CUDA_VISIBLE_DEVICES'] = str(rank) args_from_spawn.distributed_rank = rank args_from_spawn.cuda = ((not args_from_spawn.no_cu...
def run(rank, args): ' Main entry-point into the program\n\n :param rank: current device rank\n :param args: argparse\n :returns: None\n :rtype: None\n\n ' init_multiprocessing_and_cuda(rank, args) (loader, model, grapher) = build_loader_model_grapher(args) print(pprint.PrettyPrinter(in...
def l2_normalize(x, dim=None, eps=1e-12): 'Normalize a tensor over dim using the L2-norm.' sq_sum = torch.sum(torch.square(x), dim=dim, keepdim=True) inv_norm = torch.rsqrt(torch.max(sq_sum, (torch.ones_like(sq_sum) * eps))) return (x * inv_norm)
def all_gather(tensor, expand_dim=0, num_replicas=None): 'Gathers a tensor from other replicas, concat on expand_dim and return.' num_replicas = (dist.get_world_size() if (num_replicas is None) else num_replicas) other_replica_tensors = [torch.zeros_like(tensor) for _ in range(num_replicas)] dist.all_...
class NTXent(nn.Module): 'Wrap a module to get self.training member.' def __init__(self): super(NTXent, self).__init__() def forward(self, embedding1, embedding2, temperature=0.1, num_replicas=None): 'NT-XENT Loss from SimCLR\n\n :param embedding1: embedding of augmentation1\n ...
class LARS(Optimizer): "Implements 'LARS (Layer-wise Adaptive Rate Scaling)'__ as Optimizer a\n :class:`~torch.optim.Optimizer` wrapper.\n\n __ : https://arxiv.org/abs/1708.03888\n\n Wraps an arbitrary optimizer like :class:`torch.optim.SGD` to use LARS. If\n you want to the same performance obtained ...
class Scheduler(object): 'Simple container for warmup and normal scheduler.' def __init__(self, normal_schededuler, warmup_scheduler=None): self.warmup = warmup_scheduler self.sched = normal_schededuler def get_last_lr(self): ' Return last computed learning rate by current schedu...
class LinearWarmup(LambdaLR): ' Linear warmup and then constant.\n Linearly increases learning rate schedule from 0 to 1 over `warmup_steps` training steps.\n Keeps learning rate schedule equal to 1. after warmup_steps.\n\n From https://bit.ly/39o2W1f\n ' def __init__(self, optimizer,...
class ProgressLogger(Callback): def __init__(self, metric_monitor: dict, precision: int=3): self.metric_monitor = metric_monitor self.precision = precision def on_train_start(self, trainer: Trainer, pl_module: LightningModule, **kwargs) -> None: logger.info('Training started') d...
def get_module_config(cfg_model, path='modules'): files = os.listdir(f'./configs/{path}/') for file in files: if file.endswith('.yaml'): with open((f'./configs/{path}/' + file), 'r') as f: cfg_model.merge_with(OmegaConf.load(f)) return cfg_model
def get_obj_from_str(string, reload=False): (module, cls) = string.rsplit('.', 1) if reload: module_imp = importlib.import_module(module) importlib.reload(module_imp) return getattr(importlib.import_module(module, package=None), cls)
def instantiate_from_config(config): if (not ('target' in config)): if (config == '__is_first_stage__'): return None elif (config == '__is_unconditional__'): return None raise KeyError('Expected key `target` to instantiate.') return get_obj_from_str(config['targ...
def parse_args(phase='train'): parser = ArgumentParser() group = parser.add_argument_group('Training options') if (phase in ['train', 'test', 'demo']): group.add_argument('--cfg', type=str, required=False, default='./configs/config.yaml', help='config file') group.add_argument('--cfg_asset...
class HumanML3DDataModule(BASEDataModule): def __init__(self, cfg, batch_size, num_workers, collate_fn=None, phase='train', **kwargs): super().__init__(batch_size=batch_size, num_workers=num_workers, collate_fn=collate_fn) self.save_hyperparameters(logger=False) self.name = 'humanml3d' ...
class Humanact12DataModule(BASEDataModule): def __init__(self, cfg, batch_size, num_workers, collate_fn=None, phase='train', **kwargs): super().__init__(batch_size=batch_size, num_workers=num_workers, collate_fn=collate_fn) self.save_hyperparameters(logger=False) self.name = 'HumanAct12' ...
class KitDataModule(BASEDataModule): def __init__(self, cfg, phase='train', collate_fn=all_collate, batch_size: int=32, num_workers: int=16, **kwargs): super().__init__(batch_size=batch_size, num_workers=num_workers, collate_fn=collate_fn) self.save_hyperparameters(logger=False) self.name...
class UestcDataModule(BASEDataModule): def __init__(self, cfg, batch_size, num_workers, collate_fn=None, method_name='vibe', phase='train', **kwargs): super().__init__(batch_size=batch_size, num_workers=num_workers, collate_fn=collate_fn) self.save_hyperparameters(logger=False) self.name ...
class HumanAct12Poses(Dataset): dataname = 'humanact12' def __init__(self, datapath='data/HumanAct12Poses', **kargs): self.datapath = datapath super().__init__(**kargs) pkldatafilepath = os.path.join(datapath, 'humanact12poses.pkl') with rich.progress.open(pkldatafilepath, 'rb...
def parse_info_name(path): name = os.path.splitext(os.path.split(path)[(- 1)])[0] info = {} current_letter = None for letter in name: if (letter in string.ascii_letters): info[letter] = [] current_letter = letter else: info[current_letter].append(let...
def to_numpy(tensor): if torch.is_tensor(tensor): return tensor.cpu().numpy() elif (type(tensor).__module__ != 'numpy'): raise ValueError('Cannot convert {} to numpy array'.format(type(tensor))) return tensor
def to_torch(ndarray): if (type(ndarray).__module__ == 'numpy'): return torch.from_numpy(ndarray) elif (not torch.is_tensor(ndarray)): raise ValueError('Cannot convert {} to torch tensor'.format(type(ndarray))) return ndarray
def cleanexit(): import sys import os try: sys.exit(0) except SystemExit: os._exit(0)
def lengths_to_mask(lengths): max_len = max(lengths) mask = (torch.arange(max_len, device=lengths.device).expand(len(lengths), max_len) < lengths.unsqueeze(1)) return mask
def collate_tensors(batch): dims = batch[0].dim() max_size = [max([b.size(i) for b in batch]) for i in range(dims)] size = ((len(batch),) + tuple(max_size)) canvas = batch[0].new_zeros(size=size) for (i, b) in enumerate(batch): sub_tensor = canvas[i] for d in range(dims): ...
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 = leng...
class BASEDataModule(pl.LightningDataModule): def __init__(self, collate_fn, batch_size: int, num_workers: int): super().__init__() self.dataloader_options = {'batch_size': batch_size, 'num_workers': num_workers, 'collate_fn': collate_fn} self.persistent_workers = True self.is_mm ...
def get_mean_std(phase, cfg, dataset_name): name = ('t2m' if (dataset_name == 'humanml3d') else dataset_name) assert (name in ['t2m', 'kit']) if (phase in ['val']): if (name == 't2m'): data_root = pjoin(cfg.model.t2m_path, name, 'Comp_v6_KLD01', 'meta') elif (name == 'kit'): ...
def get_WordVectorizer(cfg, phase, dataset_name): if (phase not in ['text_only']): if (dataset_name.lower() in ['humanml3d', 'kit']): return WordVectorizer(cfg.DATASET.WORD_VERTILIZER_PATH, 'our_vab') else: raise ValueError('Only support WordVectorizer for HumanML3D') e...
def get_collate_fn(name, phase='train'): if (name.lower() in ['humanml3d', 'kit']): return mld_collate elif (name.lower() in ['humanact12', 'uestc']): return a2m_collate
def get_datasets(cfg, logger=None, phase='train'): dataset_names = eval(f'cfg.{phase.upper()}.DATASETS') datasets = [] for dataset_name in dataset_names: if (dataset_name.lower() in ['humanml3d', 'kit']): data_root = eval(f'cfg.DATASET.{dataset_name.upper()}.ROOT') (mean, s...
def is_float(numStr): flag = False numStr = str(numStr).strip().lstrip('-').lstrip('+') try: reg = re.compile('^[-+]?[0-9]+\\.[0-9]+$') res = reg.match(str(numStr)) if res: flag = True except Exception as ex: print(('is_float() - error: ' + str(ex))) ret...
def is_number(numStr): flag = False numStr = str(numStr).strip().lstrip('-').lstrip('+') if str(numStr).isdigit(): flag = True return flag
def get_opt(opt_path, device): opt = Namespace() opt_dict = vars(opt) skip = ('-------------- End ----------------', '------------ Options -------------', '\n') print('Reading', opt_path) with open(opt_path) as f: for line in f: if (line.strip() not in skip): (k...
def save_json(save_path, data): with open(save_path, 'w') as file: json.dump(data, file)
def load_json(file_path): with open(file_path, 'r') as file: data = json.load(file) return data
def process(graph): (entities, relations) = ({}, []) for i in graph['verbs']: description = i['description'] pos = 0 flag = 0 (_words, _spans) = ([], []) for i in description.split(): (tags, verb) = ({}, 0) if ('[' in i): _role = ...
class WordVectorizer(object): def __init__(self, meta_root, prefix): vectors = np.load(pjoin(meta_root, ('%s_data.npy' % prefix))) words = pickle.load(open(pjoin(meta_root, ('%s_words.pkl' % prefix)), 'rb')) word2idx = pickle.load(open(pjoin(meta_root, ('%s_idx.pkl' % prefix)), 'rb')) ...
class FrameSampler(): def __init__(self, sampling='conseq', sampling_step=1, request_frames=None, threshold_reject=0.75, max_len=1000, min_len=10): self.sampling = sampling self.sampling_step = sampling_step self.request_frames = request_frames self.threshold_reject = threshold_re...
def subsample(num_frames, last_framerate, new_framerate): step = int((last_framerate / new_framerate)) assert (step >= 1) frames = np.arange(0, num_frames, step) return frames
def upsample(motion, last_framerate, new_framerate): step = int((new_framerate / last_framerate)) assert (step >= 1) alpha = np.linspace(0, 1, (step + 1)) last = np.einsum('l,...->l...', (1 - alpha), motion[:(- 1)]) new = np.einsum('l,...->l...', alpha, motion[1:]) chuncks = (last + new)[:(- 1...
def get_frameix_from_data_index(num_frames: int, request_frames: Optional[int], sampling: str='conseq', sampling_step: int=1) -> Array: nframes = num_frames if (request_frames is None): frame_ix = np.arange(nframes) elif (request_frames > nframes): fair = False if fair: ...
def lengths_to_mask(lengths): max_len = max(lengths) mask = (torch.arange(max_len, device=lengths.device).expand(len(lengths), max_len) < lengths.unsqueeze(1)) return mask
def collate_tensors(batch): dims = batch[0].dim() max_size = [max([b.size(i) for b in batch]) for i in range(dims)] size = ((len(batch),) + tuple(max_size)) canvas = batch[0].new_zeros(size=size) for (i, b) in enumerate(batch): sub_tensor = canvas[i] for d in range(dims): ...
def all_collate(batch): notnone_batches = [b for b in batch if (b is not None)] databatch = [b['motion'] for b in notnone_batches] if ('lengths' in notnone_batches[0]): lenbatch = [b['lengths'] for b in notnone_batches] else: lenbatch = [len(b['inp'][0][0]) for b in notnone_batches] ...
def mld_collate(batch): notnone_batches = [b for b in batch if (b is not None)] notnone_batches.sort(key=(lambda x: x[3]), reverse=True) adapted_batch = {'motion': collate_tensors([torch.tensor(b[4]).float() for b in notnone_batches]), 'text': [b[2] for b in notnone_batches], 'length': [b[5] for b in notn...
def a2m_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] labeltextbatch = [b[3] for b in batch] databatchTensor = collate_tensors(databatch) labelbatchTensor = torch.as_tensor(labelbatch).unsqueeze(1) lenbatchT...
def parse_args(self, args=None, namespace=None): if (args is not None): return self.parse_args_bak(args=args, namespace=namespace) try: idx = sys.argv.index('--') args = sys.argv[(idx + 1):] except ValueError as e: args = [] return self.parse_args_bak(args=args, namespa...
def code_path(path=''): code_dir = hydra.utils.get_original_cwd() code_dir = Path(code_dir) return str((code_dir / path))
def working_path(path): return str((Path(os.getcwd()) / path))
def generate_id(): return ID
def get_last_checkpoint(path, ckpt_name='last.ckpt'): output_dir = Path(hydra.utils.to_absolute_path(path)) last_ckpt_path = ((output_dir / 'checkpoints') / ckpt_name) return str(last_ckpt_path)
def get_kitname(load_amass_data: bool, load_with_rot: bool): if (not load_amass_data): return 'kit-mmm-xyz' if (load_amass_data and (not load_with_rot)): return 'kit-amass-xyz' if (load_amass_data and load_with_rot): return 'kit-amass-rot'
def resolve_cfg_path(cfg: DictConfig): working_dir = os.getcwd() cfg.working_dir = working_dir
class ActorVae(nn.Module): def __init__(self, ablation, nfeats: int, latent_dim: list=[1, 256], ff_size: int=1024, num_layers: int=9, num_heads: int=4, dropout: float=0.1, is_vae: bool=True, activation: str='gelu', position_embedding: str='learned', **kwargs) -> None: super().__init__() self.late...
class ActorAgnosticEncoder(nn.Module): def __init__(self, nfeats: int, vae: bool, latent_dim: int=256, ff_size: int=1024, num_layers: int=4, num_heads: int=4, dropout: float=0.1, activation: str='gelu', **kwargs) -> None: super().__init__() input_feats = nfeats self.vae = vae self...
class ActorAgnosticDecoder(nn.Module): def __init__(self, nfeats: int, latent_dim: int=256, ff_size: int=1024, num_layers: int=4, num_heads: int=4, dropout: float=0.1, activation: str='gelu', **kwargs) -> None: super().__init__() output_feats = nfeats self.latent_dim = latent_dim ...
def sample_from_distribution(dist, *, fact=1.0, sample_mean=False) -> Tensor: if sample_mean: return dist.loc.unsqueeze(0) if (fact is None): return dist.rsample().unsqueeze(0) eps = (dist.rsample() - dist.loc) z = (dist.loc + (fact * eps)) z = z.unsqueeze(0) return z
class MLDTextEncoder(nn.Module): def __init__(self, cfg, modelpath: str, finetune: bool=False, vae: bool=True, latent_dim: int=256, ff_size: int=1024, num_layers: int=6, num_heads: int=4, dropout: float=0.1, activation: str='gelu', **kwargs) -> None: super().__init__() from transformers import Au...
class Encoder_FC(nn.Module): def __init__(self, modeltype, njoints, nfeats, num_frames, num_classes, translation, pose_rep, glob, glob_rot, latent_dim=256, **kargs): super().__init__() self.modeltype = modeltype self.njoints = njoints self.nfeats = nfeats self.num_frames =...
class Decoder_FC(nn.Module): def __init__(self, modeltype, njoints, nfeats, num_frames, num_classes, translation, pose_rep, glob, glob_rot, latent_dim=256, **kargs): super().__init__() self.modeltype = modeltype self.njoints = njoints self.nfeats = nfeats self.num_frames =...
class GATLayer(nn.Module): def __init__(self, in_features=768, out_features=768, dropout=0.1, alpha=0.2, concat=True): super(GATLayer, self).__init__() self.dropout = dropout self.in_features = in_features self.out_features = out_features self.alpha = alpha self.co...
class MotionDiscriminator(nn.Module): def __init__(self, input_size, hidden_size, hidden_layer, output_size=12, use_noise=None): super().__init__() self.input_size = input_size self.hidden_size = hidden_size self.hidden_layer = hidden_layer self.use_noise = use_noise ...
class MotionDiscriminatorForFID(MotionDiscriminator): def forward(self, motion_sequence, lengths=None, hidden_unit=None): (bs, njoints, nfeats, num_frames) = motion_sequence.shape motion_sequence = motion_sequence.reshape(bs, (njoints * nfeats), num_frames) motion_sequence = motion_sequen...
class MovementConvEncoder(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(MovementConvEncoder, self).__init__() self.main = nn.Sequential(nn.Conv1d(input_size, hidden_size, 4, 2, 1), nn.Dropout(0.2, inplace=True), nn.LeakyReLU(0.2, inplace=True), nn.Conv1d(hidden_size,...
class MotionEncoderBiGRUCo(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(MotionEncoderBiGRUCo, self).__init__() self.input_emb = nn.Linear(input_size, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True, bidirectional=True) self....
class TextEncoderBiGRUCo(nn.Module): def __init__(self, word_size, pos_size, hidden_size, output_size): super(TextEncoderBiGRUCo, self).__init__() self.pos_emb = nn.Linear(pos_size, word_size) self.input_emb = nn.Linear(word_size, hidden_size) self.gru = nn.GRU(hidden_size, hidden...
class STGCN(nn.Module): 'Spatial temporal graph convolutional networks.\n Args:\n in_channels (int): Number of channels in the input data\n num_class (int): Number of classes for the classification task\n graph_args (dict): The arguments for building the graph\n edge_importance_weig...
class st_gcn(nn.Module): 'Applies a spatial temporal graph convolution over an input graph sequence.\n Args:\n in_channels (int): Number of channels in the input sequence data\n out_channels (int): Number of channels produced by the convolution\n kernel_size (tuple): Size of the temporal c...
class Graph(): " The Graph to model the skeletons extracted by the openpose\n Args:\n strategy (string): must be one of the follow candidates\n - uniform: Uniform Labeling\n - distance: Distance Partitioning\n - spatial: Spatial Configuration\n For more information, please re...
class ConvTemporalGraphical(nn.Module): 'The basic module for applying a graph convolution.\n Args:\n in_channels (int): Number of channels in the input sequence data\n out_channels (int): Number of channels produced by the convolution\n kernel_size (int): Size of the graph convolving kern...
def get_hop_distance(num_node, edge, max_hop=1): A = np.zeros((num_node, num_node)) for (i, j) in edge: A[(j, i)] = 1 A[(i, j)] = 1 hop_dis = (np.zeros((num_node, num_node)) + np.inf) transfer_mat = [np.linalg.matrix_power(A, d) for d in range((max_hop + 1))] arrive_mat = (np.stack...
def normalize_digraph(A): Dl = np.sum(A, 0) num_node = A.shape[0] Dn = np.zeros((num_node, num_node)) for i in range(num_node): if (Dl[i] > 0): Dn[(i, i)] = (Dl[i] ** (- 1)) AD = np.dot(A, Dn) return AD
def normalize_undigraph(A): Dl = np.sum(A, 0) num_node = A.shape[0] Dn = np.zeros((num_node, num_node)) for i in range(num_node): if (Dl[i] > 0): Dn[(i, i)] = (Dl[i] ** (- 0.5)) DAD = np.dot(np.dot(Dn, A), Dn) return DAD
class VPosert(nn.Module): def __init__(self, cfg, **kwargs) -> None: super(VPosert, self).__init__() num_neurons = 512 self.latentD = 256 n_features = (196 * 263) self.encoder_net = nn.Sequential(BatchFlatten(), nn.BatchNorm1d(n_features), nn.Linear(n_features, num_neurons...
class BatchFlatten(nn.Module): def __init__(self): super(BatchFlatten, self).__init__() self._name = 'batch_flatten' def forward(self, x): return x.view(x.shape[0], (- 1))
class ContinousRotReprDecoder(nn.Module): def __init__(self): super(ContinousRotReprDecoder, self).__init__() def forward(self, module_input): reshaped_input = module_input.view((- 1), 196, 263) return reshaped_input
class NormalDistDecoder(nn.Module): def __init__(self, num_feat_in, latentD): super(NormalDistDecoder, self).__init__() self.mu = nn.Linear(num_feat_in, latentD) self.logvar = nn.Linear(num_feat_in, latentD) def forward(self, Xout): return torch.distributions.normal.Normal(se...
def get_model(cfg, datamodule, phase='train'): modeltype = cfg.model.model_type if (modeltype == 'GraphMotion'): return get_module(cfg, datamodule) else: raise ValueError(f'Invalid model type {modeltype}.')
def get_module(cfg, datamodule): modeltype = cfg.model.model_type model_module = importlib.import_module(f'.modeltype.{cfg.model.model_type}', package='GraphMotion.models') Model = model_module.__getattribute__(f'{modeltype}') return Model(cfg=cfg, datamodule=datamodule)