code stringlengths 17 6.64M |
|---|
def lengths_to_mask(lengths: List[int], device: torch.device, max_len: int=None) -> Tensor:
lengths = torch.tensor(lengths, device=device)
max_len = (max_len if max_len else max(lengths))
mask = (torch.arange(max_len, device=device).expand(len(lengths), max_len) < lengths.unsqueeze(1))
return mask
|
def detach_to_numpy(tensor):
return tensor.detach().cpu().numpy()
|
def remove_padding(tensors, lengths):
return [tensor[:tensor_length] for (tensor, tensor_length) in zip(tensors, lengths)]
|
def nfeats_of(rottype):
if (rottype in ['rotvec', 'axisangle']):
return 3
elif (rottype in ['rotquat', 'quaternion']):
return 4
elif (rottype in ['rot6d', '6drot', 'rotation6d']):
return 6
elif (rottype in ['rotmat']):
return 9
else:
return TypeError("This r... |
def axis_angle_to(newtype, rotations):
if (newtype in ['matrix']):
rotations = geometry.axis_angle_to_matrix(rotations)
return rotations
elif (newtype in ['rotmat']):
rotations = geometry.axis_angle_to_matrix(rotations)
rotations = matrix_to('rotmat', rotations)
return ... |
def matrix_to(newtype, rotations):
if (newtype in ['matrix']):
return rotations
if (newtype in ['rotmat']):
rotations = rotations.reshape((*rotations.shape[:(- 2)], 9))
return rotations
elif (newtype in ['rot6d', '6drot', 'rotation6d']):
rotations = geometry.matrix_to_rotat... |
def to_matrix(oldtype, rotations):
if (oldtype in ['matrix']):
return rotations
if (oldtype in ['rotmat']):
rotations = rotations.reshape((*rotations.shape[:(- 2)], 3, 3))
return rotations
elif (oldtype in ['rot6d', '6drot', 'rotation6d']):
rotations = geometry.rotation_6d_... |
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 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... |
def collate_data3d_slow(batch):
batchTensor = {}
for key in batch[0].keys():
databatch = [b[key] for b in batch]
batchTensor[key] = collate_tensors(databatch)
batch = batchTensor
return batch
|
def collate_data3d(batch):
batchTensor = {}
for key in batch[0].keys():
databatch = [b[key] for b in batch]
if (key == 'paths'):
batchTensor[key] = databatch
else:
batchTensor[key] = torch.stack(databatch, axis=0)
batch = batchTensor
return batch
|
def main():
'\n get input text\n ToDo skip if user input text in command\n current tasks:\n 1 text 2 mtion\n 2 motion transfer\n 3 random sampling\n 4 reconstruction\n\n ToDo \n 1 use one funtion for all expoert\n 2 fitting smpl and export fbx in this file\n 3 ... |
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 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 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 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 == 'mld'):
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='mld.models')
Model = model_module.__getattribute__(f'{modeltype.upper()}')
return Model(cfg=cfg, datamodule=datamodule)
|
class ACTORLosses(Metric):
'\n Loss\n Modify loss\n \n '
def __init__(self, vae, mode, cfg):
super().__init__(dist_sync_on_step=cfg.LOSS.DIST_SYNC_ON_STEP)
self.vae = vae
self.mode = mode
losses = []
losses.append('recons_feature')
losses.app... |
class KLLoss():
def __init__(self):
pass
def __call__(self, q, p):
div = torch.distributions.kl_divergence(q, p)
return div.mean()
def __repr__(self):
return 'KLLoss()'
|
class KLLossMulti():
def __init__(self):
self.klloss = KLLoss()
def __call__(self, qlist, plist):
return sum([self.klloss(q, p) for (q, p) in zip(qlist, plist)])
def __repr__(self):
return 'KLLossMulti()'
|
class KLLoss():
def __init__(self):
pass
def __call__(self, q, p):
div = torch.distributions.kl_divergence(q, p)
return div.mean()
def __repr__(self):
return 'KLLoss()'
|
class KLLossMulti():
def __init__(self):
self.klloss = KLLoss()
def __call__(self, qlist, plist):
return sum([self.klloss(q, p) for (q, p) in zip(qlist, plist)])
def __repr__(self):
return 'KLLossMulti()'
|
class MLDLosses(Metric):
'\n MLD Loss\n '
def __init__(self, vae, mode, cfg):
super().__init__(dist_sync_on_step=cfg.LOSS.DIST_SYNC_ON_STEP)
self.vae_type = cfg.TRAIN.ABLATION.VAE_TYPE
self.mode = mode
self.cfg = cfg
self.predict_epsilon = cfg.TRAIN.ABLATION.PRED... |
class KLLoss():
def __init__(self):
pass
def __call__(self, q, p):
div = torch.distributions.kl_divergence(q, p)
return div.mean()
def __repr__(self):
return 'KLLoss()'
|
class KLLossMulti():
def __init__(self):
self.klloss = KLLoss()
def __call__(self, qlist, plist):
return sum([self.klloss(q, p) for (q, p) in zip(qlist, plist)])
def __repr__(self):
return 'KLLossMulti()'
|
class TemosLosses(Metric):
"\n Loss\n Modify loss\n refer to temos loss\n add loss like deep-motion-editing\n 'gen_loss_total': l_total,\n 'gen_loss_adv': l_adv,\n 'gen_loss_recon_all': l_rec,\n 'gen_loss_recon_r': l_r_rec,\n 'gen_loss_recon_s': l_s_rec,\n 'gen_loss_feature_all': l_f... |
class KLLoss():
def __init__(self):
pass
def __call__(self, q, p):
div = torch.distributions.kl_divergence(q, p)
return div.mean()
def __repr__(self):
return 'KLLoss()'
|
class KLLossMulti():
def __init__(self):
self.klloss = KLLoss()
def __call__(self, qlist, plist):
return sum([self.klloss(q, p) for (q, p) in zip(qlist, plist)])
def __repr__(self):
return 'KLLossMulti()'
|
class TmostLosses(Metric):
"\n Loss\n Modify loss\n refer to temos loss\n add loss like deep-motion-editing\n 'gen_loss_total': l_total,\n 'gen_loss_adv': l_adv,\n 'gen_loss_recon_all': l_rec,\n 'gen_loss_recon_r': l_r_rec,\n 'gen_loss_recon_s': l_s_rec,\n 'gen_loss_feature_all': l_f... |
class KLLoss():
def __init__(self):
pass
def __call__(self, q, p):
div = torch.distributions.kl_divergence(q, p)
return div.mean()
def __repr__(self):
return 'KLLoss()'
|
class KLLossMulti():
def __init__(self):
self.klloss = KLLoss()
def __call__(self, qlist, plist):
return sum([self.klloss(q, p) for (q, p) in zip(qlist, plist)])
def __repr__(self):
return 'KLLossMulti()'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.