id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
33,319
import gzip import json import os import warnings from dataclasses import dataclass, field from typing import List import cv2 import numpy as np import pytorch_lightning as pl import torch import torchvision.transforms.functional as TF from PIL import Image from torch.utils.data import DataLoader, Dataset, IterableData...
null
33,320
import gzip import json import os import warnings from dataclasses import dataclass, field from typing import List import cv2 import numpy as np import pytorch_lightning as pl import torch import torchvision.transforms.functional as TF from PIL import Image from torch.utils.data import DataLoader, Dataset, IterableData...
null
33,321
import gzip import json import os import warnings from dataclasses import dataclass, field from typing import List import cv2 import numpy as np import pytorch_lightning as pl import torch import torchvision.transforms.functional as TF from PIL import Image from torch.utils.data import DataLoader, Dataset, IterableData...
null
33,322
import gzip import json import os import warnings from dataclasses import dataclass, field from typing import List import cv2 import numpy as np import pytorch_lightning as pl import torch import torchvision.transforms.functional as TF from PIL import Image from torch.utils.data import DataLoader, Dataset, IterableData...
null
33,323
import gzip import json import os import warnings from dataclasses import dataclass, field from typing import List import cv2 import numpy as np import pytorch_lightning as pl import torch import torchvision.transforms.functional as TF from PIL import Image from torch.utils.data import DataLoader, Dataset, IterableData...
null
33,324
import gzip import json import os import warnings from dataclasses import dataclass, field from typing import List import cv2 import numpy as np import pytorch_lightning as pl import torch import torchvision.transforms.functional as TF from PIL import Image from torch.utils.data import DataLoader, Dataset, IterableData...
Get a similarity transform to normalize dataset from c2w (OpenCV convention) cameras :param c2w: (N, 4) :return T (4,4) , scale (float)
33,325
import sys import warnings from bisect import bisect_right import torch import torch.nn as nn from torch.optim import lr_scheduler import threestudio def get_parameters(model, name): module = getattr_recursive(model, name) if isinstance(module, nn.Module): return module.parameters() elif isinstance(...
null
33,326
import sys import warnings from bisect import bisect_right import torch import torch.nn as nn from torch.optim import lr_scheduler import threestudio def parse_scheduler_to_instance(config, optimizer): if config.name == "ChainedScheduler": schedulers = [ parse_scheduler_to_instance(conf, optimi...
null
33,327
import sys import warnings from bisect import bisect_right import torch import torch.nn as nn from torch.optim import lr_scheduler import threestudio def get_scheduler(name): if hasattr(lr_scheduler, name): return getattr(lr_scheduler, name) else: raise NotImplementedError def parse_scheduler(c...
null
33,328
import math from typing import List import torch from torch import Tensor from torch.optim.optimizer import Optimizer def _single_tensor_adan( params: List[Tensor], grads: List[Tensor], exp_avgs: List[Tensor], exp_avg_sqs: List[Tensor], exp_avg_diffs: List[Tensor], neg_pre_grads: List[Tensor], ...
null
33,329
import math from typing import List import torch from torch import Tensor from torch.optim.optimizer import Optimizer def _multi_tensor_adan( params: List[Tensor], grads: List[Tensor], exp_avgs: List[Tensor], exp_avg_sqs: List[Tensor], exp_avg_diffs: List[Tensor], neg_pre_grads: List[Tensor], ...
null
33,330
import argparse import glob import os import imageio import numpy as np from PIL import Image, ImageDraw from tqdm import tqdm def draw_text_in_image(img, texts): img = Image.fromarray(img) draw = ImageDraw.Draw(img) black, white = (0, 0, 0), (255, 255, 255) for i, text in enumerate(texts): draw...
null
33,331
def depth_rgb_to_grey(depth_filename): # depth_filename = "image_depth.png" import cv2 import numpy as np # import shutil # shutil.copyfile(depth_filename, depth_filename.replace("_depth", "_depth_orig")) depth = cv2.imread(depth_filename) depth = cv2.cvtColor(depth, cv2.COLOR_BGR2GRAY) ...
null
33,332
def normal_mask(normal_filename): # filename = "image_normal.png" import cv2 # import shutil # shutil.copyfile(normal_filename, normal_filename.replace("_normal", "_normal_orig")) normal = cv2.imread(normal_filename) mask = ( cv2.resize( cv2.imread( normal_...
null
33,333
import json import os from dataclasses import dataclass, field import torch import torch.multiprocessing as mp import torch.nn as nn import torch.nn.functional as F from pytorch_lightning.utilities.rank_zero import rank_zero_only from transformers import AutoTokenizer, BertForMaskedLM import threestudio from threestudi...
null
33,334
import json import os from dataclasses import dataclass, field import torch import torch.multiprocessing as mp import torch.nn as nn import torch.nn.functional as F from pytorch_lightning.utilities.rank_zero import rank_zero_only from transformers import AutoTokenizer, BertForMaskedLM import threestudio from threestudi...
null
33,335
from dataclasses import dataclass, field import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import threestudio from threestudio.models.isosurface import ( IsosurfaceHelper, MarchingCubeCPUHelper, MarchingTetrahedraHelper, ) from threestudio.models.mesh import Mesh from thr...
null
33,336
from typing import Callable, List, Optional, Tuple import torch from nerfacc.data_specs import RayIntervals from nerfacc.estimators.base import AbstractEstimator from nerfacc.pdf import importance_sampling, searchsorted from nerfacc.volrend import render_transmittance_from_density from torch import Tensor def _transfo...
null
33,337
import math import tinycudann as tcnn import torch import torch.nn as nn import torch.nn.functional as F import threestudio from threestudio.utils.base import Updateable from threestudio.utils.config import config_to_primitive from threestudio.utils.misc import get_rank from threestudio.utils.ops import get_activation ...
null
33,338
from dataclasses import dataclass from functools import partial import nerfacc import torch import torch.nn as nn import torch.nn.functional as F import threestudio from threestudio.models.background.base import BaseBackground from threestudio.models.estimators import ImportanceEstimator from threestudio.models.geometr...
null
33,339
import importlib import os from dataclasses import dataclass, field import cv2 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from diffusers import DDIMScheduler, DDPMScheduler, StableDiffusionPipeline from diffusers.utils.import_utils import is_xformers_available from omegaconf i...
null
33,341
import hashlib import os import requests from tqdm import tqdm URL_MAP = {"vgg_lpips": "https://heibox.uni-heidelberg.de/f/607503859c864bc1b30b/?dl=1"} CKPT_MAP = {"vgg_lpips": "vgg.pth"} MD5_MAP = {"vgg_lpips": "d507d7349b931f0638a25a48a722f98a"} def download(url, local_path, chunk_size=1024): os.makedirs(os.path....
null
33,342
import hashlib import os import requests from tqdm import tqdm class KeyNotFoundError(Exception): def __init__(self, cause, keys=None, visited=None): self.cause = cause self.keys = keys self.visited = visited messages = list() if keys is not None: messages.append(...
Given a nested list or dict return the desired value at key expanding callable nodes if necessary and :attr:`expand` is ``True``. The expansion is done in-place. Parameters ---------- list_or_dict : list or dict Possibly nested list or dictionary. key : str key/to/value, path like string describing all keys necessary t...
33,343
from collections import namedtuple from dataclasses import dataclass, field import torch import torch.nn as nn from torchvision import models import threestudio from threestudio.utils.base import BaseObject from threestudio.utils.perceptual.utils import get_ckpt_path from threestudio.utils.typing import * def normaliz...
null
33,344
from collections import namedtuple from dataclasses import dataclass, field import torch import torch.nn as nn from torchvision import models import threestudio from threestudio.utils.base import BaseObject from threestudio.utils.perceptual.utils import get_ckpt_path from threestudio.utils.typing import * def spatial_...
null
33,345
import os from dataclasses import dataclass, field from datetime import datetime from omegaconf import OmegaConf import threestudio from threestudio.utils.typing import * def config_to_primitive(config, resolve: bool = True) -> Any: return OmegaConf.to_container(config, resolve=resolve) def C_max(value: Any) -> fl...
null
33,346
import os from dataclasses import dataclass, field from datetime import datetime from omegaconf import OmegaConf import threestudio from threestudio.utils.typing import * OmegaConf.register_new_resolver( "calc_exp_lr_decay_rate", lambda factor, n: factor ** (1.0 / n) ) OmegaConf.register_new_resolver("add", lambda ...
null
33,347
import os from dataclasses import dataclass, field from datetime import datetime from omegaconf import OmegaConf import threestudio from threestudio.utils.typing import * OmegaConf.register_new_resolver( "calc_exp_lr_decay_rate", lambda factor, n: factor ** (1.0 / n) ) OmegaConf.register_new_resolver("add", lambda ...
null
33,348
import gc import math import os import re import tinycudann as tcnn import torch from packaging import version from threestudio.utils.config import config_to_primitive from threestudio.utils.typing import * def parse_version(ver: str): return version.parse(ver)
null
33,349
import gc import math import os import re import tinycudann as tcnn import torch from packaging import version from threestudio.utils.config import config_to_primitive from threestudio.utils.typing import * def get_device(): return torch.device(f"cuda:{get_rank()}") def load_module_weights( path, module_name=N...
null
33,350
import gc import math import os import re import tinycudann as tcnn import torch from packaging import version from threestudio.utils.config import config_to_primitive from threestudio.utils.typing import * def config_to_primitive(config, resolve: bool = True) -> Any: return OmegaConf.to_container(config, resolve=...
null
33,351
import gc import math import os import re import tinycudann as tcnn import torch from packaging import version from threestudio.utils.config import config_to_primitive from threestudio.utils.typing import * def cleanup(): gc.collect() torch.cuda.empty_cache() tcnn.free_temporary_memory() def finish_with_cl...
null
33,352
import gc import math import os import re import tinycudann as tcnn import torch from packaging import version from threestudio.utils.config import config_to_primitive from threestudio.utils.typing import * def _distributed_available(): return torch.distributed.is_available() and torch.distributed.is_initialized() ...
null
33,353
import gc import math import os import re import tinycudann as tcnn import torch from packaging import version from threestudio.utils.config import config_to_primitive from threestudio.utils.typing import * def _distributed_available(): def broadcast(tensor, src=0): if not _distributed_available(): return ...
null
33,354
import gc import math import os import re import tinycudann as tcnn import torch from packaging import version from threestudio.utils.config import config_to_primitive from threestudio.utils.typing import * def enable_gradient(model, enabled: bool = True) -> None: for param in model.parameters(): param.req...
null
33,355
import gc import math import os import re import tinycudann as tcnn import torch from packaging import version from threestudio.utils.config import config_to_primitive from threestudio.utils.typing import * def find_last_path(path: str): if (path is not None) and ("LAST" in path): path = path.replace(" ", ...
null
33,356
import torch def _tensor_size(t): def tv_loss(x): batch_size = x.size()[0] h_x = x.size()[2] w_x = x.size()[3] count_h = _tensor_size(x[:, :, 1:, :]) count_w = _tensor_size(x[:, :, :, 1:]) h_tv = torch.pow((x[:, :, 1:, :] - x[:, :, : h_x - 1, :]), 2).sum() w_tv = torch.pow((x[:, :, :, 1:] -...
null
33,357
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
null
33,358
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
null
33,359
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
null
33,360
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
Get ray directions for all pixels in camera coordinate. Reference: https://www.scratchapixel.com/lessons/3d-basic-rendering/ ray-tracing-generating-camera-rays/standard-coordinate-systems Inputs: H, W, focal, principal, use_pixel_centers: image height, width, focal length, principal point and whether use pixel centers ...
33,361
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
null
33,362
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
null
33,363
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
null
33,364
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
null
33,365
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
null
33,366
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
null
33,367
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
F.binary_cross_entropy is not numerically stable in mixed-precision training.
33,368
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
null
33,369
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
null
33,370
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
null
33,371
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
null
33,372
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
null
33,373
import math from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from igl import fast_winding_number_for_meshes, point_mesh_squared_distance, read_obj from torch.autograd import Function from torch.cuda.amp import custom_bwd, custom_fwd import threest...
null
33,374
from dataclasses import dataclass import torch import torch.nn as nn from threestudio.utils.config import parse_structured from threestudio.utils.misc import get_device, load_module_weights from threestudio.utils.typing import * class Updateable: def do_update_step( self, epoch: int, global_step: int, on_lo...
null
33,375
from dataclasses import dataclass import torch import torch.nn as nn from threestudio.utils.config import parse_structured from threestudio.utils.misc import get_device, load_module_weights from threestudio.utils.typing import * class Updateable: def do_update_step( self, epoch: int, global_step: int, on_lo...
null
33,376
import importlib import multiprocessing as mp from collections import abc from functools import partial from inspect import isfunction from queue import Queue from threading import Thread import numpy as np import torch from einops import rearrange from PIL import Image, ImageDraw, ImageFont def log_txt_as_img(wh, xc,...
null
33,377
import importlib import multiprocessing as mp from collections import abc from functools import partial from inspect import isfunction from queue import Queue from threading import Thread import numpy as np import torch from einops import rearrange from PIL import Image, ImageDraw, ImageFont def ismap(x): if not i...
null
33,378
import importlib import multiprocessing as mp from collections import abc from functools import partial from inspect import isfunction from queue import Queue from threading import Thread import numpy as np import torch from einops import rearrange from PIL import Image, ImageDraw, ImageFont def isimage(x): if not...
null
33,379
import importlib import multiprocessing as mp from collections import abc from functools import partial from inspect import isfunction from queue import Queue from threading import Thread import numpy as np import torch from einops import rearrange from PIL import Image, ImageDraw, ImageFont def exists(x): return x...
null
33,380
import importlib import multiprocessing as mp from collections import abc from functools import partial from inspect import isfunction from queue import Queue from threading import Thread import numpy as np import torch from einops import rearrange from PIL import Image, ImageDraw, ImageFont The provided code snippet ...
https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86 Take the mean over all non-batch dimensions.
33,381
import importlib import multiprocessing as mp from collections import abc from functools import partial from inspect import isfunction from queue import Queue from threading import Thread import numpy as np import torch from einops import rearrange from PIL import Image, ImageDraw, ImageFont def count_params(model, ve...
null
33,382
import importlib import multiprocessing as mp from collections import abc from functools import partial from inspect import isfunction from queue import Queue from threading import Thread import numpy as np import torch from einops import rearrange from PIL import Image, ImageDraw, ImageFont def get_obj_from_str(string...
null
33,383
import importlib import multiprocessing as mp from collections import abc from functools import partial from inspect import isfunction from queue import Queue from threading import Thread import numpy as np import torch from einops import rearrange from PIL import Image, ImageDraw, ImageFont def _do_parallel_data_prefe...
null
33,384
import math from inspect import isfunction import torch import torch.nn.functional as F from einops import rearrange, repeat from torch import einsum, nn from threestudio.utils.GAN.network_util import checkpoint def uniq(arr): return {el: True for el in arr}.keys()
null
33,385
import math from inspect import isfunction import torch import torch.nn.functional as F from einops import rearrange, repeat from torch import einsum, nn from threestudio.utils.GAN.network_util import checkpoint def exists(val): return val is not None def default(val, d): if exists(val): return val ...
null
33,386
import math from inspect import isfunction import torch import torch.nn.functional as F from einops import rearrange, repeat from torch import einsum, nn from threestudio.utils.GAN.network_util import checkpoint def max_neg_value(t): return -torch.finfo(t.dtype).max
null
33,387
import math from inspect import isfunction import torch import torch.nn.functional as F from einops import rearrange, repeat from torch import einsum, nn from threestudio.utils.GAN.network_util import checkpoint def init_(tensor): dim = tensor.shape[-1] std = 1 / math.sqrt(dim) tensor.uniform_(-std, std) ...
null
33,388
import math from inspect import isfunction import torch import torch.nn.functional as F from einops import rearrange, repeat from torch import einsum, nn from threestudio.utils.GAN.network_util import checkpoint The provided code snippet includes necessary dependencies for implementing the `zero_module` function. Writ...
Zero out the parameters of a module and return it.
33,389
import math from inspect import isfunction import torch import torch.nn.functional as F from einops import rearrange, repeat from torch import einsum, nn from threestudio.utils.GAN.network_util import checkpoint def Normalize(in_channels): return torch.nn.GroupNorm( num_groups=32, num_channels=in_channels,...
null
33,390
import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `normal_kl` function. Write a Python function `def normal_kl(mean1, logvar1, mean2, logvar2)` to solve the following problem: source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c...
source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12 Compute the KL divergence between two gaussians. Shapes are automatically broadcasted, so batches can be compared to scalars, among other use cases.
33,391
import torch import torch.nn as nn import torch.nn.functional as F def conv_bn( inp, oup, stride, conv_layer=nn.Conv2d, norm_layer=nn.BatchNorm2d, nlin_layer=nn.ReLU, ): return nn.Sequential( conv_layer(inp, oup, 3, stride, 1, bias=False), norm_layer(oup), nlin_layer...
null
33,392
import torch import torch.nn as nn import torch.nn.functional as F def conv_1x1_bn( inp, oup, conv_layer=nn.Conv2d, norm_layer=nn.BatchNorm2d, nlin_layer=nn.ReLU ): return nn.Sequential( conv_layer(inp, oup, 1, 1, 0, bias=False), norm_layer(oup), nlin_layer(inplace=True), )
null
33,393
import torch import torch.nn as nn import torch.nn.functional as F def make_divisible(x, divisible_by=8): import numpy as np return int(np.ceil(x * 1.0 / divisible_by) * divisible_by)
null
33,394
import torch import torch.nn as nn import torch.nn.functional as F class MobileNetV3(nn.Module): def __init__( self, n_class=1000, input_size=224, dropout=0.0, mode="small", width_mult=1.0 ): super(MobileNetV3, self).__init__() input_channel = 16 last_channel = 1280 if mo...
null
33,395
import math import os import numpy as np import torch import torch.nn as nn from einops import repeat from threestudio.utils.GAN.util import instantiate_from_config def make_beta_schedule( schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3 ): if schedule == "linear": betas = ( ...
null
33,396
import math import os import numpy as np import torch import torch.nn as nn from einops import repeat from threestudio.utils.GAN.util import instantiate_from_config def make_ddim_timesteps( ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True ): if ddim_discr_method == "uniform": c =...
null
33,397
import math import os import numpy as np import torch import torch.nn as nn from einops import repeat from threestudio.utils.GAN.util import instantiate_from_config def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True): # select alphas for computing the variance schedule alphas = alph...
null
33,398
import math import os import numpy as np import torch import torch.nn as nn from einops import repeat from threestudio.utils.GAN.util import instantiate_from_config The provided code snippet includes necessary dependencies for implementing the `betas_for_alpha_bar` function. Write a Python function `def betas_for_alph...
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-bet...
33,399
import math import os import numpy as np import torch import torch.nn as nn from einops import repeat from threestudio.utils.GAN.util import instantiate_from_config 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
33,400
import math import os import numpy as np import torch import torch.nn as nn from einops import repeat from threestudio.utils.GAN.util import instantiate_from_config class CheckpointFunction(torch.autograd.Function): def forward(ctx, run_function, length, *args): ctx.run_function = run_function ctx.i...
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...
33,401
import math import os import numpy as np import torch import torch.nn as nn from einops import repeat from threestudio.utils.GAN.util import instantiate_from_config The provided code snippet includes necessary dependencies for implementing the `timestep_embedding` function. Write a Python function `def timestep_embedd...
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.
33,402
import math import os import numpy as np import torch import torch.nn as nn from einops import repeat from threestudio.utils.GAN.util import instantiate_from_config The provided code snippet includes necessary dependencies for implementing the `zero_module` function. Write a Python function `def zero_module(module)` t...
Zero out the parameters of a module and return it.
33,403
import math import os import numpy as np import torch import torch.nn as nn from einops import repeat from threestudio.utils.GAN.util import instantiate_from_config The provided code snippet includes necessary dependencies for implementing the `scale_module` function. Write a Python function `def scale_module(module, ...
Scale the parameters of a module and return it.
33,404
import math import os import numpy as np import torch import torch.nn as nn from einops import repeat from threestudio.utils.GAN.util import instantiate_from_config The provided code snippet includes necessary dependencies for implementing the `mean_flat` function. Write a Python function `def mean_flat(tensor)` to so...
Take the mean over all non-batch dimensions.
33,405
import math import os import numpy as np import torch import torch.nn as nn from einops import repeat from threestudio.utils.GAN.util import instantiate_from_config class GroupNorm32(nn.GroupNorm): def forward(self, x): return super().forward(x.float()).type(x.dtype) The provided code snippet includes nece...
Make a standard normalization layer. :param channels: number of input channels. :return: an nn.Module for normalization.
33,406
import math import os import numpy as np import torch import torch.nn as nn from einops import repeat from threestudio.utils.GAN.util import instantiate_from_config The provided code snippet includes necessary dependencies for implementing the `conv_nd` function. Write a Python function `def conv_nd(dims, *args, **kwa...
Create a 1D, 2D, or 3D convolution module.
33,407
import math import os import numpy as np import torch import torch.nn as nn from einops import repeat from threestudio.utils.GAN.util import instantiate_from_config The provided code snippet includes necessary dependencies for implementing the `linear` function. Write a Python function `def linear(*args, **kwargs)` to...
Create a linear module.
33,408
import math import os import numpy as np import torch import torch.nn as nn from einops import repeat from threestudio.utils.GAN.util import instantiate_from_config The provided code snippet includes necessary dependencies for implementing the `avg_pool_nd` function. Write a Python function `def avg_pool_nd(dims, *arg...
Create a 1D, 2D, or 3D average pooling module.
33,409
import math import os import numpy as np import torch import torch.nn as nn from einops import repeat from threestudio.utils.GAN.util import instantiate_from_config def noise_like(shape, device, repeat=False): repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat( shape[0], *((1,) * (le...
null
33,410
import torch import torch.nn.functional as F def generator_loss(discriminator, inputs, reconstructions, cond=None): if cond is None: logits_fake = discriminator(reconstructions.contiguous()) else: logits_fake = discriminator( torch.cat((reconstructions.contiguous(), cond), dim=1) ...
null
33,411
import torch import torch.nn.functional as F def hinge_d_loss(logits_real, logits_fake): loss_real = torch.mean(F.relu(1.0 - logits_real)) loss_fake = torch.mean(F.relu(1.0 + logits_fake)) d_loss = 0.5 * (loss_real + loss_fake) return d_loss def discriminator_loss(discriminator, inputs, reconstructions...
null
33,412
import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from threestudio.utils.GAN.attention import LinearAttention from threestudio.utils.GAN.util import instantiate_from_config The provided code snippet includes necessary dependencies for impleme...
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".
33,413
import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from threestudio.utils.GAN.attention import LinearAttention from threestudio.utils.GAN.util import instantiate_from_config def nonlinearity(x): # swish return x * torch.sigmoid(x)
null
33,414
import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from threestudio.utils.GAN.attention import LinearAttention from threestudio.utils.GAN.util import instantiate_from_config def Normalize(in_channels, num_groups=32): return torch.nn.BatchN...
null
33,415
import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from threestudio.utils.GAN.attention import LinearAttention from threestudio.utils.GAN.util import instantiate_from_config class LinAttnBlock(LinearAttention): """to match AttnBlock usage""...
null
33,416
import functools import torch import torch.nn as nn def count_params(model): total_params = sum(p.numel() for p in model.parameters()) return total_params
null
33,417
import functools import torch import torch.nn as nn def weights_init(m): classname = m.__class__.__name__ if classname.find("Conv") != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find("BatchNorm") != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m....
null
33,418
import os import numpy as np def generate_tetrahedron_grid_file(res=32, root=".."): frac = 1.0 / res command = f"cd {root}; ./quartet meshes/cube.obj {frac} meshes/cube_{res}_tet.tet -s meshes/cube_boundary_{res}.obj" os.system(command)
null
33,419
import os import numpy as np def convert_from_quartet_to_npz(quartetfile="cube_32_tet.tet", npzfile="32_tets"): file1 = open(quartetfile, "r") header = file1.readline() numvertices = int(header.split(" ")[1]) numtets = int(header.split(" ")[2]) print(numvertices, numtets) # load vertices v...
null