id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
162,541
import os import math import random import numpy as np from typing import Optional from torchtyping import TensorType from plyfile import PlyData, PlyElement import torch from torch import nn import torch.nn.functional as F from kornia.geometry.conversions import ( quaternion_to_rotation_matrix, ) from diff_gaussian_rasterization import ( GaussianRasterizationSettings, GaussianRasterizer, ) from simple_knn._C import distCUDA2 from ..shared_utils.sh_utils import eval_sh, SH2RGB, RGB2SH from ..mesh_processer.mesh import Mesh, PointCloud from ..mesh_processer.mesh_utils import construct_list_of_gs_attributes, write_gs_ply, read_gs_ply The provided code snippet includes necessary dependencies for implementing the `random_point_in_triangle` function. Write a Python function `def random_point_in_triangle(v0, v1, v2)` to solve the following problem: Given three vertices v0, v1, v2, sample a point uniformly in the triangle Algorithm Reference: https://math.stackexchange.com/questions/538458/how-to-sample-points-on-a-triangle-surface-in-3d https://stackoverflow.com/questions/47410054/generate-random-locations-within-a-triangular-domain Here is the function: def random_point_in_triangle(v0, v1, v2): """ Given three vertices v0, v1, v2, sample a point uniformly in the triangle Algorithm Reference: https://math.stackexchange.com/questions/538458/how-to-sample-points-on-a-triangle-surface-in-3d https://stackoverflow.com/questions/47410054/generate-random-locations-within-a-triangular-domain """ r1 = random.random() r2 = random.random() s1 = math.sqrt(r1) return v0 * (1.0 - s1) + v1 * (1.0 - r2) * s1 + v2 * r2 * s1#
Given three vertices v0, v1, v2, sample a point uniformly in the triangle Algorithm Reference: https://math.stackexchange.com/questions/538458/how-to-sample-points-on-a-triangle-surface-in-3d https://stackoverflow.com/questions/47410054/generate-random-locations-within-a-triangular-domain
162,542
import os import math import random import numpy as np from typing import Optional from torchtyping import TensorType from plyfile import PlyData, PlyElement import torch from torch import nn import torch.nn.functional as F from kornia.geometry.conversions import ( quaternion_to_rotation_matrix, ) from diff_gaussian_rasterization import ( GaussianRasterizationSettings, GaussianRasterizer, ) from simple_knn._C import distCUDA2 from ..shared_utils.sh_utils import eval_sh, SH2RGB, RGB2SH from ..mesh_processer.mesh import Mesh, PointCloud from ..mesh_processer.mesh_utils import construct_list_of_gs_attributes, write_gs_ply, read_gs_ply The provided code snippet includes necessary dependencies for implementing the `find_points_within_radius` function. Write a Python function `def find_points_within_radius(query_points, vertex_points, d)` to solve the following problem: Finds vertex points within a given radius for each query point. Args: query_points (torch.Tensor): Tensor of shape (P1, 3) representing query points. vertex_points (torch.Tensor): Tensor of shape (P2, 3) representing vertex points. d (float): Radius within which to search for vertex points. Returns: List[List[int]]: A list of lists, where each inner list contains indices of vertex points within the radius for the corresponding query point. Here is the function: def find_points_within_radius(query_points, vertex_points, d): """ Finds vertex points within a given radius for each query point. Args: query_points (torch.Tensor): Tensor of shape (P1, 3) representing query points. vertex_points (torch.Tensor): Tensor of shape (P2, 3) representing vertex points. d (float): Radius within which to search for vertex points. Returns: List[List[int]]: A list of lists, where each inner list contains indices of vertex points within the radius for the corresponding query point. """ num_query_points = query_points.shape[0] # Calculate pairwise distances between query points and vertex points distances = torch.norm(query_points[:, None] - vertex_points, dim=2) # Create a mask indicating which vertex points are within the radius mask = distances <= d # Collect indices of vertex points within the radius for each query point result = [] for i in range(num_query_points): indices_within_radius = torch.nonzero(mask[i]).squeeze().tolist() result.append(indices_within_radius) return result
Finds vertex points within a given radius for each query point. Args: query_points (torch.Tensor): Tensor of shape (P1, 3) representing query points. vertex_points (torch.Tensor): Tensor of shape (P2, 3) representing vertex points. d (float): Radius within which to search for vertex points. Returns: List[List[int]]: A list of lists, where each inner list contains indices of vertex points within the radius for the corresponding query point.
162,543
import os import math import random import numpy as np from typing import Optional from torchtyping import TensorType from plyfile import PlyData, PlyElement import torch from torch import nn import torch.nn.functional as F pytorch3d_capable = True from kornia.geometry.conversions import ( quaternion_to_rotation_matrix, ) from diff_gaussian_rasterization import ( GaussianRasterizationSettings, GaussianRasterizer, ) from simple_knn._C import distCUDA2 from ..shared_utils.sh_utils import eval_sh, SH2RGB, RGB2SH from ..mesh_processer.mesh import Mesh, PointCloud from ..mesh_processer.mesh_utils import construct_list_of_gs_attributes, write_gs_ply, read_gs_ply def K_nearest_neighbors( points: torch.Tensor, K: int, query: Optional[torch.Tensor] = None, return_dist=False, ): if not pytorch3d_capable: raise ImportError("pytorch3d is not installed, which is required for KNN") # query/points: Tensor of shape (N, P1/P2, D) giving a batch of N point clouds, each containing up to P1/P2 points of dimension D if query is None: query = points dist, idx, nn = knn_points(query[None, ...], points[None, ...], K=K, return_nn=True) # idx: Tensor of shape (N, P1, K) # nn: Tensor of shape (N, P1, K, D) # take the index 1 since index 0 is the point itself if not return_dist: return nn[0, :, 1:, :], idx[0, :, 1:] else: return nn[0, :, 1:, :], idx[0, :, 1:], dist[0, :, 1:]
null
162,544
import os import math import random import numpy as np from typing import Optional from torchtyping import TensorType from plyfile import PlyData, PlyElement import torch from torch import nn import torch.nn.functional as F from kornia.geometry.conversions import ( quaternion_to_rotation_matrix, ) from diff_gaussian_rasterization import ( GaussianRasterizationSettings, GaussianRasterizer, ) from simple_knn._C import distCUDA2 from ..shared_utils.sh_utils import eval_sh, SH2RGB, RGB2SH from ..mesh_processer.mesh import Mesh, PointCloud from ..mesh_processer.mesh_utils import construct_list_of_gs_attributes, write_gs_ply, read_gs_ply The provided code snippet includes necessary dependencies for implementing the `distance_to_gaussian_surface` function. Write a Python function `def distance_to_gaussian_surface(points, svec, rotmat, query)` to solve the following problem: Calculate the radius of the gaussian along the direction, which determined by offset between points and query Calculation using Mahalanobis distance Args: points (Tensor): gaussians position of shape (*, 3) svec (Tensor): gaussians scale vector of shape (*, 3) rotmat : the rotation matrix of shape (*, 3, 3) query (Tensor): query positions of shape (*, 3) Returns: Distance of shape (*, 1): Here is the function: def distance_to_gaussian_surface(points, svec, rotmat, query): """ Calculate the radius of the gaussian along the direction, which determined by offset between points and query Calculation using Mahalanobis distance Args: points (Tensor): gaussians position of shape (*, 3) svec (Tensor): gaussians scale vector of shape (*, 3) rotmat : the rotation matrix of shape (*, 3, 3) query (Tensor): query positions of shape (*, 3) Returns: Distance of shape (*, 1): """ offset_dir = query - points offset_dir = torch.einsum("bij,bj->bi", rotmat.transpose(-1, -2), offset_dir) offset_dir = F.normalize(offset_dir, dim=-1) z = offset_dir[..., 2] y = offset_dir[..., 1] x = offset_dir[..., 0] r_xy = torch.sqrt(x**2 + y**2 + 1e-10) cos_theta = z sin_theta = r_xy cos_phi = x / r_xy sin_phi = y / r_xy d2 = svec[..., 0] ** 2 * cos_phi**2 + svec[..., 1] ** 2 * sin_phi**2 #r2 = svec[..., 2] ** 2 * cos_theta**2 + d2**2 * sin_theta**2 r2 = svec[..., 2] ** 2 * cos_theta**2 + d2 * sin_theta**2 # same as: squared_dist = np.dot(diff.T, np.dot(np.linalg.inv(covariance), diff)) """ Alternatively: def gaussian_squared_distance(query_point, mean, covariance): # Calculate the difference vector diff = query_point - mean # Compute the squared Mahalanobis distance inv_covariance = np.linalg.inv(covariance) squared_dist = np.dot(diff.T, np.dot(inv_covariance, diff)) return squared_dist # Example usage mean = np.array([x0, y0, z0]) # Gaussian mean (origin position) covariance = np.diag([sigma_x**2, sigma_y**2, sigma_z**2]) # Covariance matrix query_point = np.array([x_q, y_q, z_q]) # Query point squared_dist_to_gaussian = gaussian_squared_distance(query_point, mean, covariance) print(f"Squared distance to Gaussian surface: {squared_dist_to_gaussian:.4f}") """ return torch.sqrt(r2 + 1e-10)
Calculate the radius of the gaussian along the direction, which determined by offset between points and query Calculation using Mahalanobis distance Args: points (Tensor): gaussians position of shape (*, 3) svec (Tensor): gaussians scale vector of shape (*, 3) rotmat : the rotation matrix of shape (*, 3, 3) query (Tensor): query positions of shape (*, 3) Returns: Distance of shape (*, 1):
162,545
import os import math import random import numpy as np from typing import Optional from torchtyping import TensorType from plyfile import PlyData, PlyElement import torch from torch import nn import torch.nn.functional as F from kornia.geometry.conversions import ( quaternion_to_rotation_matrix, ) from diff_gaussian_rasterization import ( GaussianRasterizationSettings, GaussianRasterizer, ) from simple_knn._C import distCUDA2 from ..shared_utils.sh_utils import eval_sh, SH2RGB, RGB2SH from ..mesh_processer.mesh import Mesh, PointCloud from ..mesh_processer.mesh_utils import construct_list_of_gs_attributes, write_gs_ply, read_gs_ply def qvec2rotmat_batched(qvec: TensorType["N", 4]): return quaternion_to_rotation_matrix(qvec)
null
162,546
import os import math import numpy as np import cv2 as cv import trimesh import torch import torch.nn.functional as F import tqdm import comfy.utils from pyhocon import ConfigFactory from NeuS.models.dataset_mvdiff import Dataset from NeuS.models.fields import RenderingNetwork, SDFNetwork, SingleVarianceNetwork, NeRF from NeuS.models.renderer import NeuSRenderer from ..mesh_processer.mesh import Mesh def ranking_loss(error, penalize_ratio=0.7, type='mean'): error, indices = torch.sort(error) # only sum relatively small errors s_error = torch.index_select(error, 0, index=indices[: int(penalize_ratio * indices.shape[0])]) if type == 'mean': return torch.mean(s_error) elif type == 'sum': return torch.sum(s_error)
null
162,549
import torch def sdf_reg_loss(sdf, all_edges): sdf_f1x6x2 = sdf[all_edges.reshape(-1)].reshape(-1,2) mask = torch.sign(sdf_f1x6x2[...,0]) != torch.sign(sdf_f1x6x2[...,1]) sdf_f1x6x2 = sdf_f1x6x2[mask] sdf_diff = torch.nn.functional.binary_cross_entropy_with_logits(sdf_f1x6x2[...,0], (sdf_f1x6x2[...,1] > 0).float()) + \ torch.nn.functional.binary_cross_entropy_with_logits(sdf_f1x6x2[...,1], (sdf_f1x6x2[...,0] > 0).float()) return sdf_diff
null
162,550
import numpy as np import cv2 import torch import numpy as np from PIL import Image def get_obj_from_str(string, reload=False): import importlib 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: raise KeyError("Expected key `target` to instantiate.") return get_obj_from_str(config["target"])(**config.get("params", dict()))
null
162,551
import numpy as np import cv2 import torch import numpy as np from PIL import Image def tensor_detail(t): assert type(t) == torch.Tensor print(f"shape: {t.shape} mean: {t.mean():.2f}, std: {t.std():.2f}, min: {t.min():.2f}, max: {t.max():.2f}")
null
162,552
import numpy as np import cv2 import torch import numpy as np from PIL import Image The provided code snippet includes necessary dependencies for implementing the `drawRoundRec` function. Write a Python function `def drawRoundRec(draw, color, x, y, w, h, r)` to solve the following problem: Rounds Here is the function: def drawRoundRec(draw, color, x, y, w, h, r): drawObject = draw '''Rounds''' drawObject.ellipse((x, y, x + r, y + r), fill=color) drawObject.ellipse((x + w - r, y, x + w, y + r), fill=color) drawObject.ellipse((x, y + h - r, x + r, y + h), fill=color) drawObject.ellipse((x + w - r, y + h - r, x + w, y + h), fill=color) '''rec.s''' drawObject.rectangle((x + r / 2, y, x + w - (r / 2), y + h), fill=color) drawObject.rectangle((x, y + r / 2, x + w, y + h - (r / 2)), fill=color)
Rounds
162,553
import numpy as np import cv2 import torch import numpy as np from PIL import Image def do_resize_content(original_image: Image, scale_rate): # resize image content wile retain the original image size if scale_rate != 1: # Calculate the new size after rescaling new_size = tuple(int(dim * scale_rate) for dim in original_image.size) # Resize the image while maintaining the aspect ratio resized_image = original_image.resize(new_size) # Create a new image with the original size and black background padded_image = Image.new("RGBA", original_image.size, (0, 0, 0, 0)) paste_position = ((original_image.width - resized_image.width) // 2, (original_image.height - resized_image.height) // 2) padded_image.paste(resized_image, paste_position) return padded_image else: return original_image
null
162,554
import numpy as np import cv2 import torch import numpy as np from PIL import Image def add_stroke(img, color=(255, 255, 255), stroke_radius=3): # color in R, G, B format if isinstance(img, Image.Image): assert img.mode == "RGBA" img = cv2.cvtColor(np.array(img), cv2.COLOR_RGBA2BGRA) else: assert img.shape[2] == 4 gray = img[:,:, 3] ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY) contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) res = cv2.drawContours(img, contours,-1, tuple(color)[::-1] + (255,), stroke_radius) return Image.fromarray(cv2.cvtColor(res,cv2.COLOR_BGRA2RGBA))
null
162,555
import numpy as np import cv2 import torch import numpy as np from PIL import Image The provided code snippet includes necessary dependencies for implementing the `make_blob` function. Write a Python function `def make_blob(image_size=(512, 512), sigma=0.2)` to solve the following problem: make 2D blob image with: I(x, y)=1-\exp \left(-\frac{(x-H / 2)^2+(y-W / 2)^2}{2 \sigma^2 HS}\right) Here is the function: def make_blob(image_size=(512, 512), sigma=0.2): """ make 2D blob image with: I(x, y)=1-\exp \left(-\frac{(x-H / 2)^2+(y-W / 2)^2}{2 \sigma^2 HS}\right) """ import numpy as np H, W = image_size x = np.arange(0, W, 1, float) y = np.arange(0, H, 1, float) x, y = np.meshgrid(x, y) x0 = W // 2 y0 = H // 2 img = 1 - np.exp(-((x - x0) ** 2 + (y - y0) ** 2) / (2 * sigma ** 2 * H * W)) return (img * 255).astype(np.uint8)
make 2D blob image with: I(x, y)=1-\exp \left(-\frac{(x-H / 2)^2+(y-W / 2)^2}{2 \sigma^2 HS}\right)
162,556
import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `normalize_camera` function. Write a Python function `def normalize_camera(camera_matrix)` to solve the following problem: normalize the camera location onto a unit-sphere Here is the function: def normalize_camera(camera_matrix): """normalize the camera location onto a unit-sphere""" if isinstance(camera_matrix, np.ndarray): camera_matrix = camera_matrix.reshape(-1, 4, 4) translation = camera_matrix[:, :3, 3] translation = translation / ( np.linalg.norm(translation, axis=1, keepdims=True) + 1e-8 ) camera_matrix[:, :3, 3] = translation else: camera_matrix = camera_matrix.reshape(-1, 4, 4) translation = camera_matrix[:, :3, 3] translation = translation / ( torch.norm(translation, dim=1, keepdim=True) + 1e-8 ) camera_matrix[:, :3, 3] = translation return camera_matrix.reshape(-1, 16)
normalize the camera location onto a unit-sphere
162,557
import numpy as np import torch def get_camera( num_frames, elevation=15, azimuth_start=0, azimuth_span=360, blender_coord=True, extra_view=False, ): angle_gap = azimuth_span / num_frames cameras = [] for azimuth in np.arange(azimuth_start, azimuth_span + azimuth_start, angle_gap): camera_matrix = create_camera_to_world_matrix(elevation, azimuth) if blender_coord: camera_matrix = convert_opengl_to_blender(camera_matrix) cameras.append(camera_matrix.flatten()) if extra_view: dim = len(cameras[0]) cameras.append(np.zeros(dim)) return torch.tensor(np.stack(cameras, 0)).float() The provided code snippet includes necessary dependencies for implementing the `get_camera_for_index` function. Write a Python function `def get_camera_for_index(data_index)` to solve the following problem: 按照当前我们的数据格式, 以000为正对我们的情况: 000是正面, ev: 0, azimuth: 0 001是左边, ev: 0, azimuth: -90 002是下面, ev: -90, azimuth: 0 003是背面, ev: 0, azimuth: 180 004是右边, ev: 0, azimuth: 90 005是上面, ev: 90, azimuth: 0 Here is the function: def get_camera_for_index(data_index): """ 按照当前我们的数据格式, 以000为正对我们的情况: 000是正面, ev: 0, azimuth: 0 001是左边, ev: 0, azimuth: -90 002是下面, ev: -90, azimuth: 0 003是背面, ev: 0, azimuth: 180 004是右边, ev: 0, azimuth: 90 005是上面, ev: 90, azimuth: 0 """ params = [(0, 0), (0, -90), (-90, 0), (0, 180), (0, 90), (90, 0)] return get_camera(1, *params[data_index])
按照当前我们的数据格式, 以000为正对我们的情况: 000是正面, ev: 0, azimuth: 0 001是左边, ev: 0, azimuth: -90 002是下面, ev: -90, azimuth: 0 003是背面, ev: 0, azimuth: 180 004是右边, ev: 0, azimuth: 90 005是上面, ev: 90, azimuth: 0
162,558
import os import pkg_resources from omegaconf import OmegaConf import torch from huggingface_hub import hf_hub_download from crm.imagedream.ldm.util import instantiate_from_config PRETRAINED_MODELS = { "sd-v2.1-base-4view-ipmv": { "config": "sd_v2_base_ipmv.yaml", "repo_id": "Peng-Wang/ImageDream", "filename": "sd-v2.1-base-4view-ipmv.pt", }, "sd-v2.1-base-4view-ipmv-local": { "config": "sd_v2_base_ipmv_local.yaml", "repo_id": "Peng-Wang/ImageDream", "filename": "sd-v2.1-base-4view-ipmv-local.pt", }, } def get_config_file(config_path): cfg_file = pkg_resources.resource_filename( "imagedream", os.path.join("configs", config_path) ) if not os.path.exists(cfg_file): raise RuntimeError(f"Config {config_path} not available!") return cfg_file 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.") # import pdb; pdb.set_trace() return get_obj_from_str(config["target"])(**config.get("params", dict())) def build_model(model_name, config_path=None, ckpt_path=None, cache_dir=None): if (config_path is not None) and (ckpt_path is not None): config = OmegaConf.load(config_path) model = instantiate_from_config(config.model) model.load_state_dict(torch.load(ckpt_path, map_location="cpu"), strict=False) return model if not model_name in PRETRAINED_MODELS: raise RuntimeError( f"Model name {model_name} is not a pre-trained model. Available models are:\n- " + "\n- ".join(PRETRAINED_MODELS.keys()) ) model_info = PRETRAINED_MODELS[model_name] # Instiantiate the model print(f"Loading model from config: {model_info['config']}") config_file = get_config_file(model_info["config"]) config = OmegaConf.load(config_file) model = instantiate_from_config(config.model) # Load pre-trained checkpoint from huggingface if not ckpt_path: ckpt_path = hf_hub_download( repo_id=model_info["repo_id"], filename=model_info["filename"], cache_dir=cache_dir, ) print(f"Loading model from cache file: {ckpt_path}") model.load_state_dict(torch.load(ckpt_path, map_location="cpu"), strict=False) return model
null
162,559
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib 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["target"])(**config.get("params", dict()))
null
162,560
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib def make_beta_schedule( schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3 ): if schedule == "linear": betas = ( torch.linspace( linear_start**0.5, linear_end**0.5, n_timestep, dtype=torch.float64 ) ** 2 ) elif schedule == "cosine": timesteps = ( torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s ) alphas = timesteps / (1 + cosine_s) * np.pi / 2 alphas = torch.cos(alphas).pow(2) alphas = alphas / alphas[0] betas = 1 - alphas[1:] / alphas[:-1] betas = np.clip(betas, a_min=0, a_max=0.999) elif schedule == "sqrt_linear": betas = torch.linspace( linear_start, linear_end, n_timestep, dtype=torch.float64 ) elif schedule == "sqrt": betas = ( torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5 ) else: raise ValueError(f"schedule '{schedule}' unknown.") return betas.numpy()
null
162,561
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib def enforce_zero_terminal_snr(betas): betas = torch.tensor(betas) if not isinstance(betas, torch.Tensor) else betas # Convert betas to alphas_bar_sqrt alphas =1 - betas alphas_bar = alphas.cumprod(0) alphas_bar_sqrt = alphas_bar.sqrt() # Store old values. alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone() alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone() # Shift so last timestep is zero. alphas_bar_sqrt -= alphas_bar_sqrt_T # Scale so first timestep is back to old value. alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T) # Convert alphas_bar_sqrt to betas alphas_bar = alphas_bar_sqrt ** 2 alphas = alphas_bar[1:] / alphas_bar[:-1] alphas = torch.cat ([alphas_bar[0:1], alphas]) betas = 1 - alphas return betas
null
162,562
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib def make_ddim_timesteps( ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True ): if ddim_discr_method == "uniform": c = num_ddpm_timesteps // num_ddim_timesteps ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c))) elif ddim_discr_method == "quad": ddim_timesteps = ( (np.linspace(0, np.sqrt(num_ddpm_timesteps * 0.8), num_ddim_timesteps)) ** 2 ).astype(int) else: raise NotImplementedError( f'There is no ddim discretization method called "{ddim_discr_method}"' ) # assert ddim_timesteps.shape[0] == num_ddim_timesteps # add one to get the final alpha values right (the ones from first scale to data during sampling) steps_out = ddim_timesteps + 1 if verbose: print(f"Selected timesteps for ddim sampler: {steps_out}") return steps_out
null
162,563
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True): # select alphas for computing the variance schedule alphas = alphacums[ddim_timesteps] alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist()) # according the the formula provided in https://arxiv.org/abs/2010.02502 sigmas = eta * np.sqrt( (1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev) ) if verbose: print( f"Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}" ) print( f"For the chosen value of eta, which is {eta}, " f"this results in the following sigma_t schedule for ddim sampler {sigmas}" ) return sigmas, alphas, alphas_prev
null
162,564
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib The provided code snippet includes necessary dependencies for implementing the `betas_for_alpha_bar` function. Write a Python function `def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999)` to solve the following problem: Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of (1-beta) over time from t = [0,1]. :param num_diffusion_timesteps: the number of betas to produce. :param alpha_bar: a lambda that takes an argument t from 0 to 1 and produces the cumulative product of (1-beta) up to that part of the diffusion process. :param max_beta: the maximum beta to use; use values lower than 1 to prevent singularities. Here is the function: def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999): """ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of (1-beta) over time from t = [0,1]. :param num_diffusion_timesteps: the number of betas to produce. :param alpha_bar: a lambda that takes an argument t from 0 to 1 and produces the cumulative product of (1-beta) up to that part of the diffusion process. :param max_beta: the maximum beta to use; use values lower than 1 to prevent singularities. """ betas = [] for i in range(num_diffusion_timesteps): t1 = i / num_diffusion_timesteps t2 = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta)) return np.array(betas)
Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of (1-beta) over time from t = [0,1]. :param num_diffusion_timesteps: the number of betas to produce. :param alpha_bar: a lambda that takes an argument t from 0 to 1 and produces the cumulative product of (1-beta) up to that part of the diffusion process. :param max_beta: the maximum beta to use; use values lower than 1 to prevent singularities.
162,565
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib def extract_into_tensor(a, t, x_shape): b, *_ = t.shape out = a.gather(-1, t) return out.reshape(b, *((1,) * (len(x_shape) - 1)))
null
162,566
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib class CheckpointFunction(torch.autograd.Function): def forward(ctx, run_function, length, *args): ctx.run_function = run_function ctx.input_tensors = list(args[:length]) ctx.input_params = list(args[length:]) with torch.no_grad(): output_tensors = ctx.run_function(*ctx.input_tensors) return output_tensors def backward(ctx, *output_grads): ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors] with torch.enable_grad(): # Fixes a bug where the first op in run_function modifies the # Tensor storage in place, which is not allowed for detach()'d # Tensors. shallow_copies = [x.view_as(x) for x in ctx.input_tensors] output_tensors = ctx.run_function(*shallow_copies) input_grads = torch.autograd.grad( output_tensors, ctx.input_tensors + ctx.input_params, output_grads, allow_unused=True, ) del ctx.input_tensors del ctx.input_params del output_tensors return (None, None) + input_grads The provided code snippet includes necessary dependencies for implementing the `checkpoint` function. Write a Python function `def checkpoint(func, inputs, params, flag)` to solve the following problem: 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 take as arguments. :param flag: if False, disable gradient checkpointing. Here is the function: def checkpoint(func, inputs, params, flag): """ 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 take as arguments. :param flag: if False, disable gradient checkpointing. """ if flag: args = tuple(inputs) + tuple(params) return CheckpointFunction.apply(func, len(inputs), *args) else: return func(*inputs)
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 take as arguments. :param flag: if False, disable gradient checkpointing.
162,567
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib 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, repeat_only=False)` to solve the following problem: 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. Here is the function: def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False): """ 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. """ if not repeat_only: half = dim // 2 freqs = torch.exp( -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half ).to(device=timesteps.device) args = timesteps[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat( [embedding, torch.zeros_like(embedding[:, :1])], dim=-1 ) else: embedding = repeat(timesteps, "b -> b d", d=dim) # import pdb; pdb.set_trace() return embedding
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.
162,568
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib 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 zero_module(module): """ Zero out the parameters of a module and return it. """ for p in module.parameters(): p.detach().zero_() return module
Zero out the parameters of a module and return it.
162,569
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib 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: def scale_module(module, scale): """ Scale the parameters of a module and return it. """ for p in module.parameters(): p.detach().mul_(scale) return module
Scale the parameters of a module and return it.
162,570
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib 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(tensor): """ Take the mean over all non-batch dimensions. """ return tensor.mean(dim=list(range(1, len(tensor.shape))))
Take the mean over all non-batch dimensions.
162,571
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib 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(channels)` to solve the following problem: Make a standard normalization layer. :param channels: number of input channels. :return: an nn.Module for normalization. Here is the function: def normalization(channels): """ Make a standard normalization layer. :param channels: number of input channels. :return: an nn.Module for normalization. """ return GroupNorm32(32, channels)
Make a standard normalization layer. :param channels: number of input channels. :return: an nn.Module for normalization.
162,572
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib 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 conv_nd(dims, *args, **kwargs): """ Create a 1D, 2D, or 3D convolution module. """ if dims == 1: return nn.Conv1d(*args, **kwargs) elif dims == 2: return nn.Conv2d(*args, **kwargs) elif dims == 3: return nn.Conv3d(*args, **kwargs) raise ValueError(f"unsupported dimensions: {dims}")
Create a 1D, 2D, or 3D convolution module.
162,573
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib 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. """ return nn.Linear(*args, **kwargs)
Create a linear module.
162,574
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib 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 function: def avg_pool_nd(dims, *args, **kwargs): """ Create a 1D, 2D, or 3D average pooling module. """ if dims == 1: return nn.AvgPool1d(*args, **kwargs) elif dims == 2: return nn.AvgPool2d(*args, **kwargs) elif dims == 3: return nn.AvgPool3d(*args, **kwargs) raise ValueError(f"unsupported dimensions: {dims}")
Create a 1D, 2D, or 3D average pooling module.
162,575
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib def noise_like(shape, device, repeat=False): repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat( shape[0], *((1,) * (len(shape) - 1)) ) noise = lambda: torch.randn(shape, device=device) return repeat_noise() if repeat else noise()
null
162,576
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib The provided code snippet includes necessary dependencies for implementing the `convert_module_to_f16` function. Write a Python function `def convert_module_to_f16(l)` to solve the following problem: Convert primitive modules to float16. Here is the function: def convert_module_to_f16(l): """ Convert primitive modules to float16. """ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): l.weight.data = l.weight.data.half() if l.bias is not None: l.bias.data = l.bias.data.half()
Convert primitive modules to float16.
162,577
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat import importlib The provided code snippet includes necessary dependencies for implementing the `convert_module_to_f32` function. Write a Python function `def convert_module_to_f32(l)` to solve the following problem: Convert primitive modules to float32, undoing convert_module_to_f16(). Here is the function: def convert_module_to_f32(l): """ Convert primitive modules to float32, undoing convert_module_to_f16(). """ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): l.weight.data = l.weight.data.float() if l.bias is not None: l.bias.data = l.bias.data.float()
Convert primitive modules to float32, undoing convert_module_to_f16().
162,578
import math import torch import torch.nn as nn import numpy as np from einops import rearrange from typing import Optional, Any from ..attention import MemoryEfficientCrossAttention The provided code snippet includes necessary dependencies for implementing the `get_timestep_embedding` function. Write a Python function `def get_timestep_embedding(timesteps, embedding_dim)` to solve the following problem: This matches the implementation in Denoising Diffusion Probabilistic Models: From Fairseq. Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of "Attention Is All You Need". Here is the function: def get_timestep_embedding(timesteps, embedding_dim): """ This matches the implementation in Denoising Diffusion Probabilistic Models: From Fairseq. Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of "Attention Is All You Need". """ assert len(timesteps.shape) == 1 half_dim = embedding_dim // 2 emb = math.log(10000) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb) emb = emb.to(device=timesteps.device) emb = timesteps.float()[:, None] * emb[None, :] emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1) if embedding_dim % 2 == 1: # zero pad emb = torch.nn.functional.pad(emb, (0, 1, 0, 0)) return emb
This matches the implementation in Denoising Diffusion Probabilistic Models: From Fairseq. Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of "Attention Is All You Need".
162,579
import math import torch import torch.nn as nn import numpy as np from einops import rearrange from typing import Optional, Any from ..attention import MemoryEfficientCrossAttention def nonlinearity(x): # swish return x * torch.sigmoid(x)
null
162,580
import math import torch import torch.nn as nn import numpy as np from einops import rearrange from typing import Optional, Any from ..attention import MemoryEfficientCrossAttention def Normalize(in_channels, num_groups=32): return torch.nn.GroupNorm( num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True )
null
162,581
import math import torch import torch.nn as nn import numpy as np from einops import rearrange from typing import Optional, Any from ..attention import MemoryEfficientCrossAttention class AttnBlock(nn.Module): def __init__(self, in_channels): super().__init__() self.in_channels = in_channels self.norm = Normalize(in_channels) self.q = torch.nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0 ) self.k = torch.nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0 ) self.v = torch.nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0 ) self.proj_out = torch.nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0 ) def forward(self, x): h_ = x h_ = self.norm(h_) q = self.q(h_) k = self.k(h_) v = self.v(h_) # compute attention b, c, h, w = q.shape q = q.reshape(b, c, h * w) q = q.permute(0, 2, 1) # b,hw,c k = k.reshape(b, c, h * w) # b,c,hw w_ = torch.bmm(q, k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j] w_ = w_ * (int(c) ** (-0.5)) w_ = torch.nn.functional.softmax(w_, dim=2) # attend to values v = v.reshape(b, c, h * w) w_ = w_.permute(0, 2, 1) # b,hw,hw (first hw of k, second of q) h_ = torch.bmm(v, w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j] h_ = h_.reshape(b, c, h, w) h_ = self.proj_out(h_) return x + h_ class MemoryEfficientAttnBlock(nn.Module): """ Uses xformers efficient implementation, see https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223 Note: this is a single-head self-attention operation """ # def __init__(self, in_channels): super().__init__() self.in_channels = in_channels self.norm = Normalize(in_channels) self.q = torch.nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0 ) self.k = torch.nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0 ) self.v = torch.nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0 ) self.proj_out = torch.nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0 ) self.attention_op: Optional[Any] = None def forward(self, x): h_ = x h_ = self.norm(h_) q = self.q(h_) k = self.k(h_) v = self.v(h_) # compute attention B, C, H, W = q.shape q, k, v = map(lambda x: rearrange(x, "b c h w -> b (h w) c"), (q, k, v)) q, k, v = map( lambda t: t.unsqueeze(3) .reshape(B, t.shape[1], 1, C) .permute(0, 2, 1, 3) .reshape(B * 1, t.shape[1], C) .contiguous(), (q, k, v), ) out = xformers.ops.memory_efficient_attention( q, k, v, attn_bias=None, op=self.attention_op ) out = ( out.unsqueeze(0) .reshape(B, 1, out.shape[1], C) .permute(0, 2, 1, 3) .reshape(B, out.shape[1], C) ) out = rearrange(out, "b (h w) c -> b c h w", b=B, h=H, w=W, c=C) out = self.proj_out(out) return x + out class MemoryEfficientCrossAttentionWrapper(MemoryEfficientCrossAttention): def forward(self, x, context=None, mask=None): b, c, h, w = x.shape x = rearrange(x, "b c h w -> b (h w) c") out = super().forward(x, context=context, mask=mask) out = rearrange(out, "b (h w) c -> b c h w", h=h, w=w, c=c) return x + out def make_attn(in_channels, attn_type="vanilla", attn_kwargs=None): assert attn_type in [ "vanilla", "vanilla-xformers", "memory-efficient-cross-attn", "linear", "none", ], f"attn_type {attn_type} unknown" if XFORMERS_IS_AVAILBLE and attn_type == "vanilla": attn_type = "vanilla-xformers" print(f"making attention of type '{attn_type}' with {in_channels} in_channels") if attn_type == "vanilla": assert attn_kwargs is None return AttnBlock(in_channels) elif attn_type == "vanilla-xformers": print(f"building MemoryEfficientAttnBlock with {in_channels} in_channels...") return MemoryEfficientAttnBlock(in_channels) elif type == "memory-efficient-cross-attn": attn_kwargs["query_dim"] = in_channels return MemoryEfficientCrossAttentionWrapper(**attn_kwargs) elif attn_type == "none": return nn.Identity(in_channels) else: raise NotImplementedError()
null
162,584
from abc import abstractmethod import math import numpy as np import torch import torch as th import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat from crm.imagedream.ldm.modules.diffusionmodules.util import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_module, normalization, timestep_embedding, convert_module_to_f16, convert_module_to_f32 ) from crm.imagedream.ldm.modules.attention import ( SpatialTransformer, SpatialTransformer3D, exists ) from crm.imagedream.ldm.modules.diffusionmodules.adaptors import ( Resampler, ImageProjModel ) The provided code snippet includes necessary dependencies for implementing the `count_flops_attn` function. Write a Python function `def count_flops_attn(model, _x, y)` to solve the following problem: A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops}, ) Here is the function: def count_flops_attn(model, _x, y): """ A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops}, ) """ b, c, *spatial = y[0].shape num_spatial = int(np.prod(spatial)) # We perform two matmuls with the same number of ops. # The first computes the weight matrix, the second computes # the combination of the value vectors. matmul_ops = 2 * b * (num_spatial**2) * c model.total_ops += th.DoubleTensor([matmul_ops])
A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops}, )
162,585
from inspect import isfunction import math import torch import torch.nn.functional as F from torch import nn, einsum from einops import rearrange, repeat from typing import Optional, Any from .diffusionmodules.util import checkpoint import os def uniq(arr): return {el: True for el in arr}.keys()
null
162,586
from inspect import isfunction import math import torch import torch.nn.functional as F from torch import nn, einsum from einops import rearrange, repeat from typing import Optional, Any from .diffusionmodules.util import checkpoint import os def exists(val): return val is not None def default(val, d): if exists(val): return val return d() if isfunction(d) else d
null
162,590
from inspect import isfunction import math import torch import torch.nn.functional as F from torch import nn, einsum from einops import rearrange, repeat from typing import Optional, Any from .diffusionmodules.util import checkpoint import os def Normalize(in_channels): return torch.nn.GroupNorm( num_groups=32, num_channels=in_channels, eps=1e-6, affine=True )
null
162,592
import torch import torch.nn as nn from torch.utils.checkpoint import checkpoint from transformers import T5Tokenizer, T5EncoderModel, CLIPTokenizer, CLIPTextModel import numpy as np import open_clip from PIL import Image from ...util import default, count_params The provided code snippet includes necessary dependencies for implementing the `disabled_train` function. Write a Python function `def disabled_train(self, mode=True)` to solve the following problem: Overwrite model.train with this function to make sure train/eval mode does not change anymore. Here is the function: def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self
Overwrite model.train with this function to make sure train/eval mode does not change anymore.
162,593
import importlib import random import torch import numpy as np from collections import abc import multiprocessing as mp from threading import Thread from queue import Queue from inspect import isfunction from PIL import Image, ImageDraw, ImageFont def log_txt_as_img(wh, xc, size=10): # wh a tuple of (width, height) # xc a list of captions to plot b = len(xc) txts = list() for bi in range(b): txt = Image.new("RGB", wh, color="white") draw = ImageDraw.Draw(txt) font = ImageFont.truetype("data/DejaVuSans.ttf", size=size) nc = int(40 * (wh[0] / 256)) lines = "\n".join( xc[bi][start : start + nc] for start in range(0, len(xc[bi]), nc) ) try: draw.text((0, 0), lines, fill="black", font=font) except UnicodeEncodeError: print("Cant encode string for logging. Skipping.") txt = np.array(txt).transpose(2, 0, 1) / 127.5 - 1.0 txts.append(txt) txts = np.stack(txts) txts = torch.tensor(txts) return txts
null
162,594
import importlib import random import torch import numpy as np from collections import abc import multiprocessing as mp from threading import Thread from queue import Queue from inspect import isfunction from PIL import Image, ImageDraw, ImageFont def ismap(x): if not isinstance(x, torch.Tensor): return False return (len(x.shape) == 4) and (x.shape[1] > 3)
null
162,595
import importlib import random import torch import numpy as np from collections import abc import multiprocessing as mp from threading import Thread from queue import Queue from inspect import isfunction from PIL import Image, ImageDraw, ImageFont def isimage(x): if not isinstance(x, torch.Tensor): return False return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1)
null
162,596
import importlib import random import torch import numpy as np from collections import abc import multiprocessing as mp from threading import Thread from queue import Queue from inspect import isfunction from PIL import Image, ImageDraw, ImageFont def exists(x): return x is not None def default(val, d): if exists(val): return val return d() if isfunction(d) else d
null
162,597
import importlib import random import torch import numpy as np from collections import abc import multiprocessing as mp from threading import Thread from queue import Queue from inspect import isfunction from PIL import Image, ImageDraw, ImageFont 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: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86 Take the mean over all non-batch dimensions. Here is the function: def mean_flat(tensor): """ https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86 Take the mean over all non-batch dimensions. """ return tensor.mean(dim=list(range(1, len(tensor.shape))))
https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86 Take the mean over all non-batch dimensions.
162,598
import importlib import random import torch import numpy as np from collections import abc import multiprocessing as mp from threading import Thread from queue import Queue from inspect import isfunction from PIL import Image, ImageDraw, ImageFont def count_params(model, verbose=False): total_params = sum(p.numel() for p in model.parameters()) if verbose: print(f"{model.__class__.__name__} has {total_params * 1.e-6:.2f} M params.") return total_params
null
162,599
import importlib import random import torch import numpy as np from collections import abc import multiprocessing as mp from threading import Thread from queue import Queue from inspect import isfunction from PIL import Image, ImageDraw, ImageFont def _do_parallel_data_prefetch(func, Q, data, idx, idx_to_fn=False): # create dummy dataset instance # run prefetching if idx_to_fn: res = func(data, worker_id=idx) else: res = func(data) Q.put([idx, res]) Q.put("Done") def parallel_data_prefetch( func: callable, data, n_proc, target_data_type="ndarray", cpu_intensive=True, use_worker_id=False, ): # if target_data_type not in ["ndarray", "list"]: # raise ValueError( # "Data, which is passed to parallel_data_prefetch has to be either of type list or ndarray." # ) if isinstance(data, np.ndarray) and target_data_type == "list": raise ValueError("list expected but function got ndarray.") elif isinstance(data, abc.Iterable): if isinstance(data, dict): print( f'WARNING:"data" argument passed to parallel_data_prefetch is a dict: Using only its values and disregarding keys.' ) data = list(data.values()) if target_data_type == "ndarray": data = np.asarray(data) else: data = list(data) else: raise TypeError( f"The data, that shall be processed parallel has to be either an np.ndarray or an Iterable, but is actually {type(data)}." ) if cpu_intensive: Q = mp.Queue(1000) proc = mp.Process else: Q = Queue(1000) proc = Thread # spawn processes if target_data_type == "ndarray": arguments = [ [func, Q, part, i, use_worker_id] for i, part in enumerate(np.array_split(data, n_proc)) ] else: step = ( int(len(data) / n_proc + 1) if len(data) % n_proc != 0 else int(len(data) / n_proc) ) arguments = [ [func, Q, part, i, use_worker_id] for i, part in enumerate( [data[i : i + step] for i in range(0, len(data), step)] ) ] processes = [] for i in range(n_proc): p = proc(target=_do_parallel_data_prefetch, args=arguments[i]) processes += [p] # start processes print(f"Start prefetching...") import time start = time.time() gather_res = [[] for _ in range(n_proc)] try: for p in processes: p.start() k = 0 while k < n_proc: # get result res = Q.get() if res == "Done": k += 1 else: gather_res[res[0]] = res[1] except Exception as e: print("Exception: ", e) for p in processes: p.terminate() raise e finally: for p in processes: p.join() print(f"Prefetching complete. [{time.time() - start} sec.]") if target_data_type == "ndarray": if not isinstance(gather_res[0], np.ndarray): return np.concatenate([np.asarray(r) for r in gather_res], axis=0) # order outputs return np.concatenate(gather_res, axis=0) elif target_data_type == "list": out = [] for r in gather_res: out.extend(r) return out else: return gather_res
null
162,600
import importlib import random import torch import numpy as np from collections import abc import multiprocessing as mp from threading import Thread from queue import Queue from inspect import isfunction from PIL import Image, ImageDraw, ImageFont def set_seed(seed=None): random.seed(seed) np.random.seed(seed) if seed is not None: torch.manual_seed(seed) torch.cuda.manual_seed_all(seed)
null
162,601
import importlib import random import torch import numpy as np from collections import abc import multiprocessing as mp from threading import Thread from queue import Queue from inspect import isfunction from PIL import Image, ImageDraw, ImageFont def add_random_background(image, bg_color=None): bg_color = np.random.rand() * 255 if bg_color is None else bg_color image = np.array(image) rgb, alpha = image[..., :3], image[..., 3:] alpha = alpha.astype(np.float32) / 255.0 image_new = rgb * alpha + bg_color * (1 - alpha) return Image.fromarray(image_new.astype(np.uint8))
null
162,602
import numpy as np import torch import random def perspective(fovx=0.7854, aspect=1.0, n=0.1, f=1000.0, device=None): # y = np.tan(fovy / 2) x = np.tan(fovx / 2) return torch.tensor([[1/x, 0, 0, 0], [ 0, -aspect/x, 0, 0], [ 0, 0, -(f+n)/(f-n), -(2*f*n)/(f-n)], [ 0, 0, -1, 0]], dtype=torch.float32, device=device)
null
162,603
import numpy as np import torch import random def translate(x, y, z, device=None): return torch.tensor([[1, 0, 0, x], [0, 1, 0, y], [0, 0, 1, z], [0, 0, 0, 1]], dtype=torch.float32, device=device)
null
162,604
import numpy as np import torch import random def rotate_x(a, device=None): s, c = np.sin(a), np.cos(a) return torch.tensor([[1, 0, 0, 0], [0, c, -s, 0], [0, s, c, 0], [0, 0, 0, 1]], dtype=torch.float32, device=device)
null
162,605
import numpy as np import torch import random def rotate_y(a, device=None): s, c = np.sin(a), np.cos(a) return torch.tensor([[ c, 0, s, 0], [ 0, 1, 0, 0], [-s, 0, c, 0], [ 0, 0, 0, 1]], dtype=torch.float32, device=device)
null
162,606
import numpy as np import torch import random def rotate_z(a, device=None): s, c = np.sin(a), np.cos(a) return torch.tensor([[c, -s, 0, 0], [s, c, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=torch.float32, device=device)
null
162,607
import numpy as np import torch import random def batch_random_rotation_translation(b, t, device=None): m = np.random.normal(size=[b, 3, 3]) m[:, 1] = np.cross(m[:, 0], m[:, 2]) m[:, 2] = np.cross(m[:, 0], m[:, 1]) m = m / np.linalg.norm(m, axis=2, keepdims=True) m = np.pad(m, [[0, 0], [0, 1], [0, 1]], mode='constant') m[:, 3, 3] = 1.0 m[:, :3, 3] = np.random.uniform(-t, t, size=[b, 3]) return torch.tensor(m, dtype=torch.float32, device=device)
null
162,608
import numpy as np import torch import random def random_rotation_translation(t, device=None): m = np.random.normal(size=[3, 3]) m[1] = np.cross(m[0], m[2]) m[2] = np.cross(m[0], m[1]) m = m / np.linalg.norm(m, axis=1, keepdims=True) m = np.pad(m, [[0, 1], [0, 1]], mode='constant') m[3, 3] = 1.0 m[:3, 3] = np.random.uniform(-t, t, size=[3]) return torch.tensor(m, dtype=torch.float32, device=device)
null
162,609
import numpy as np import torch import random def random_rotation(device=None): m = np.random.normal(size=[3, 3]) m[1] = np.cross(m[0], m[2]) m[2] = np.cross(m[0], m[1]) m = m / np.linalg.norm(m, axis=1, keepdims=True) m = np.pad(m, [[0, 1], [0, 1]], mode='constant') m[3, 3] = 1.0 m[:3, 3] = np.array([0,0,0]).astype(np.float32) return torch.tensor(m, dtype=torch.float32, device=device)
null
162,610
import numpy as np import torch import random def length(x: torch.Tensor, eps: float =1e-20) -> torch.Tensor: return torch.sqrt(torch.clamp(dot(x,x), min=eps)) # Clamp to avoid nan gradients because grad(sqrt(0)) = NaN def safe_normalize(x: torch.Tensor, eps: float =1e-20) -> torch.Tensor: return x / length(x, eps)
null
162,611
import numpy as np import torch import random def lr_schedule(iter, warmup_iter, scheduler_decay): if iter < warmup_iter: return iter / warmup_iter return max(0.0, 10 ** ( -(iter - warmup_iter) * scheduler_decay))
null
162,612
import numpy as np import torch import random def trans_depth(depth): depth = depth[0].detach().cpu().numpy() valid = depth > 0 depth[valid] -= depth[valid].min() depth[valid] = ((depth[valid] / depth[valid].max()) * 255) return depth.astype('uint8')
null
162,613
import numpy as np import torch import random def nan_to_num(input, nan=0.0, posinf=None, neginf=None, *, out=None): assert isinstance(input, torch.Tensor) if posinf is None: posinf = torch.finfo(input.dtype).max if neginf is None: neginf = torch.finfo(input.dtype).min assert nan == 0 return torch.clamp(input.unsqueeze(0).nansum(0), min=neginf, max=posinf, out=out)
null
162,614
import numpy as np import torch import random def load_item(filepath): with open(filepath, 'r') as f: items = [name.strip() for name in f.readlines()] return set(items)
null
162,615
import numpy as np import torch import random def load_prompt(filepath): uuid2prompt = {} with open(filepath, 'r') as f: for line in f.readlines(): list_line = line.split(',') uuid2prompt[list_line[0]] = ','.join(list_line[1:]).strip() return uuid2prompt
null
162,616
import numpy as np import torch import random def resize_and_center_image(image_tensor, scale=0.95, c = 0, shift = 0, rgb=False, aug_shift = 0): def get_tri(triview_color, dim = 1, blender=True, c = 0, scale=0.95, shift = 0, fix = False, rgb=False, aug_shift = 0): # triview_color: [6,C,H,W] # rgb is useful when shift is not 0 triview_color = resize_and_center_image(triview_color, scale=scale, c = c, shift=shift,rgb=rgb, aug_shift = aug_shift) if blender is False: triview_color0 = torch.rot90(triview_color[0],k=2,dims=[1,2]) triview_color1 = torch.rot90(triview_color[4],k=1,dims=[1,2]).flip(2).flip(1) triview_color2 = torch.rot90(triview_color[5],k=1,dims=[1,2]).flip(2) triview_color3 = torch.rot90(triview_color[3],k=2,dims=[1,2]).flip(2) triview_color4 = torch.rot90(triview_color[1],k=3,dims=[1,2]).flip(1) triview_color5 = torch.rot90(triview_color[2],k=3,dims=[1,2]).flip(1).flip(2) else: triview_color0 = torch.rot90(triview_color[2],k=2,dims=[1,2]) triview_color1 = torch.rot90(triview_color[4],k=0,dims=[1,2]).flip(2).flip(1) triview_color2 = torch.rot90(torch.rot90(triview_color[0],k=3,dims=[1,2]).flip(2), k=2,dims=[1,2]) triview_color3 = torch.rot90(torch.rot90(triview_color[5],k=2,dims=[1,2]).flip(2), k=2,dims=[1,2]) triview_color4 = torch.rot90(triview_color[1],k=2,dims=[1,2]).flip(1).flip(1).flip(2) triview_color5 = torch.rot90(triview_color[3],k=1,dims=[1,2]).flip(1).flip(2) if fix == True: triview_color0[1] = triview_color0[1] * 0 triview_color0[2] = triview_color0[2] * 0 triview_color3[1] = triview_color3[1] * 0 triview_color3[2] = triview_color3[2] * 0 triview_color1[0] = triview_color1[0] * 0 triview_color1[1] = triview_color1[1] * 0 triview_color4[0] = triview_color4[0] * 0 triview_color4[1] = triview_color4[1] * 0 triview_color2[0] = triview_color2[0] * 0 triview_color2[2] = triview_color2[2] * 0 triview_color5[0] = triview_color5[0] * 0 triview_color5[2] = triview_color5[2] * 0 color_tensor1_gt = torch.cat((triview_color0, triview_color1, triview_color2), dim=2) color_tensor2_gt = torch.cat((triview_color3, triview_color4, triview_color5), dim=2) color_tensor_gt = torch.cat((color_tensor1_gt, color_tensor2_gt), dim = dim) return color_tensor_gt
null
162,617
import torch from .flexicubes import FlexiCubes import torch.nn.functional as F def get_center_boundary_index(grid_res, device): v = torch.zeros((grid_res + 1, grid_res + 1, grid_res + 1), dtype=torch.bool, device=device) v[grid_res // 2 + 1, grid_res // 2 + 1, grid_res // 2 + 1] = True center_indices = torch.nonzero(v.reshape(-1)) v[grid_res // 2 + 1, grid_res // 2 + 1, grid_res // 2 + 1] = False v[:2, ...] = True v[-2:, ...] = True v[:, :2, ...] = True v[:, -2:, ...] = True v[:, :, :2] = True v[:, :, -2:] = True boundary_indices = torch.nonzero(v.reshape(-1)) return center_indices, boundary_indices
null
162,618
import math import numpy as np from inspect import isfunction from typing import Optional, Any, List import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat from diffusers.configuration_utils import ConfigMixin from diffusers.models.modeling_utils import ModelMixin import xformers import xformers.ops from kiui.cam import orbit_camera def get_camera( num_frames, elevation=15, azimuth_start=0, azimuth_span=360, blender_coord=True, extra_view=False, ): angle_gap = azimuth_span / num_frames cameras = [] for azimuth in np.arange(azimuth_start, azimuth_span + azimuth_start, angle_gap): pose = orbit_camera(-elevation, azimuth, radius=1) # kiui's elevation is negated, [4, 4] # opengl to blender if blender_coord: pose[2] *= -1 pose[[1, 2]] = pose[[2, 1]] cameras.append(pose.flatten()) if extra_view: cameras.append(np.zeros_like(cameras[0])) return torch.from_numpy(np.stack(cameras, axis=0)).float() # [num_frames, 16]
null
162,619
import math import numpy as np from inspect import isfunction from typing import Optional, Any, List import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat from diffusers.configuration_utils import ConfigMixin from diffusers.models.modeling_utils import ModelMixin import xformers import xformers.ops from kiui.cam import orbit_camera 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, repeat_only=False)` to solve the following problem: 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. Here is the function: def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False): """ 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. """ if not repeat_only: half = dim // 2 freqs = torch.exp( -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half ).to(device=timesteps.device) args = timesteps[:, None] * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat( [embedding, torch.zeros_like(embedding[:, :1])], dim=-1 ) else: embedding = repeat(timesteps, "b -> b d", d=dim) # import pdb; pdb.set_trace() return embedding
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.
162,620
import math import numpy as np from inspect import isfunction from typing import Optional, Any, List import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat from diffusers.configuration_utils import ConfigMixin from diffusers.models.modeling_utils import ModelMixin import xformers import xformers.ops from kiui.cam import orbit_camera 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 zero_module(module): """ Zero out the parameters of a module and return it. """ for p in module.parameters(): p.detach().zero_() return module
Zero out the parameters of a module and return it.
162,621
import math import numpy as np from inspect import isfunction from typing import Optional, Any, List import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat from diffusers.configuration_utils import ConfigMixin from diffusers.models.modeling_utils import ModelMixin import xformers import xformers.ops from kiui.cam import orbit_camera 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 conv_nd(dims, *args, **kwargs): """ Create a 1D, 2D, or 3D convolution module. """ if dims == 1: return nn.Conv1d(*args, **kwargs) elif dims == 2: return nn.Conv2d(*args, **kwargs) elif dims == 3: return nn.Conv3d(*args, **kwargs) raise ValueError(f"unsupported dimensions: {dims}")
Create a 1D, 2D, or 3D convolution module.
162,622
import math import numpy as np from inspect import isfunction from typing import Optional, Any, List import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat from diffusers.configuration_utils import ConfigMixin from diffusers.models.modeling_utils import ModelMixin import xformers import xformers.ops from kiui.cam import orbit_camera 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 function: def avg_pool_nd(dims, *args, **kwargs): """ Create a 1D, 2D, or 3D average pooling module. """ if dims == 1: return nn.AvgPool1d(*args, **kwargs) elif dims == 2: return nn.AvgPool2d(*args, **kwargs) elif dims == 3: return nn.AvgPool3d(*args, **kwargs) raise ValueError(f"unsupported dimensions: {dims}")
Create a 1D, 2D, or 3D average pooling module.
162,623
import math import numpy as np from inspect import isfunction from typing import Optional, Any, List import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat from diffusers.configuration_utils import ConfigMixin from diffusers.models.modeling_utils import ModelMixin import xformers import xformers.ops from kiui.cam import orbit_camera def default(val, d): if val is not None: return val return d() if isfunction(d) else d
null
162,624
import torch import torch.nn as nn class Embedder: def __init__(self, **kwargs): self.kwargs = kwargs self.create_embedding_fn() def create_embedding_fn(self): embed_fns = [] d = self.kwargs['input_dims'] out_dim = 0 if self.kwargs['include_input']: embed_fns.append(lambda x: x) out_dim += d max_freq = self.kwargs['max_freq_log2'] N_freqs = self.kwargs['num_freqs'] if self.kwargs['log_sampling']: freq_bands = 2. ** torch.linspace(0., max_freq, N_freqs) else: freq_bands = torch.linspace(2.**0., 2.**max_freq, N_freqs) for freq in freq_bands: for p_fn in self.kwargs['periodic_fns']: embed_fns.append(lambda x, p_fn=p_fn, freq=freq: p_fn(x * freq)) out_dim += d self.embed_fns = embed_fns self.out_dim = out_dim def embed(self, inputs): return torch.cat([fn(inputs) for fn in self.embed_fns], -1) def get_embedder(multires, input_dims=3): embed_kwargs = { 'include_input': True, 'input_dims': input_dims, 'max_freq_log2': multires-1, 'num_freqs': multires, 'log_sampling': True, 'periodic_fns': [torch.sin, torch.cos], } embedder_obj = Embedder(**embed_kwargs) def embed(x, eo=embedder_obj): return eo.embed(x) return embed, embedder_obj.out_dim
null
162,625
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import mcubes def extract_fields(bound_min, bound_max, resolution, query_func): N = 64 X = torch.linspace(bound_min[0], bound_max[0], resolution).split(N) Y = torch.linspace(bound_min[1], bound_max[1], resolution).split(N) Z = torch.linspace(bound_min[2], bound_max[2], resolution).split(N) u = np.zeros([resolution, resolution, resolution], dtype=np.float32) with torch.no_grad(): for xi, xs in enumerate(X): for yi, ys in enumerate(Y): for zi, zs in enumerate(Z): xx, yy, zz = torch.meshgrid(xs, ys, zs) pts = torch.cat([xx.reshape(-1, 1), yy.reshape(-1, 1), zz.reshape(-1, 1)], dim=-1) val = query_func(pts.cuda()).reshape(len(xs), len(ys), len(zs)).detach().cpu().numpy() u[xi * N: xi * N + len(xs), yi * N: yi * N + len(ys), zi * N: zi * N + len(zs)] = val return u def extract_geometry(bound_min, bound_max, resolution, threshold, query_func, color_func): u = extract_fields(bound_min, bound_max, resolution, query_func) vertices, triangles = mcubes.marching_cubes(u, threshold) b_max_np = bound_max.detach().cpu().numpy() b_min_np = bound_min.detach().cpu().numpy() vertices = vertices / (resolution - 1.0) * (b_max_np - b_min_np)[None, :] + b_min_np[None, :] vertices_color = color_func(vertices) return vertices, triangles, vertices_color
null
162,626
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import mcubes def sample_pdf(bins, weights, n_samples, det=False): # This implementation is from NeRF # Get pdf device = weights.device weights = weights + 1e-5 # prevent nans pdf = weights / torch.sum(weights, -1, keepdim=True) cdf = torch.cumsum(pdf, -1) cdf = torch.cat([torch.zeros_like(cdf[..., :1]), cdf], -1) # Take uniform samples if det: u = torch.linspace(0. + 0.5 / n_samples, 1. - 0.5 / n_samples, steps=n_samples).to(device) u = u.expand(list(cdf.shape[:-1]) + [n_samples]) else: u = torch.rand(list(cdf.shape[:-1]) + [n_samples]).to(device) # Invert CDF u = u.contiguous() inds = torch.searchsorted(cdf, u, right=True) below = torch.max(torch.zeros_like(inds - 1).to(device), inds - 1) above = torch.min((cdf.shape[-1] - 1) * torch.ones_like(inds).to(device), inds) inds_g = torch.stack([below, above], -1) # (batch, N_samples, 2) matched_shape = [inds_g.shape[0], inds_g.shape[1], cdf.shape[-1]] cdf_g = torch.gather(cdf.unsqueeze(1).expand(matched_shape), 2, inds_g) bins_g = torch.gather(bins.unsqueeze(1).expand(matched_shape), 2, inds_g) denom = (cdf_g[..., 1] - cdf_g[..., 0]) denom = torch.where(denom < 1e-5, torch.ones_like(denom).to(device), denom) t = (u - cdf_g[..., 0]) / denom samples = bins_g[..., 0] + t * (bins_g[..., 1] - bins_g[..., 0]) return samples
null
162,627
import numpy as np def camNormal2worldNormal(rot_c2w, camNormal): H,W,_ = camNormal.shape normal_img = np.matmul(rot_c2w[None, :, :], camNormal.reshape(-1,3)[:, :, None]).reshape([H, W, 3]) return normal_img
null
162,628
import numpy as np def worldNormal2camNormal(rot_w2c, normal_map_world): def trans_normal(normal, RT_w2c, RT_w2c_target): # normal_world = camNormal2worldNormal(np.linalg.inv(RT_w2c[:3,:3]), normal) # normal_target_cam = worldNormal2camNormal(RT_w2c_target[:3,:3], normal_world) relative_RT = np.matmul(RT_w2c_target[:3,:3], np.linalg.inv(RT_w2c[:3,:3])) normal_target_cam = worldNormal2camNormal(relative_RT[:3,:3], normal) return normal_target_cam
null
162,629
import numpy as np def img2normal(img): return (img/255.)*2-1
null
162,630
import numpy as np def normal2img(normal): return np.uint8((normal*0.5+0.5)*255)
null
162,631
import numpy as np def norm_normalize(normal, dim=-1): normal = normal/(np.linalg.norm(normal, axis=dim, keepdims=True)+1e-6) return normal
null
162,632
import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `visualize_depth_numpy` function. Write a Python function `def visualize_depth_numpy(depth, minmax=None, cmap=cv2.COLORMAP_JET)` to solve the following problem: depth: (H, W) Here is the function: def visualize_depth_numpy(depth, minmax=None, cmap=cv2.COLORMAP_JET): """ depth: (H, W) """ x = np.nan_to_num(depth) # change nan to 0 if minmax is None: mi = np.min(x[x > 0]) # get minimum positive depth (ignore background) ma = np.max(x) else: mi, ma = minmax x = (x - mi) / (ma - mi + 1e-8) # normalize to 0~1 x = (255 * x).astype(np.uint8) x_ = cv2.applyColorMap(x, cmap) return x_, [mi, ma]
depth: (H, W)
162,633
import torch import torch.nn.functional as F import cv2 import numpy as np import os from glob import glob from scipy.spatial.transform import Rotation as Rot from scipy.spatial.transform import Slerp from glob import glob from shared_utils.image_utils import prepare_torch_img def camNormal2worldNormal(rot_c2w, camNormal): H,W,_ = camNormal.shape normal_img = np.matmul(rot_c2w[None, :, :], camNormal.reshape(-1,3)[:, :, None]).reshape([H, W, 3]) return normal_img def worldNormal2camNormal(rot_w2c, worldNormal): H,W,_ = worldNormal.shape normal_img = np.matmul(rot_w2c[None, :, :], worldNormal.reshape(-1,3)[:, :, None]).reshape([H, W, 3]) return normal_img def trans_normal(normal, RT_w2c, RT_w2c_target): normal_world = camNormal2worldNormal(np.linalg.inv(RT_w2c[:3,:3]), normal) normal_target_cam = worldNormal2camNormal(RT_w2c_target[:3,:3], normal_world) return normal_target_cam
null
162,634
import torch import torch.nn.functional as F import cv2 import numpy as np import os from glob import glob from scipy.spatial.transform import Rotation as Rot from scipy.spatial.transform import Slerp from glob import glob from shared_utils.image_utils import prepare_torch_img def img2normal(img): return (img/255.)*2-1
null
162,635
import torch import torch.nn.functional as F import cv2 import numpy as np import os from glob import glob from scipy.spatial.transform import Rotation as Rot from scipy.spatial.transform import Slerp from glob import glob from shared_utils.image_utils import prepare_torch_img def normal2img(normal): return np.uint8((normal*0.5+0.5)*255)
null
162,636
import torch import torch.nn.functional as F import cv2 import numpy as np import os from glob import glob from scipy.spatial.transform import Rotation as Rot from scipy.spatial.transform import Slerp from glob import glob from shared_utils.image_utils import prepare_torch_img def norm_normalize(normal, dim=-1): normal = normal/(np.linalg.norm(normal, axis=dim, keepdims=True)+1e-6) return normal
null
162,637
import torch import torch.nn.functional as F import cv2 import numpy as np import os from glob import glob from scipy.spatial.transform import Rotation as Rot from scipy.spatial.transform import Slerp from glob import glob from shared_utils.image_utils import prepare_torch_img def camNormal2worldNormal(rot_c2w, camNormal): H,W,_ = camNormal.shape normal_img = np.matmul(rot_c2w[None, :, :], camNormal.reshape(-1,3)[:, :, None]).reshape([H, W, 3]) return normal_img def RT_opengl2opencv(RT): # Build the coordinate transform matrix from world to computer vision camera # R_world2cv = R_bcam2cv@R_world2bcam # T_world2cv = R_bcam2cv@T_world2bcam R = RT[:3, :3] t = RT[:3, 3] R_bcam2cv = np.asarray([[1, 0, 0], [0, -1, 0], [0, 0, -1]], np.float32) R_world2cv = R_bcam2cv @ R t_world2cv = R_bcam2cv @ t RT = np.concatenate([R_world2cv,t_world2cv[:,None]],1) return RT def normal_opengl2opencv(normal): H,W,C = np.shape(normal) # normal_img = np.reshape(normal, (H*W,C)) R_bcam2cv = np.array([1, -1, -1], np.float32) normal_cv = normal * R_bcam2cv[None, None, :] return normal_cv def inv_RT(RT): RT_h = np.concatenate([RT, np.array([[0,0,0,1]])], axis=0) RT_inv = np.linalg.inv(RT_h) return RT_inv[:3, :] def prepare_torch_img(img, size_H, size_W, device="cuda", keep_shape=False): # [N, H, W, C] -> [N, C, H, W] img_new = img.permute(0, 3, 1, 2).to(device) img_new = F.interpolate(img_new, (size_H, size_W), mode="bilinear", align_corners=False).contiguous() if keep_shape: img_new = img_new.permute(0, 2, 3, 1) return img_new def load_pose_and_preprocess(mv_images, mv_masks, mv_normals, imSize, view_types, cam_pose_dir=None, normal_system='front'): all_images = [] all_masks = [] all_normals = [] all_normals_world = [] all_poses = [] all_w2cs = [] RT_front = np.loadtxt(glob(os.path.join(cam_pose_dir, '*_%s_RT.txt'%( 'front')))[0]) # world2cam matrix RT_front_cv = RT_opengl2opencv(RT_front) # convert normal from opengl to opencv img_H, img_W = imSize[0], imSize[1] # rgb to bgr mv_images = mv_images[:, :, :, [2, 1, 0]].contiguous() for idx, view in enumerate(view_types): image = prepare_torch_img(mv_images[idx].unsqueeze(0), img_H, img_W, keep_shape=True).squeeze(0).detach().cpu().numpy() mask = prepare_torch_img(mv_masks[idx].unsqueeze(2).unsqueeze(0), img_H, img_W, keep_shape=True).squeeze(0).squeeze(2).detach().cpu().numpy() normal = prepare_torch_img(mv_normals[idx].unsqueeze(0), img_H, img_W, keep_shape=True).detach().squeeze(0).cpu().numpy() RT = np.loadtxt(os.path.join(cam_pose_dir, '000_%s_RT.txt'%( view))) # world2cam matrix # [0, 1] -> [-1, 1] normal = normal * 2 - 1 normal[mask==0] = [0,0,0] RT_cv = RT_opengl2opencv(RT) # convert normal from opengl to opencv all_poses.append(inv_RT(RT_cv)) # cam2world all_w2cs.append(RT_cv) # whether to normal_cam_cv = normal_opengl2opencv(normal) if normal_system == 'front': normal_world = camNormal2worldNormal(inv_RT(RT_front_cv)[:3, :3], normal_cam_cv) elif normal_system == 'self': normal_world = camNormal2worldNormal(inv_RT(RT_cv)[:3, :3], normal_cam_cv) all_images.append(image) all_masks.append(mask) all_normals.append(normal_cam_cv) all_normals_world.append(normal_world) return np.stack(all_images), np.stack(all_masks), np.stack(all_normals), np.stack(all_normals_world), np.stack(all_poses), np.stack(all_w2cs)
null
162,638
import server import folder_paths as comfy_paths import os from ..shared_utils.common_utils import cstr web_conf = None def set_web_conf(new_web_conf): global web_conf web_conf = new_web_conf
null
162,639
import server import folder_paths as comfy_paths import os from ..shared_utils.common_utils import cstr web = server.web SUPPORTED_VIEW_EXTENSIONS = ( '.png', '.jpg', '.jpeg ', '.mtl', '.obj', '.glb', '.ply', '.splat' ) web_conf = None class cstr(str): # Modified from: WAS Node Suite class color: END = '\33[0m' BOLD = '\33[1m' ITALIC = '\33[3m' UNDERLINE = '\33[4m' BLINK = '\33[5m' BLINK2 = '\33[6m' SELECTED = '\33[7m' BLACK = '\33[30m' RED = '\33[31m' GREEN = '\33[32m' YELLOW = '\33[33m' BLUE = '\33[34m' VIOLET = '\33[35m' BEIGE = '\33[36m' WHITE = '\33[37m' BLACKBG = '\33[40m' REDBG = '\33[41m' GREENBG = '\33[42m' YELLOWBG = '\33[43m' BLUEBG = '\33[44m' VIOLETBG = '\33[45m' BEIGEBG = '\33[46m' WHITEBG = '\33[47m' GREY = '\33[90m' LIGHTRED = '\33[91m' LIGHTGREEN = '\33[92m' LIGHTYELLOW = '\33[93m' LIGHTBLUE = '\33[94m' LIGHTVIOLET = '\33[95m' LIGHTBEIGE = '\33[96m' LIGHTWHITE = '\33[97m' GREYBG = '\33[100m' LIGHTREDBG = '\33[101m' LIGHTGREENBG = '\33[102m' LIGHTYELLOWBG = '\33[103m' LIGHTBLUEBG = '\33[104m' LIGHTVIOLETBG = '\33[105m' LIGHTBEIGEBG = '\33[106m' LIGHTWHITEBG = '\33[107m' def add_code(name, code): if not hasattr(cstr.color, name.upper()): setattr(cstr.color, name.upper(), code) else: raise ValueError(f"'cstr' object already contains a code with the name '{name}'.") def __new__(cls, text): return super().__new__(cls, text) def __getattr__(self, attr): if attr.lower().startswith("_cstr"): code = getattr(self.color, attr.upper().lstrip("_cstr")) modified_text = self.replace(f"__{attr[1:]}__", f"{code}") return cstr(modified_text) elif attr.upper() in dir(self.color): code = getattr(self.color, attr.upper()) modified_text = f"{code}{self}{self.color.END}" return cstr(modified_text) elif attr.lower() in dir(cstr): return getattr(cstr, attr.lower()) else: raise AttributeError(f"'cstr' object has no attribute '{attr}'") def print(self, **kwargs): print(self, **kwargs) cstr.color.add_code("msg", f"{cstr.color.BLUE}[Comfy3D] {cstr.color.END}") cstr.color.add_code("warning", f"{cstr.color.LIGHTYELLOW}[Comfy3D] [WARNING] {cstr.color.END}") cstr.color.add_code("error", f"{cstr.color.RED}[Comfy3D] [ERROR] {cstr.color.END}") async def view_file(request): query = request.rel_url.query # Security check to see if query client is local if request.remote in web_conf['clients_ip'] and "filepath" in query: filepath = query["filepath"] cstr(f"[Server Query view_file] Get file {filepath}").msg.print() if filepath.lower().endswith(SUPPORTED_VIEW_EXTENSIONS) and os.path.exists(filepath): return web.FileResponse(filepath) return web.Response(status=404)
null
162,647
import importlib import math from collections import defaultdict from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Tuple, Union import imageio import numpy as np import PIL.Image import rembg import torch import torch.nn as nn import torch.nn.functional as F import trimesh from omegaconf import DictConfig, OmegaConf from PIL import Image def get_ray_directions( H: int, W: int, focal: Union[float, Tuple[float, float]], principal: Optional[Tuple[float, float]] = None, use_pixel_centers: bool = True, normalize: bool = True, ) -> torch.FloatTensor: def get_rays( directions, c2w, keepdim=False, normalize=False, ) -> Tuple[torch.FloatTensor, torch.FloatTensor]: def get_spherical_cameras( n_views: int, elevation_deg: float, camera_distance: float, fovy_deg: float, height: int, width: int, ): azimuth_deg = torch.linspace(0, 360.0, n_views + 1)[:n_views] elevation_deg = torch.full_like(azimuth_deg, elevation_deg) camera_distances = torch.full_like(elevation_deg, camera_distance) elevation = elevation_deg * math.pi / 180 azimuth = azimuth_deg * math.pi / 180 # convert spherical coordinates to cartesian coordinates # right hand coordinate system, x back, y right, z up # elevation in (-90, 90), azimuth from +x to +y in (-180, 180) camera_positions = torch.stack( [ camera_distances * torch.cos(elevation) * torch.cos(azimuth), camera_distances * torch.cos(elevation) * torch.sin(azimuth), camera_distances * torch.sin(elevation), ], dim=-1, ) # default scene center at origin center = torch.zeros_like(camera_positions) # default camera up direction as +z up = torch.as_tensor([0, 0, 1], dtype=torch.float32)[None, :].repeat(n_views, 1) fovy = torch.full_like(elevation_deg, fovy_deg) * math.pi / 180 lookat = F.normalize(center - camera_positions, dim=-1) right = F.normalize(torch.cross(lookat, up), dim=-1) up = F.normalize(torch.cross(right, lookat), dim=-1) c2w3x4 = torch.cat( [torch.stack([right, up, -lookat], dim=-1), camera_positions[:, :, None]], dim=-1, ) c2w = torch.cat([c2w3x4, torch.zeros_like(c2w3x4[:, :1])], dim=1) c2w[:, 3, 3] = 1.0 # get directions by dividing directions_unit_focal by focal length focal_length = 0.5 * height / torch.tan(0.5 * fovy) directions_unit_focal = get_ray_directions( H=height, W=width, focal=1.0, ) directions = directions_unit_focal[None, :, :, :].repeat(n_views, 1, 1, 1) directions[:, :, :, :2] = ( directions[:, :, :, :2] / focal_length[:, None, None, None] ) # must use normalize=True to normalize directions here rays_o, rays_d = get_rays(directions, c2w, keepdim=True, normalize=True) return rays_o, rays_d
null
162,648
import importlib import math from collections import defaultdict from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Tuple, Union import imageio import numpy as np import PIL.Image import rembg import torch import torch.nn as nn import torch.nn.functional as F import trimesh from omegaconf import DictConfig, OmegaConf from PIL import Image def remove_background( image: PIL.Image.Image, rembg_session: Any = None, force: bool = False, **rembg_kwargs, ) -> PIL.Image.Image: do_remove = True if image.mode == "RGBA" and image.getextrema()[3][0] < 255: do_remove = False do_remove = do_remove or force if do_remove: image = rembg.remove(image, session=rembg_session, **rembg_kwargs) return image
null
162,649
import importlib import math from collections import defaultdict from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Tuple, Union import imageio import numpy as np import PIL.Image import rembg import torch import torch.nn as nn import torch.nn.functional as F import trimesh from omegaconf import DictConfig, OmegaConf from PIL import Image def resize_foreground( image: PIL.Image.Image, ratio: float, ) -> PIL.Image.Image: image = np.array(image) assert image.shape[-1] == 4 alpha = np.where(image[..., 3] > 0) y1, y2, x1, x2 = ( alpha[0].min(), alpha[0].max(), alpha[1].min(), alpha[1].max(), ) # crop the foreground fg = image[y1:y2, x1:x2] # pad to square size = max(fg.shape[0], fg.shape[1]) ph0, pw0 = (size - fg.shape[0]) // 2, (size - fg.shape[1]) // 2 ph1, pw1 = size - fg.shape[0] - ph0, size - fg.shape[1] - pw0 new_image = np.pad( fg, ((ph0, ph1), (pw0, pw1), (0, 0)), mode="constant", constant_values=((0, 0), (0, 0), (0, 0)), ) # compute padding according to the ratio new_size = int(new_image.shape[0] / ratio) # pad to size, double side ph0, pw0 = (new_size - size) // 2, (new_size - size) // 2 ph1, pw1 = new_size - size - ph0, new_size - size - pw0 new_image = np.pad( new_image, ((ph0, ph1), (pw0, pw1), (0, 0)), mode="constant", constant_values=((0, 0), (0, 0), (0, 0)), ) new_image = PIL.Image.fromarray(new_image) return new_image
null
162,651
import importlib import math from collections import defaultdict from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Tuple, Union import imageio import numpy as np import PIL.Image import rembg import torch import torch.nn as nn import torch.nn.functional as F import trimesh from omegaconf import DictConfig, OmegaConf from PIL import Image def to_gradio_3d_orientation(mesh): mesh.apply_transform(trimesh.transformations.rotation_matrix(-np.pi/2, [1, 0, 0])) mesh.apply_scale([1, 1, -1]) mesh.apply_transform(trimesh.transformations.rotation_matrix(np.pi/2, [0, 1, 0])) return mesh
null
162,652
import numpy as np import math from scipy.spatial.transform import Rotation as R import torch def look_at(campos, target, opengl=True): # campos: [N, 3], camera/eye position # target: [N, 3], object to look at # return: [N, 3, 3], rotation matrix if not opengl: # camera forward aligns with -z forward_vector = safe_normalize(target - campos) up_vector = np.array([0, 1, 0], dtype=np.float32) right_vector = safe_normalize(np.cross(forward_vector, up_vector)) up_vector = safe_normalize(np.cross(right_vector, forward_vector)) else: # camera forward aligns with +z forward_vector = safe_normalize(campos - target) up_vector = np.array([0, 1, 0], dtype=np.float32) right_vector = safe_normalize(np.cross(up_vector, forward_vector)) up_vector = safe_normalize(np.cross(forward_vector, right_vector)) R = np.stack([right_vector, up_vector, forward_vector], axis=1) return R The provided code snippet includes necessary dependencies for implementing the `get_look_at_camera_pose` function. Write a Python function `def get_look_at_camera_pose(target, target_to_cam_offset, look_distance=0.1, opengl=True)` to solve the following problem: Calculate the pose (cam2world) matrix from target position the camera suppose to look at and offset vector from target to camera Args: target (NDArray[float32], shape: 3): the target position the camera suppose to look at target_to_cam_dir (NDArray[float32], shape: 3): offset direction from target to camera look_distance (float, optional): length of offset vector from target to camera. Returns: NDArray[float32]: shape: (4, 4), pose (cam2world) matrix Here is the function: def get_look_at_camera_pose(target, target_to_cam_offset, look_distance=0.1, opengl=True): """ Calculate the pose (cam2world) matrix from target position the camera suppose to look at and offset vector from target to camera Args: target (NDArray[float32], shape: 3): the target position the camera suppose to look at target_to_cam_dir (NDArray[float32], shape: 3): offset direction from target to camera look_distance (float, optional): length of offset vector from target to camera. Returns: NDArray[float32]: shape: (4, 4), pose (cam2world) matrix """ norm=np.linalg.norm(target_to_cam_offset) if norm==0: norm=np.finfo(np.float32).eps target_to_cam_offset = look_distance * target_to_cam_offset / norm campos = target_to_cam_offset + target # [3] T = np.eye(4, dtype=np.float32) T[:3, :3] = look_at(campos, target, opengl) T[:3, 3] = campos return T
Calculate the pose (cam2world) matrix from target position the camera suppose to look at and offset vector from target to camera Args: target (NDArray[float32], shape: 3): the target position the camera suppose to look at target_to_cam_dir (NDArray[float32], shape: 3): offset direction from target to camera look_distance (float, optional): length of offset vector from target to camera. Returns: NDArray[float32]: shape: (4, 4), pose (cam2world) matrix
162,653
import numpy as np import math from scipy.spatial.transform import Rotation as R import torch def calculate_fovX(H, W, fovy): return 2 * np.arctan(np.tan(fovy / 2) * W / H)
null
162,654
import numpy as np import math from scipy.spatial.transform import Rotation as R import torch def get_projection_matrix(znear, zfar, fovX, fovY): tanHalfFovY = math.tan((fovY / 2)) tanHalfFovX = math.tan((fovX / 2)) P = torch.zeros(4, 4) z_sign = 1.0 P[0, 0] = 1 / tanHalfFovX P[1, 1] = 1 / tanHalfFovY P[3, 2] = z_sign P[2, 2] = z_sign * zfar / (zfar - znear) P[2, 3] = -(zfar * znear) / (zfar - znear) return P
null
162,655
import torch import torch.nn.functional as F import numpy as np from PIL import Image The provided code snippet includes necessary dependencies for implementing the `torch_img_to_pil_rgba` function. Write a Python function `def torch_img_to_pil_rgba(img, mask)` to solve the following problem: img (torch): [1, H, W, C] or [H, W, C] mask (torch): [1, H, W] or [H, W] Here is the function: def torch_img_to_pil_rgba(img, mask): """ img (torch): [1, H, W, C] or [H, W, C] mask (torch): [1, H, W] or [H, W] """ if len(img.shape) == 4: img = img.squeeze(0) if len(mask.shape) == 3: mask = mask.squeeze(0).unsqueeze(2) single_image = torch.cat((img, mask), dim=2).detach().cpu().numpy() single_image = Image.fromarray((single_image * 255).astype(np.uint8), mode="RGBA") return single_image
img (torch): [1, H, W, C] or [H, W, C] mask (torch): [1, H, W] or [H, W]
162,656
import os from os import listdir from os.path import isfile, join, exists import sys from datetime import datetime def get_persistent_directory(folder_name): if sys.platform == "win32": folder = join(os.path.expanduser("~"), "AppData", "Local", folder_name) else: folder = join(os.path.expanduser("~"), "." + folder_name) os.makedirs(folder, exist_ok=True) return folder
null