code
stringlengths
17
6.64M
class ComputeMetricsBest(ComputeMetrics): def update(self, jts_text_: List[Tensor], jts_ref_: List[Tensor], lengths: List[List[int]]): self.count += sum(lengths[0]) self.count_seq += len(lengths[0]) ntrials = len(jts_text_) metrics = [] for index in range(ntrials): ...
class ComputeMetricsWorst(ComputeMetrics): def update(self, jts_text_: List[Tensor], jts_ref_: List[Tensor], lengths: List[List[int]]): self.count += sum(lengths[0]) self.count_seq += len(lengths[0]) ntrials = len(jts_text_) metrics = [] for index in range(ntrials): ...
class MMMetrics(Metric): full_state_update = True def __init__(self, mm_num_times=10, dist_sync_on_step=True, stage=0, **kwargs): super().__init__(dist_sync_on_step=dist_sync_on_step) self.name = 'MultiModality scores' self.mm_num_times = mm_num_times self.add_state('count', d...
class MRMetrics(Metric): def __init__(self, njoints, jointstype: str='mmm', force_in_meter: bool=True, align_root: bool=True, dist_sync_on_step=True, **kwargs): super().__init__(dist_sync_on_step=dist_sync_on_step) if (jointstype not in ['mmm', 'humanml3d']): raise NotImplementedError...
class UncondMetrics(Metric): full_state_update = True def __init__(self, top_k=3, R_size=32, diversity_times=300, dist_sync_on_step=True, **kwargs): super().__init__(dist_sync_on_step=dist_sync_on_step) self.name = 'fid, kid, and diversity scores' self.top_k = top_k self.R_siz...
class MLP(nn.Module): def __init__(self, cfg, out_dim, is_init): super(MLP, self).__init__() dims = cfg.MODEL.MOTION_DECODER.MLP_DIM n_blk = len(dims) norm = 'none' acti = 'lrelu' layers = [] for i in range((n_blk - 1)): layers += LinearBlock(di...
def ZeroPad1d(sizes): return nn.ConstantPad1d(sizes, 0)
def get_acti_layer(acti='relu', inplace=True): if (acti == 'relu'): return [nn.ReLU(inplace=inplace)] elif (acti == 'lrelu'): return [nn.LeakyReLU(0.2, inplace=inplace)] elif (acti == 'tanh'): return [nn.Tanh()] elif (acti == 'none'): return [] else: assert ...
def get_norm_layer(norm='none', norm_dim=None): if (norm == 'bn'): return [nn.BatchNorm1d(norm_dim)] elif (norm == 'in'): return [nn.InstanceNorm1d(norm_dim, affine=True)] elif (norm == 'adain'): return [AdaptiveInstanceNorm1d(norm_dim)] elif (norm == 'none'): return []...
def get_dropout_layer(dropout=None): if (dropout is not None): return [nn.Dropout(p=dropout)] else: return []
def ConvLayers(kernel_size, in_channels, out_channels, stride=1, pad_type='reflect', use_bias=True): '\n returns a list of [pad, conv] => should be += to some list, then apply sequential\n ' if (pad_type == 'reflect'): pad = nn.ReflectionPad1d elif (pad_type == 'replicate'): pad = nn...
def ConvBlock(kernel_size, in_channels, out_channels, stride=1, pad_type='reflect', dropout=None, norm='none', acti='lrelu', acti_first=False, use_bias=True, inplace=True): '\n returns a list of [pad, conv, norm, acti] or [acti, pad, conv, norm]\n ' layers = ConvLayers(kernel_size, in_channels, out_chan...
def LinearBlock(in_dim, out_dim, dropout=None, norm='none', acti='relu'): use_bias = True layers = [] layers.append(nn.Linear(in_dim, out_dim, bias=use_bias)) layers += get_dropout_layer(dropout) layers += get_norm_layer(norm, norm_dim=out_dim) layers += get_acti_layer(acti) return layers
@contextlib.contextmanager def no_weight_gradients(): global weight_gradients_disabled old = weight_gradients_disabled weight_gradients_disabled = True (yield) weight_gradients_disabled = old
def conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1): if could_use_op(input): return conv2d_gradfix(transpose=False, weight_shape=weight.shape, stride=stride, padding=padding, output_padding=0, dilation=dilation, groups=groups).apply(input, weight, bias) return F.conv2d(inpu...
def conv_transpose2d(input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1): if could_use_op(input): return conv2d_gradfix(transpose=True, weight_shape=weight.shape, stride=stride, padding=padding, output_padding=output_padding, groups=groups, dilation=dilation).apply(input...
def could_use_op(input): if ((not enabled) or (not torch.backends.cudnn.enabled)): return False if (input.device.type != 'cuda'): return False if any((torch.__version__.startswith(x) for x in ['1.7.', '1.8.'])): return True warnings.warn(f'conv2d_gradfix not supported on PyTorc...
def ensure_tuple(xs, ndim): xs = (tuple(xs) if isinstance(xs, (tuple, list)) else ((xs,) * ndim)) return xs
def conv2d_gradfix(transpose, weight_shape, stride, padding, output_padding, dilation, groups): ndim = 2 weight_shape = tuple(weight_shape) stride = ensure_tuple(stride, ndim) padding = ensure_tuple(padding, ndim) output_padding = ensure_tuple(output_padding, ndim) dilation = ensure_tuple(dila...
class SkipTransformerEncoder(nn.Module): def __init__(self, encoder_layer, num_layers, norm=None): super().__init__() self.d_model = encoder_layer.d_model self.num_layers = num_layers self.norm = norm assert ((num_layers % 2) == 1) num_block = ((num_layers - 1) // ...
class SkipTransformerDecoder(nn.Module): def __init__(self, decoder_layer, num_layers, norm=None): super().__init__() self.d_model = decoder_layer.d_model self.num_layers = num_layers self.norm = norm assert ((num_layers % 2) == 1) num_block = ((num_layers - 1) // ...
class Transformer(nn.Module): def __init__(self, d_model=512, nhead=8, num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=2048, dropout=0.1, activation='relu', normalize_before=False, return_intermediate_dec=False): super().__init__() encoder_layer = TransformerEncoderLayer(d_model, nhea...
class TransformerEncoder(nn.Module): def __init__(self, encoder_layer, num_layers, norm=None): super().__init__() self.layers = _get_clones(encoder_layer, num_layers) self.num_layers = num_layers self.norm = norm def forward(self, src, mask: Optional[Tensor]=None, src_key_pad...
class TransformerDecoder(nn.Module): def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False): super().__init__() self.layers = _get_clones(decoder_layer, num_layers) self.num_layers = num_layers self.norm = norm self.return_intermediate = return...
class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='relu', normalize_before=False): super().__init__() self.d_model = d_model self.nhead = nhead self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=d...
class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='relu', normalize_before=False): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) self.multihead_attn = nn.MultiheadAttentio...
def _get_clone(module): return copy.deepcopy(module)
def _get_clones(module, N): return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
def build_transformer(args): return Transformer(d_model=args.hidden_dim, dropout=args.dropout, nhead=args.nheads, dim_feedforward=args.dim_feedforward, num_encoder_layers=args.enc_layers, num_decoder_layers=args.dec_layers, normalize_before=args.pre_norm, return_intermediate_dec=True)
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 remove_padding(tensors, lengths): return [tensor[:tensor_length] for (tensor, tensor_length) in zip(tensors, lengths)]
class AutoParams(nn.Module): def __init__(self, **kargs): try: for param in self.needed_params: if (param in kargs): setattr(self, param, kargs[param]) else: raise ValueError(f'{param} is needed.') except: ...
def freeze_params(module: nn.Module) -> None: '\n Freeze the parameters of this module,\n i.e. do not update them during training\n\n :param module: freeze parameters of this module\n ' for (_, p) in module.named_parameters(): p.requires_grad = False
class Camera(): def __init__(self, *, first_root, mode, is_mesh): camera = bpy.data.objects['Camera'] camera.location.x = 7.36 camera.location.y = (- 6.93) if is_mesh: camera.location.z = 5.6 else: camera.location.z = 5.2 if (mode == 'sequen...
class Data(): def __len__(self): return self.N
def clear_material(material): if material.node_tree: material.node_tree.links.clear() material.node_tree.nodes.clear()
def colored_material_diffuse_BSDF(r, g, b, a=1, roughness=0.127451): materials = bpy.data.materials material = materials.new(name='body') material.use_nodes = True clear_material(material) nodes = material.node_tree.nodes links = material.node_tree.links output = nodes.new(type='ShaderNode...
def colored_material_relection_BSDF(r, g, b, a=1, roughness=0.127451, saturation_factor=1): materials = bpy.data.materials material = materials.new(name='body') material.use_nodes = True nodes = material.node_tree.nodes links = material.node_tree.links output = nodes.new(type='ShaderNodeOutput...
def body_material(r, g, b, a=1, name='body', oldrender=True): if oldrender: material = colored_material_diffuse_BSDF(r, g, b, a=a) else: materials = bpy.data.materials material = materials.new(name=name) material.use_nodes = True nodes = material.node_tree.nodes ...
def colored_material_bsdf(name, **kwargs): materials = bpy.data.materials material = materials.new(name=name) material.use_nodes = True nodes = material.node_tree.nodes diffuse = nodes['Principled BSDF'] inputs = diffuse.inputs settings = DEFAULT_BSDF_SETTINGS.copy() for (key, val) in ...
def floor_mat(name='floor_mat', color=(0.1, 0.1, 0.1, 1), roughness=0.127451): return colored_material_diffuse_BSDF(color[0], color[1], color[2], a=color[3], roughness=roughness)
def plane_mat(): materials = bpy.data.materials material = materials.new(name='plane') material.use_nodes = True clear_material(material) nodes = material.node_tree.nodes links = material.node_tree.links output = nodes.new(type='ShaderNodeOutputMaterial') diffuse = nodes.new(type='Shad...
def plane_mat_uni(): materials = bpy.data.materials material = materials.new(name='plane_uni') material.use_nodes = True clear_material(material) nodes = material.node_tree.nodes links = material.node_tree.links output = nodes.new(type='ShaderNodeOutputMaterial') diffuse = nodes.new(ty...
def prune_begin_end(data, perc): to_remove = int((len(data) * perc)) if (to_remove == 0): return data return data[to_remove:(- to_remove)]
def render_current_frame(path): bpy.context.scene.render.filepath = path bpy.ops.render.render(use_viewport=True, write_still=True)
def render(npydata, frames_folder, *, mode, faces_path, gt=False, exact_frame=None, num=8, downsample=True, canonicalize=True, always_on_floor=False, denoising=True, oldrender=True, jointstype='mmm', res='high', init=True, accelerator='gpu', device=[0]): if init: setup_scene(res=res, denoising=denoising, ...
def get_frameidx(*, mode, nframes, exact_frame, frames_to_keep): if (mode == 'sequence'): frameidx = np.linspace(0, (nframes - 1), frames_to_keep) frameidx = np.round(frameidx).astype(int) frameidx = list(frameidx) elif (mode == 'frame'): index_frame = int((exact_frame * nframe...
def setup_renderer(denoising=True, oldrender=True, accelerator='gpu', device=[0]): bpy.context.scene.render.engine = 'CYCLES' bpy.data.scenes[0].render.engine = 'CYCLES' if (accelerator.lower() == 'gpu'): bpy.context.preferences.addons['cycles'].preferences.compute_device_type = 'CUDA' bpy...
def setup_scene(res='high', denoising=True, oldrender=True, accelerator='gpu', device=[0]): scene = bpy.data.scenes['Scene'] assert (res in ['ultra', 'high', 'med', 'low']) if (res == 'high'): scene.render.resolution_x = 1280 scene.render.resolution_y = 1024 elif (res == 'med'): ...
def mesh_detect(data): if (data.shape[1] > 1000): return True return False
class ndarray_pydata(np.ndarray): def __bool__(self) -> bool: return (len(self) > 0)
def load_numpy_vertices_into_blender(vertices, faces, name, mat): mesh = bpy.data.meshes.new(name) mesh.from_pydata(vertices, [], faces.view(ndarray_pydata)) mesh.validate() obj = bpy.data.objects.new(name, mesh) bpy.context.scene.collection.objects.link(obj) bpy.ops.object.select_all(action='...
def delete_objs(names): if (not isinstance(names, list)): names = [names] bpy.ops.object.select_all(action='DESELECT') for obj in bpy.context.scene.objects: for name in names: if (obj.name.startswith(name) or obj.name.endswith(name)): obj.select_set(True) bp...
class LevelsFilter(logging.Filter): def __init__(self, levels): self.levels = [getattr(logging, level) for level in levels] def filter(self, record): return (record.levelno in self.levels)
class StreamToLogger(object): '\n Fake file-like stream object that redirects writes to a logger instance.\n ' def __init__(self, logger, level): self.logger = logger self.level = level self.linebuf = '' def write(self, buf): for line in buf.rstrip().splitlines(): ...
class TqdmLoggingHandler(logging.Handler): def __init__(self, level=logging.NOTSET): super().__init__(level) def emit(self, record): try: msg = self.format(record) tqdm.tqdm.write(msg) self.flush() except Exception: self.handleError(rec...
def generate_id() -> str: run_gen = shortuuid.ShortUUID(alphabet=list('0123456789abcdefghijklmnopqrstuvwxyz')) return run_gen.random(8)
class Transform(): def collate(self, lst_datastruct): from mld.datasets.utils import collate_tensor_with_padding example = lst_datastruct[0] def collate_or_none(key): if (example[key] is None): return None key_lst = [x[key] for x in lst_datastruct]...
@dataclass class Datastruct(): def __getitem__(self, key): return getattr(self, key) def __setitem__(self, key, value): self.__dict__[key] = value def get(self, key, default=None): return getattr(self, key, default) def __iter__(self): return self.keys() def ke...
def main(): data_root = '../datasets/humanml3d' feastures_path = 'in.npy' animation_save_path = 'in.mp4' fps = 20 mean = np.load(pjoin(data_root, 'Mean.npy')) std = np.load(pjoin(data_root, 'Std.npy')) motion = np.load(feastures_path) motion = ((motion * std) + mean) motion_rec = r...
class IdentityTransform(Transform): def __init__(self, **kwargs): return def Datastruct(self, **kwargs): return IdentityDatastruct(**kwargs) def __repr__(self): return 'IdentityTransform()'
@dataclass class IdentityDatastruct(Datastruct): transforms: IdentityTransform features: Optional[Tensor] = None def __post_init__(self): self.datakeys = ['features'] def __len__(self): return len(self.rfeats)
class Joints2Jfeats(nn.Module): def __init__(self, path: Optional[str]=None, normalization: bool=False, eps: float=1e-12, **kwargs) -> None: if (normalization and (path is None)): raise TypeError('You should provide a path if normalization is on.') super().__init__() self.norm...
class Rots2Joints(nn.Module): def __init__(self, path: Optional[str]=None, normalization: bool=False, eps: float=1e-12, **kwargs) -> None: if (normalization and (path is None)): raise TypeError('You should provide a path if normalization is on.') super().__init__() self.normal...
class Rots2Rfeats(nn.Module): def __init__(self, path: Optional[str]=None, normalization: bool=False, eps: float=1e-12, **kwargs) -> None: if (normalization and (path is None)): raise TypeError('You should provide a path if normalization is on.') super().__init__() self.normal...
class XYZTransform(Transform): def __init__(self, joints2jfeats: Joints2Jfeats, **kwargs): self.joints2jfeats = joints2jfeats def Datastruct(self, **kwargs): return XYZDatastruct(_joints2jfeats=self.joints2jfeats, transforms=self, **kwargs) def __repr__(self): return 'XYZTransfo...
@dataclass class XYZDatastruct(Datastruct): transforms: XYZTransform _joints2jfeats: Joints2Jfeats features: Optional[Tensor] = None joints_: Optional[Tensor] = None jfeats_: Optional[Tensor] = None def __post_init__(self): self.datakeys = ['features', 'joints_', 'jfeats_'] if...
def load_example_input(txt_path): file = open(txt_path, 'r') Lines = file.readlines() count = 0 (texts, lens) = ([], []) for line in Lines: count += 1 s = line.strip() s_l = s.split(' ')[0] s_t = s[(len(s_l) + 1):] lens.append(int(s_l)) texts.append(...
def render_batch(npy_dir, execute_python='./scripts/visualize_motion.sh', mode='sequence'): os.system(f'{execute_python} {npy_dir} {mode}')
def render(execute_python, npy_path, jointtype, cfg_path): export_scripts = 'render.py' os.system(f'{execute_python} --background --python {export_scripts} -- --cfg={cfg_path} --npy={npy_path} --joint_type={jointtype}') fig_path = Path(str(npy_path).replace('.npy', '.png')) return fig_path
def export_fbx_hand(pkl_path): input = pkl_path output = pkl_path.replace('.pkl', '.fbx') execute_python = '/apdcephfs/share_1227775/shingxchen/libs/blender_bpy/blender-2.93.2-linux-x64/blender' export_scripts = './scripts/fbx_output_smplx.py' os.system(f'{execute_python} -noaudio --background --p...
def export_fbx(pkl_path): input = pkl_path output = pkl_path.replace('.pkl', '.fbx') execute_python = '/apdcephfs/share_1227775/shingxchen/libs/blender_bpy/blender-2.93.2-linux-x64/blender' export_scripts = './scripts/fbx_output.py' os.system(f'{execute_python} -noaudio --background --python {expo...
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 fixseed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed)
def get_root_idx(joinstype): return root_joints[joinstype]
def create_logger(cfg, phase='train'): root_output_dir = Path(cfg.FOLDER) if (not root_output_dir.exists()): print('=> creating {}'.format(root_output_dir)) root_output_dir.mkdir() cfg_name = cfg.NAME model = cfg.model.model_type cfg_name = os.path.basename(cfg_name).split('.')[0] ...
@rank_zero_only def config_logger(final_output_dir, time_str, phase, head): log_file = '{}_{}_{}.log'.format('log', time_str, phase) final_log_file = (final_output_dir / log_file) logging.basicConfig(filename=str(final_log_file)) logger = logging.getLogger() logger.setLevel(logging.INFO) conso...
@rank_zero_only def new_dir(cfg, phase, time_str, final_output_dir): cfg.TIME = str(time_str) if (os.path.exists(final_output_dir) and (cfg.TRAIN.RESUME is None) and (not cfg.DEBUG)): file_list = sorted(os.listdir(final_output_dir), reverse=True) for item in file_list: if item.ends...
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 cfg_mean_nsamples_resolution(cfg): if (cfg.mean and (cfg.number_of_samples > 1)): logger.error('All the samples will be the mean.. cfg.number_of_samples=1 will be forced.') cfg.number_of_samples = 1 return (cfg.number_of_samples == 1)
def get_path(sample_path: Path, is_amass: bool, gender: str, split: str, onesample: bool, mean: bool, fact: float): extra_str = (('_mean' if mean else '') if onesample else '_multi') fact_str = ('' if (fact == 1) else f'{fact}_') gender_str = ((gender + '_') if is_amass else '') path = (sample_path / ...
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