id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
26,717 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Load config file. :param g: generative image instance :type g: GenerativeImage :param config: config JSON file :type config: (io.IOBase & file) :return: None |
26,718 | import os
import sys
import codecs
Failed = 0
TEST_NUMBER = len(FILES.keys())
The provided code snippet includes necessary dependencies for implementing the `print_result` function. Write a Python function `def print_result(failed=False)` to solve the following problem:
Print final result. :param failed: failed flag :... | Print final result. :param failed: failed flag :type failed: bool :return: None |
26,719 | from samila import *
import random
import math
def f1(x, y):
result = random.uniform(-1, 1) * x**2 - math.sin(y**2) + abs(y-x)
return result | null |
26,720 | from samila import *
import random
import math
def f2(x, y):
result = random.uniform(-1, 1) * y**3 - math.cos(x**2) + 2*x
return result | null |
26,721 | from t2m.data.dataset import Text2MotionDatasetV2, collate_fn
from t2m.utils.word_vectorizer import WordVectorizer
import numpy as np
from os.path import join as pjoin
from torch.utils.data import DataLoader
from t2m.utils.get_opt import get_opt
def get_dataset_motion_loader(opt_path, batch_size, device):
opt = ge... | null |
26,722 | import torch
from data_loaders.humanml.networks.modules import *
from data_loaders.humanml.networks.trainers import CompTrainerV6
from torch.utils.data import Dataset, DataLoader
from os.path import join as pjoin
from tqdm import tqdm
from utils import dist_util
def build_models(opt):
if opt.text_enc_mod == 'bigru... | null |
26,723 | from torch.utils.data import DataLoader, Dataset
from data_loaders.humanml.utils.get_opt import get_opt
from data_loaders.humanml.motion_loaders.comp_v6_model_dataset import CompMDMGeneratedDataset
from data_loaders.humanml.utils.word_vectorizer import WordVectorizer
import numpy as np
from torch.utils.data._utils.coll... | null |
26,724 | from torch.utils.data import DataLoader, Dataset
from data_loaders.humanml.utils.get_opt import get_opt
from data_loaders.humanml.motion_loaders.comp_v6_model_dataset import CompMDMGeneratedDataset
from data_loaders.humanml.utils.word_vectorizer import WordVectorizer
import numpy as np
from torch.utils.data._utils.coll... | null |
26,725 | from data_loaders.humanml.networks.modules import *
from data_loaders.humanml.utils.word_vectorizer import POS_enumerator
from os.path import join as pjoin
def build_models(opt):
movement_enc = MovementConvEncoder(opt.dim_pose-4, opt.dim_movement_enc_hidden, opt.dim_movement_latent)
text_enc = TextEncoderBiGRU... | null |
26,726 | from data_loaders.humanml.networks.modules import *
from data_loaders.humanml.utils.word_vectorizer import POS_enumerator
from os.path import join as pjoin
def build_evaluators(opt):
movement_enc = MovementConvEncoder(opt['dim_pose']-4, opt['dim_movement_enc_hidden'], opt['dim_movement_latent'])
text_enc = Tex... | null |
26,727 | import torch
import torch.nn as nn
import numpy as np
import time
import math
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import torch.nn.functional as F
def init_weight(m):
if isinstance(m, nn.Conv1d) or isinstance(m, nn.Linear) or isinstance(m, nn.ConvTranspose1d):
nn.init.xa... | null |
26,728 | import torch
import torch.nn as nn
import numpy as np
import time
import math
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import torch.nn.functional as F
def reparameterize(mu, logvar):
s_var = logvar.mul(0.5).exp_()
eps = s_var.data.new(s_var.size()).normal_()
return eps.mul(s... | null |
26,729 | import torch
import torch.nn as nn
import numpy as np
import time
import math
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import torch.nn.functional as F
def positional_encoding(batch_size, dim, pos):
assert batch_size == pos.shape[0]
positions_enc = np.array([
[pos[j] / np... | null |
26,730 | import torch
import torch.nn as nn
import numpy as np
import time
import math
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import torch.nn.functional as F
def get_padding_mask(batch_size, seq_len, cap_lens):
cap_lens = cap_lens.data.tolist()
mask_2d = torch.ones((batch_size, seq_len... | null |
26,731 | import torch
import numpy as np
def qinv(q):
assert q.shape[-1] == 4, 'q must be a tensor of shape (*, 4)'
mask = torch.ones_like(q)
mask[..., 1:] = -mask[..., 1:]
return q * mask
def qinv_np(q):
assert q.shape[-1] == 4, 'q must be a tensor of shape (*, 4)'
return qinv(torch.from_numpy(q).float... | null |
26,732 | import torch
import numpy as np
def qrot(q, v):
"""
Rotate vector(s) v about the rotation described by quaternion(s) q.
Expects a tensor of shape (*, 4) for q and a tensor of shape (*, 3) for v,
where * denotes any number of dimensions.
Returns a tensor of shape (*, 3).
"""
assert q.shape[-1... | null |
26,733 | import torch
import numpy as np
def qeuler(q, order, epsilon=0, deg=True):
"""
Convert quaternion(s) q to Euler angles.
Expects a tensor of shape (*, 4), where * denotes any number of dimensions.
Returns a tensor of shape (*, 3).
"""
assert q.shape[-1] == 4
original_shape = list(q.shape)
... | null |
26,734 | import torch
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `qfix` function. Write a Python function `def qfix(q)` to solve the following problem:
Enforce quaternion continuity across the time dimension by selecting the representation (q or -q) with minimal distance (... | Enforce quaternion continuity across the time dimension by selecting the representation (q or -q) with minimal distance (or, equivalently, maximal dot product) between two consecutive frames. Expects a tensor of shape (L, J, 4), where L is the sequence length and J is the number of joints. Returns a tensor of the same ... |
26,735 | import torch
import numpy as np
def qmul(q, r):
"""
Multiply quaternion(s) q with quaternion(s) r.
Expects two equally-sized tensors of shape (*, 4), where * denotes any number of dimensions.
Returns q*r as a tensor of shape (*, 4).
"""
assert q.shape[-1] == 4
assert r.shape[-1] == 4
ori... | Convert Euler angles to quaternions. |
26,736 | import torch
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `expmap_to_quaternion` function. Write a Python function `def expmap_to_quaternion(e)` to solve the following problem:
Convert axis-angle rotations (aka exponential maps) to quaternions. Stable formula from "... | Convert axis-angle rotations (aka exponential maps) to quaternions. Stable formula from "Practical Parameterization of Rotations Using the Exponential Map". Expects a tensor of shape (*, 3), where * denotes any number of dimensions. Returns a tensor of shape (*, 4). |
26,737 | import torch
import numpy as np
def qmul_np(q, r):
q = torch.from_numpy(q).contiguous().float()
r = torch.from_numpy(r).contiguous().float()
return qmul(q, r).numpy()
The provided code snippet includes necessary dependencies for implementing the `euler_to_quaternion` function. Write a Python function `def ... | Convert Euler angles to quaternions. |
26,738 | import torch
import numpy as np
def quaternion_to_matrix_np(quaternions):
def quaternion_to_cont6d_np(quaternions):
rotation_mat = quaternion_to_matrix_np(quaternions)
cont_6d = np.concatenate([rotation_mat[..., 0], rotation_mat[..., 1]], axis=-1)
return cont_6d | null |
26,739 | import torch
import numpy as np
def quaternion_to_matrix(quaternions):
"""
Convert rotations given as quaternions to rotation matrices.
Args:
quaternions: quaternions with real part first,
as tensor of shape (..., 4).
Returns:
Rotation matrices as tensor of shape (..., 3, 3).... | null |
26,740 | import torch
import numpy as np
def cont6d_to_matrix(cont6d):
assert cont6d.shape[-1] == 6, "The last dimension must be 6"
x_raw = cont6d[..., 0:3]
y_raw = cont6d[..., 3:6]
x = x_raw / torch.norm(x_raw, dim=-1, keepdim=True)
z = torch.cross(x, y_raw, dim=-1)
z = z / torch.norm(z, dim=-1, keepdim... | null |
26,741 | import torch
import numpy as np
def qinv(q):
assert q.shape[-1] == 4, 'q must be a tensor of shape (*, 4)'
mask = torch.ones_like(q)
mask[..., 1:] = -mask[..., 1:]
return q * mask
def qnormalize(q):
assert q.shape[-1] == 4, 'q must be a tensor of shape (*, 4)'
return q / torch.norm(q, dim=-1, ke... | q0: starting quaternion q1: ending quaternion t: array of points along the way Returns: Tensor of Slerps: t.shape + q0.shape |
26,742 | import torch
import numpy as np
def qbetween(v0, v1):
'''
find the quaternion used to rotate v0 to v1
'''
assert v0.shape[-1] == 3, 'v0 must be of the shape (*, 3)'
assert v1.shape[-1] == 3, 'v1 must be of the shape (*, 3)'
v = torch.cross(v0, v1)
w = torch.sqrt((v0 ** 2).sum(dim=-1, keepdim... | find the quaternion used to rotate v0 to v1 |
26,743 | import torch
import numpy as np
def lerp(p0, p1, t):
if not isinstance(t, torch.Tensor):
t = torch.Tensor([t])
new_shape = t.shape + p0.shape
new_view_t = t.shape + torch.Size([1] * len(p0.shape))
new_view_p = torch.Size([1] * len(t.shape)) + p0.shape
p0 = p0.view(new_view_p).expand(new_sh... | null |
26,744 | from os.path import join as pjoin
from data_loaders.humanml.common.skeleton import Skeleton
import numpy as np
import os
from data_loaders.humanml.common.quaternion import *
from data_loaders.humanml.utils.paramUtil import *
import torch
from tqdm import tqdm
class Skeleton(object):
def __init__(self, offset, kine... | Get Foot Contacts |
26,745 | from os.path import join as pjoin
from data_loaders.humanml.common.skeleton import Skeleton
import numpy as np
import os
from data_loaders.humanml.common.quaternion import *
from data_loaders.humanml.utils.paramUtil import *
import torch
from tqdm import tqdm
def uniform_skeleton(positions, target_offset):
src_skel... | Uniform Skeleton |
26,746 | from os.path import join as pjoin
from data_loaders.humanml.common.skeleton import Skeleton
import numpy as np
import os
from data_loaders.humanml.common.quaternion import *
from data_loaders.humanml.utils.paramUtil import *
import torch
from tqdm import tqdm
def recover_root_rot_pos(data):
rot_vel = data[..., 0]
... | null |
26,747 | from os.path import join as pjoin
from data_loaders.humanml.common.skeleton import Skeleton
import numpy as np
import os
from data_loaders.humanml.common.quaternion import *
from data_loaders.humanml.utils.paramUtil import *
import torch
from tqdm import tqdm
def recover_root_rot_pos(data):
rot_vel = data[..., 0]
... | null |
26,748 | from os.path import join as pjoin
from data_loaders.humanml.common.skeleton import Skeleton
import numpy as np
import os
from data_loaders.humanml.common.quaternion import *
from data_loaders.humanml.utils.paramUtil import *
import torch
from tqdm import tqdm
def recover_root_rot_pos(data):
rot_vel = data[..., 0]
... | Add Y-axis rotation to local joints |
26,749 | import os
import numpy as np
from PIL import Image
from data_loaders.humanml.utils import paramUtil
import math
import time
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
def mkdir(path):
if not os.path.exists(path):
os.makedirs(path) | null |
26,750 | import os
import numpy as np
from PIL import Image
from data_loaders.humanml.utils import paramUtil
import math
import time
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
def save_logfile(log_loss, save_path):
with open(save_path, 'wt') as f:
for k, v in log_loss.items():
... | null |
26,751 | import os
import numpy as np
from PIL import Image
from data_loaders.humanml.utils import paramUtil
import math
import time
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
def print_current_loss(start_time, niter_state, losses, epoch=None, sub_epoch=None,
inner_iter=Non... | null |
26,752 | import os
import numpy as np
from PIL import Image
from data_loaders.humanml.utils import paramUtil
import math
import time
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
def print_current_loss_decomp(start_time, niter_state, total_niters, losses, epoch=None, inner_iter=None):
def as_mi... | null |
26,753 | import os
import numpy as np
from PIL import Image
from data_loaders.humanml.utils import paramUtil
import math
import time
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
def compose_gif_img_list(img_list, fp_out, duration):
img, *imgs = [Image.fromarray(np.array(image)) for image in img... | null |
26,754 | import os
import numpy as np
from PIL import Image
from data_loaders.humanml.utils import paramUtil
import math
import time
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
def save_image(image_numpy, image_path):
img_pil = Image.fromarray(image_numpy)
img_pil.save(image_path)
def save... | null |
26,755 | import os
import numpy as np
from PIL import Image
from data_loaders.humanml.utils import paramUtil
import math
import time
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
def save_image(image_numpy, image_path):
def save_images_test(visuals, image_path, from_name, to_name):
if not os.pat... | null |
26,756 | import os
import numpy as np
from PIL import Image
from data_loaders.humanml.utils import paramUtil
import math
import time
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
def compose_image(img_list, col, row, img_size):
to_image = Image.new('RGB', (col * img_size[0], row * img_size[1]))
... | null |
26,757 | import os
import numpy as np
from PIL import Image
from data_loaders.humanml.utils import paramUtil
import math
import time
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
def list_cut_average(ll, intervals):
if intervals == 1:
return ll
bins = math.ceil(len(ll) * 1.0 / interva... | null |
26,758 | import os
import numpy as np
from PIL import Image
from data_loaders.humanml.utils import paramUtil
import math
import time
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
def motion_temporal_filter(motion, sigma=1):
motion = motion.reshape(motion.shape[0], -1)
# print(motion.shape)
... | null |
26,759 | import math
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation, FFMpegFileWriter
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import mpl_toolkits.mplot3d.axes3d as p3
from textwrap import wrap
def list_c... | null |
26,760 | import math
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation, FFMpegFileWriter
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import mpl_toolkits.mplot3d.axes3d as p3
from textwrap import wrap
def plot_3... | null |
26,761 | import numpy as np
from scipy import linalg
def euclidean_distance_matrix(matrix1, matrix2):
"""
Params:
-- matrix1: N1 x D
-- matrix2: N2 x D
Returns:
-- dist: N1 x N2
dist[i, j] == distance(matrix1[i], matrix2[j])
"""
assert matrix1.shape[1] == matrix2.shape... | null |
26,762 | import numpy as np
from scipy import linalg
def calculate_matching_score(embedding1, embedding2, sum_all=False):
assert len(embedding1.shape) == 2
assert embedding1.shape[0] == embedding2.shape[0]
assert embedding1.shape[1] == embedding2.shape[1]
dist = linalg.norm(embedding1 - embedding2, axis=1)
... | null |
26,763 | import numpy as np
from scipy import linalg
The provided code snippet includes necessary dependencies for implementing the `calculate_activation_statistics` function. Write a Python function `def calculate_activation_statistics(activations)` to solve the following problem:
Params: -- activation: num_samples x dim_feat... | Params: -- activation: num_samples x dim_feat Returns: -- mu: dim_feat -- sigma: dim_feat x dim_feat |
26,764 | import numpy as np
from scipy import linalg
def calculate_diversity(activation, diversity_times):
assert len(activation.shape) == 2
assert activation.shape[0] > diversity_times
num_samples = activation.shape[0]
first_indices = np.random.choice(num_samples, diversity_times, replace=False)
second_in... | null |
26,765 | import numpy as np
from scipy import linalg
def calculate_multimodality(activation, multimodality_times):
assert len(activation.shape) == 3
assert activation.shape[1] > multimodality_times
num_per_sent = activation.shape[1]
first_dices = np.random.choice(num_per_sent, multimodality_times, replace=Fals... | null |
26,766 | import numpy as np
from scipy import linalg
The provided code snippet includes necessary dependencies for implementing the `calculate_frechet_distance` function. Write a Python function `def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6)` to solve the following problem:
Numpy implementation of the Frec... | Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Stable version by Dougal J. Sutherland. Params: -- mu1 : Numpy array containing the activations of a layer of the ... |
26,767 | import os
from tqdm import tqdm
import numpy as np
import pickle as pkl
import utils.rotation_conversions as geometry
import torch
from .dataset import Dataset
def get_z(cam_s, cam_pos, joints, img_size, flength):
"""
Solves for the depth offset of the model to approx. orth with persp camera.
"""
# Tran... | null |
26,768 | import copy
import functools
import os
import time
from types import SimpleNamespace
import numpy as np
import blobfile as bf
import torch
from torch.optim import AdamW
from diffusion import logger
from utils import dist_util
from diffusion.fp16_util import MixedPrecisionTrainer
from diffusion.resample import LossAware... | Parse filenames of the form path/to/modelNNNNNN.pt, where NNNNNN is the checkpoint's number of steps. |
26,769 | import copy
import functools
import os
import time
from types import SimpleNamespace
import numpy as np
import blobfile as bf
import torch
from torch.optim import AdamW
from diffusion import logger
from utils import dist_util
from diffusion.fp16_util import MixedPrecisionTrainer
from diffusion.resample import LossAware... | null |
26,770 | import copy
import functools
import os
import time
from types import SimpleNamespace
import numpy as np
import blobfile as bf
import torch
from torch.optim import AdamW
from diffusion import logger
from utils import dist_util
from diffusion.fp16_util import MixedPrecisionTrainer
from diffusion.resample import LossAware... | null |
26,771 | import copy
import functools
import os
import time
from types import SimpleNamespace
import numpy as np
import blobfile as bf
import torch
from torch.optim import AdamW
from diffusion import logger
from utils import dist_util
from diffusion.fp16_util import MixedPrecisionTrainer
from diffusion.resample import LossAware... | null |
26,772 | import numpy as np
import torch as th
import torch.nn as nn
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from diffusion import logger
The provided code snippet includes necessary dependencies for implementing the `convert_module_to_f16` function. Write a Python function `def convert_module... | Convert primitive modules to float16. |
26,773 | import numpy as np
import torch as th
import torch.nn as nn
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from diffusion import logger
The provided code snippet includes necessary dependencies for implementing the `convert_module_to_f32` function. Write a Python function `def convert_module... | Convert primitive modules to float32, undoing convert_module_to_f16(). |
26,774 | import numpy as np
import torch as th
import torch.nn as nn
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from diffusion import logger
def param_grad_or_zeros(param):
if param.grad is not None:
return param.grad.data.detach()
else:
return th.zeros_like(param)
The pro... | Copy the gradients from the model parameters into the master parameters from make_master_params(). |
26,775 | import numpy as np
import torch as th
import torch.nn as nn
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from diffusion import logger
def unflatten_master_params(param_group, master_param):
return _unflatten_dense_tensors(master_param, [param for (_, param) in param_group])
The provide... | Copy the master parameter data back into the model parameters. |
26,776 | import numpy as np
import torch as th
import torch.nn as nn
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from diffusion import logger
def unflatten_master_params(param_group, master_param):
return _unflatten_dense_tensors(master_param, [param for (_, param) in param_group])
def master_... | null |
26,777 | import numpy as np
import torch as th
import torch.nn as nn
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from diffusion import logger
def make_master_params(param_groups_and_shapes):
"""
Copy model parameters into a (differently-shaped) list of full-precision
parameters.
"""... | null |
26,778 | import numpy as np
import torch as th
import torch.nn as nn
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from diffusion import logger
def zero_master_grads(master_params):
for param in master_params:
param.grad = None | null |
26,779 | import numpy as np
import torch as th
import torch.nn as nn
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from diffusion import logger
def zero_grad(model_params):
for param in model_params:
# Taken from https://pytorch.org/docs/stable/_modules/torch/optim/optimizer.html#Optimiz... | null |
26,780 | import numpy as np
import torch as th
import torch.nn as nn
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from diffusion import logger
def check_overflow(value):
return (value == float("inf")) or (value == -float("inf")) or (value != value) | null |
26,781 | import numpy as np
import torch as th
The provided code snippet includes necessary dependencies for implementing the `normal_kl` function. Write a Python function `def normal_kl(mean1, logvar1, mean2, logvar2)` to solve the following problem:
Compute the KL divergence between two gaussians. Shapes are automatically br... | Compute the KL divergence between two gaussians. Shapes are automatically broadcasted, so batches can be compared to scalars, among other use cases. |
26,782 | import numpy as np
import torch as th
def approx_standard_normal_cdf(x):
"""
A fast approximation of the cumulative distribution function of the
standard normal.
"""
return 0.5 * (1.0 + th.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * th.pow(x, 3))))
The provided code snippet includes necessary depen... | Compute the log-likelihood of a Gaussian distribution discretizing to a given image. :param x: the target images. It is assumed that this was uint8 values, rescaled to the range [-1, 1]. :param means: the Gaussian mean Tensor. :param log_scales: the Gaussian log stddev Tensor. :return: a tensor like x of log probabilit... |
26,783 | import enum
import math
import numpy as np
import torch
import torch as th
from copy import deepcopy
from diffusion.nn import mean_flat, sum_flat
from diffusion.losses import normal_kl, discretized_gaussian_log_likelihood
from data_loaders.humanml.scripts import motion_process
The provided code snippet includes necess... | Extract values from a 1-D numpy array for a batch of indices. :param arr: the 1-D numpy array. :param timesteps: a tensor of indices into the array to extract. :param broadcast_shape: a larger shape of K dimensions with the batch dimension equal to the length of timesteps. :return: a tensor of shape [batch_size, 1, ...... |
26,784 | from abc import ABC, abstractmethod
import numpy as np
import torch as th
import torch.distributed as dist
class UniformSampler(ScheduleSampler):
def __init__(self, diffusion):
self.diffusion = diffusion
self._weights = np.ones([diffusion.num_timesteps])
def weights(self):
return self._w... | Create a ScheduleSampler from a library of pre-defined samplers. :param name: the name of the sampler. :param diffusion: the diffusion object to sample for. |
26,785 | import math
import torch as th
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `conv_nd` function. Write a Python function `def conv_nd(dims, *args, **kwargs)` to solve the following problem:
Create a 1D, 2D, or 3D convolution module.
Here is the function:
def con... | Create a 1D, 2D, or 3D convolution module. |
26,786 | import math
import torch as th
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `linear` function. Write a Python function `def linear(*args, **kwargs)` to solve the following problem:
Create a linear module.
Here is the function:
def linear(*args, **kwargs):
"... | Create a linear module. |
26,787 | import math
import torch as th
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `avg_pool_nd` function. Write a Python function `def avg_pool_nd(dims, *args, **kwargs)` to solve the following problem:
Create a 1D, 2D, or 3D average pooling module.
Here is the functi... | Create a 1D, 2D, or 3D average pooling module. |
26,788 | import math
import torch as th
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `update_ema` function. Write a Python function `def update_ema(target_params, source_params, rate=0.99)` to solve the following problem:
Update target parameters to be closer to those of ... | Update target parameters to be closer to those of source parameters using an exponential moving average. :param target_params: the target parameter sequence. :param source_params: the source parameter sequence. :param rate: the EMA rate (closer to 1 means slower). |
26,789 | import math
import torch as th
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `zero_module` function. Write a Python function `def zero_module(module)` to solve the following problem:
Zero out the parameters of a module and return it.
Here is the function:
def ze... | Zero out the parameters of a module and return it. |
26,790 | import math
import torch as th
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `scale_module` function. Write a Python function `def scale_module(module, scale)` to solve the following problem:
Scale the parameters of a module and return it.
Here is the function:
... | Scale the parameters of a module and return it. |
26,791 | import math
import torch as th
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `mean_flat` function. Write a Python function `def mean_flat(tensor)` to solve the following problem:
Take the mean over all non-batch dimensions.
Here is the function:
def mean_flat(te... | Take the mean over all non-batch dimensions. |
26,792 | import math
import torch as th
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `sum_flat` function. Write a Python function `def sum_flat(tensor)` to solve the following problem:
Take the sum over all non-batch dimensions.
Here is the function:
def sum_flat(tensor... | Take the sum over all non-batch dimensions. |
26,793 | import math
import torch as th
import torch.nn as nn
class GroupNorm32(nn.GroupNorm):
def forward(self, x):
return super().forward(x.float()).type(x.dtype)
The provided code snippet includes necessary dependencies for implementing the `normalization` function. Write a Python function `def normalization(cha... | Make a standard normalization layer. :param channels: number of input channels. :return: an nn.Module for normalization. |
26,794 | import math
import torch as th
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `timestep_embedding` function. Write a Python function `def timestep_embedding(timesteps, dim, max_period=10000)` to solve the following problem:
Create sinusoidal timestep embeddings. :p... | Create sinusoidal timestep embeddings. :param timesteps: a 1-D Tensor of N indices, one per batch element. These may be fractional. :param dim: the dimension of the output. :param max_period: controls the minimum frequency of the embeddings. :return: an [N x dim] Tensor of positional embeddings. |
26,795 | import math
import torch as th
import torch.nn as nn
class CheckpointFunction(th.autograd.Function):
def forward(ctx, run_function, length, *args):
ctx.run_function = run_function
ctx.input_length = length
ctx.save_for_backward(*args)
with th.no_grad():
output_tensors = c... | Evaluate a function without caching intermediate activations, allowing for reduced memory at the expense of extra compute in the backward pass. :param func: the function to evaluate. :param inputs: the argument sequence to pass to `func`. :param params: a sequence of parameters `func` depends on but does not explicitly... |
26,796 | import os
import sys
import shutil
import os.path as osp
import json
import time
import datetime
import tempfile
import warnings
from collections import defaultdict
from contextlib import contextmanager
def logkv(key, val):
"""
Log a value of some diagnostic
Call this once for each diagnostic quantity, each... | Log a dictionary of key-value pairs |
26,797 | import os
import sys
import shutil
import os.path as osp
import json
import time
import datetime
import tempfile
import warnings
from collections import defaultdict
from contextlib import contextmanager
def get_current():
if Logger.CURRENT is None:
_configure_default_logger()
return Logger.CURRENT
The ... | Write all of the diagnostics from the current iteration |
26,798 | import os
import sys
import shutil
import os.path as osp
import json
import time
import datetime
import tempfile
import warnings
from collections import defaultdict
from contextlib import contextmanager
def get_current():
def getkvs():
return get_current().name2val | null |
26,799 | import os
import sys
import shutil
import os.path as osp
import json
import time
import datetime
import tempfile
import warnings
from collections import defaultdict
from contextlib import contextmanager
DEBUG = 10
def log(*args, level=INFO):
"""
Write the sequence of args, with no separators, to the console and... | null |
26,800 | import os
import sys
import shutil
import os.path as osp
import json
import time
import datetime
import tempfile
import warnings
from collections import defaultdict
from contextlib import contextmanager
INFO = 20
def log(*args, level=INFO):
"""
Write the sequence of args, with no separators, to the console and ... | null |
26,801 | import os
import sys
import shutil
import os.path as osp
import json
import time
import datetime
import tempfile
import warnings
from collections import defaultdict
from contextlib import contextmanager
ERROR = 40
def log(*args, level=INFO):
"""
Write the sequence of args, with no separators, to the console and... | null |
26,802 | import os
import sys
import shutil
import os.path as osp
import json
import time
import datetime
import tempfile
import warnings
from collections import defaultdict
from contextlib import contextmanager
def get_current():
if Logger.CURRENT is None:
_configure_default_logger()
return Logger.CURRENT
The ... | Set logging threshold on current logger. |
26,803 | import os
import sys
import shutil
import os.path as osp
import json
import time
import datetime
import tempfile
import warnings
from collections import defaultdict
from contextlib import contextmanager
def get_current():
if Logger.CURRENT is None:
_configure_default_logger()
return Logger.CURRENT
def ... | null |
26,804 | import os
import sys
import shutil
import os.path as osp
import json
import time
import datetime
import tempfile
import warnings
from collections import defaultdict
from contextlib import contextmanager
def profile_kv(scopename):
logkey = "wait_" + scopename
tstart = time.time()
try:
yield
final... | Usage: @profile("my_func") def my_func(): code |
26,805 | import os
import sys
import shutil
import os.path as osp
import json
import time
import datetime
import tempfile
import warnings
from collections import defaultdict
from contextlib import contextmanager
def warn(*args):
log(*args, level=WARN)
The provided code snippet includes necessary dependencies for implementi... | Copied from: https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/common/mpi_util.py#L110 Perform a weighted average over dicts that are each on a different node Input: local_name2valcount: dict mapping key -> (value, count) Returns: key -> mean |
26,806 | import os
import sys
import shutil
import os.path as osp
import json
import time
import datetime
import tempfile
import warnings
from collections import defaultdict
from contextlib import contextmanager
def log(*args, level=INFO):
"""
Write the sequence of args, with no separators, to the console and output fil... | null |
26,807 | import os
import sys
import shutil
import os.path as osp
import json
import time
import datetime
import tempfile
import warnings
from collections import defaultdict
from contextlib import contextmanager
class Logger(object):
def __init__(self, dir, output_formats, comm=None):
def logkv(self, key, val):
d... | null |
26,808 | import numpy as np
import torch
from utils.rotation_conversions import rotation_6d_to_matrix, matrix_to_euler_angles
from visualize.simplify_loc2rot import joints2smpl
JOINT_MAP = [
'Hips',
'LeftUpLeg',
'RightUpLeg',
'Spine',
'LeftLeg',
'RightLeg',
'Spine1',
'LeftFoot',
'RightFoot',
... | Utility function to convert model output to a representation used by HumanIK skeletons in Maya and Motion Builder by converting joint positions to joint rotations in degrees. Based on visualize.vis_utils.npy2obj :param motions: numpy array containing MDM model output [num_reps, num_joints, num_params (xyz), num_frames ... |
26,809 | import torch
import torch.nn.functional as F
from visualize.joints2smpl.src import config
def gmof(x, sigma):
"""
Geman-McClure error function
"""
x_squared = x ** 2
sigma_squared = sigma ** 2
return (sigma_squared * x_squared) / (sigma_squared + x_squared)
def angle_prior(pose):
"""
Ang... | Loss function for body fitting |
26,810 | import torch
import torch.nn.functional as F
from visualize.joints2smpl.src import config
def perspective_projection(points, rotation, translation,
focal_length, camera_center):
"""
This function computes the perspective projection of a set of points.
Input:
points (bs, N,... | Loss function for camera optimization. |
26,811 | import torch
import torch.nn.functional as F
from visualize.joints2smpl.src import config
def gmof(x, sigma):
"""
Geman-McClure error function
"""
x_squared = x ** 2
sigma_squared = sigma ** 2
return (sigma_squared * x_squared) / (sigma_squared + x_squared)
def angle_prior(pose):
"""
Ang... | Loss function for body fitting |
26,812 | import torch
import torch.nn.functional as F
from visualize.joints2smpl.src import config
The provided code snippet includes necessary dependencies for implementing the `camera_fitting_loss_3d` function. Write a Python function `def camera_fitting_loss_3d(model_joints, camera_t, camera_t_est, ... | Loss function for camera optimization. |
26,813 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import sys
import os
import time
import pickle
import numpy as np
import torch
import torch.nn as nn
class SMPLifyAnglePrior(nn.Module):
def __init__(self, dtype=torch.float32, **kwargs):
super(SMPLi... | null |
26,814 | import torch
import os, sys
import pickle
import smplx
import numpy as np
from customloss import (camera_fitting_loss,
body_fitting_loss,
camera_fitting_loss_3d,
body_fitting_loss_3d,
)
from prior import MaxMixturePrior
f... | Initialize the camera translation via triangle similarity, by using the torso joints . :param model_joints: SMPL model with pre joints :param j3d: 25x3 array of Kinect Joints :returns: 3D vector corresponding to the estimated camera translation |
26,815 | import os
import subprocess
from typing import Any, List, Optional
from argparse import Namespace
import torch
from cog import BasePredictor, Input, Path, BaseModel
import data_loaders.humanml.utils.paramUtil as paramUtil
from data_loaders.get_data import get_dataset_loader
from data_loaders.humanml.scripts.motion_proc... | null |
26,816 | from utils.fixseed import fixseed
import os
import numpy as np
import torch
from utils.parser_util import generate_args
from utils.model_util import create_model_and_diffusion, load_model_wo_clip
from utils import dist_util
from model.cfg_sampler import ClassifierFreeSampleModel
from data_loaders.get_data import get_da... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.