id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
23,026 | import torch
from kaolin import _C
import wisp._C as wisp_C
import kaolin.ops.spc as spc_ops
class GridInterpolate(torch.autograd.Function):
def forward(ctx, coords, feats):
feats_out = wisp_C.ops.grid_interpolate_cuda(coords.float().contiguous(),
feats.... | null |
23,027 | import torch
from kaolin import _C
import wisp._C as wisp_C
import kaolin.ops.spc as spc_ops
The provided code snippet includes necessary dependencies for implementing the `hashgrid_query_fwd` function. Write a Python function `def hashgrid_query_fwd(coords, resolutions, codebook_bitwidth, lod_idx, codebook, probe_bit... | Non-differentiable version of hashgrid query. No assumptions on the typing of the codebook. |
23,028 | import torch
from kaolin import _C
import wisp._C as wisp_C
import kaolin.ops.spc as spc_ops
class HashGridQuery(torch.autograd.Function):
def forward(ctx, coords, resolutions, codebook_bitwidth, probe_bitwidth, lod_idx, *codebook):
if codebook[0].shape[-1] % 2 == 1:
raise Exception("The codeboo... | A hash-grid query, accelerated with CUDA. Args: coords (torch.FloatTensor): 3D coordinates of shape [batch, 3] resolutions (torch.LongTensor): the resolution of the grid per level of shape [num_lods] codebook_bitwidth (int): The bitwidth of the codebook. The codebook will have 2^bw entries. lod_idx (int): The LOD to ag... |
23,029 | import torch
import torch.nn.functional as F
from scipy.ndimage import gaussian_filter
from wisp.core import RenderBuffer, Rays
The provided code snippet includes necessary dependencies for implementing the `pointlight_shadow_shader` function. Write a Python function `def pointlight_shadow_shader(rb: RenderBuffer, ray... | Apply shadow rays with one secondary ray towards the pointlight. Args: rb (wisp.core.RenderBuffer): The RenderBuffer. rays (wisp.core.Rays): The rays object. pipeline (wisp.core.Pipeline): The neural field. point_light (list[3] of float): Position of the point light. min_y (float): The location of the xz plane. Returns... |
23,030 | import os
import numpy as np
import torch
from scipy.interpolate import RegularGridInterpolator
from PIL import Image
from wisp.core import RenderBuffer, Rays
from wisp.ops.geometric import spherical_envmap
def matcap_sampler(path, interpolate=True):
"""Fetches MatCap texture & converts to a interpolation function ... | Apply matcap shading. Args: rb (wisp.core.RenderBuffer): The RenderBuffer. rays (wisp.core.Rays): The rays object. matcap_path (str): Path to a matcap. mm (torch.FloatTensor): A 3x3 rotation matrix. Returns: (wisp.core.RenderBuffer): The output RenderBuffer. |
23,031 | import torch
import numpy as np
from .barycentric_coordinates import barycentric_coordinates
from .closest_point import closest_point
from .sample_tex import sample_tex
def barycentric_coordinates(
points : torch.Tensor,
A : torch.Tensor,
B : torch.Tensor,
C : torch.Tensor):
"""
Return barycen... | Returns the closest texture for a set of points. V (torch.FloatTensor): mesh vertices of shape [V, 3] F (torch.LongTensor): mesh face indices of shape [F, 3] TV (torch.FloatTensor): TF (torch.FloatTensor): materials: points (torch.FloatTensor): sample locations of shape [N, 3] Returns: (torch.FloatTensor): texture samp... |
23,032 | import os
import sys
import numpy as np
import tinyobjloader
import torch
from PIL import Image
import logging as log
texopts = [
'ambient_texname',
'diffuse_texname',
'specular_texname',
'specular_highlight_texname',
'bump_texname',
'displacement_texname',
'alpha_texname',
'reflection_t... | Load .obj file using TinyOBJ and extract info. This is more robust since it can triangulate polygon meshes with up to 255 sides per face. Args: fname (str): path to Wavefront .obj file |
23,033 | import torch
The provided code snippet includes necessary dependencies for implementing the `normalize` function. Write a Python function `def normalize( V : torch.Tensor, F : torch.Tensor, mode : str)` to solve the following problem:
Normalizes a mesh. Args: V (torch.FloatTensor): Vertices of shape [V, 3]... | Normalizes a mesh. Args: V (torch.FloatTensor): Vertices of shape [V, 3] F (torch.LongTensor): Faces of shape [F, 3] mode (str): Different methods of normalization. Returns: (torch.FloatTensor, torch.LongTensor): - Normalized Vertices - Faces |
23,034 | import math
import contextlib
import os
import sys
import torch
import numpy as np
import wisp._C as _C
The provided code snippet includes necessary dependencies for implementing the `compute_sdf` function. Write a Python function `def compute_sdf( V : torch.Tensor, F : torch.Tensor, points : torch.Tensor,... | Computes SDF given point samples and a mesh. Args: V (torch.FloatTensor): #V, 3 array of vertices F (torch.LongTensor): #F, 3 array of indices points (torch.FloatTensor): [N, 3] array of points to sample split_size (int): The batch at which the SDF will be computed. The kernel will break for too large batches; when in ... |
23,035 | import torch
from .sample_near_surface import sample_near_surface
from .sample_surface import sample_surface
from .sample_uniform import sample_uniform
from .area_weighted_distribution import area_weighted_distribution
def sample_near_surface(
V : torch.Tensor,
F : torch.Tensor,
num_samples: int,
var... | Sample points from a mesh. Args: V (torch.Tensor): #V, 3 array of vertices F (torch.Tensor): #F, 3 array of indices techniques (list[str]): list of techniques to sample with num_samples (int): points to sample per technique Returns: (torch.FloatTensor): Samples of shape [len(techniques)*num_samples, 3] |
23,036 | import cv2
import torch
The provided code snippet includes necessary dependencies for implementing the `srgb_to_linear` function. Write a Python function `def srgb_to_linear(img)` to solve the following problem:
Converts from SRGB to Linear colorspace. Args: img (torch.FloatTensor): SRGB image. Returns: (torch.FloatTe... | Converts from SRGB to Linear colorspace. Args: img (torch.FloatTensor): SRGB image. Returns: (torch.FloatTensor): Linear image. |
23,037 | import cv2
import torch
The provided code snippet includes necessary dependencies for implementing the `linear_to_srgb` function. Write a Python function `def linear_to_srgb(img)` to solve the following problem:
Converts from Linear to SRGB colorspace. Args: img (torch.FloatTensor): Linear image. Returns: (torch.Float... | Converts from Linear to SRGB colorspace. Args: img (torch.FloatTensor): Linear image. Returns: (torch.FloatTensor): SRGB image. |
23,038 | import cv2
import torch
The provided code snippet includes necessary dependencies for implementing the `resize_mip` function. Write a Python function `def resize_mip(img, mip, interpolation=cv2.INTER_LINEAR)` to solve the following problem:
Resize image with cv2. Args: img (torch.FloatTensor): Image of shape [H, W, 3]... | Resize image with cv2. Args: img (torch.FloatTensor): Image of shape [H, W, 3] mip (int): Rescaling factor. Will rescale by 2**mip. interpolation: Interpolation modes used by `cv2.resize`. Returns: (torch.FloatTensor): Rescaled image of shape [H/(2**mip), W/(2**mip), 3] |
23,039 | import os
import glob
import numpy as np
import torch
import torchvision
The provided code snippet includes necessary dependencies for implementing the `write_exr` function. Write a Python function `def write_exr(path, data)` to solve the following problem:
Writes an EXR image to some path. Data is a dict of form { "d... | Writes an EXR image to some path. Data is a dict of form { "default" = rgb_array, "depth" = depth_array } Args: path (str): Path to save the EXR data (dict): Dictionary of EXR buffers. Returns: (void): Writes to path. |
23,040 | import os
import glob
import numpy as np
import torch
import torchvision
def hwc_to_chw(img):
"""Converts [H,W,C] to [C,H,W] for TensorBoard output.
Args:
img (torch.Tensor): [H,W,C] image.
Returns:
(torch.Tensor): [C,H,W] image.
"""
return img.permute(2, 0, 1)
The provided code sni... | Writes an PNG image to some path. Args: path (str): Path to save the PNG. data (np.array): HWC image. Returns: (void): Writes to path. |
23,041 | import os
import glob
import numpy as np
import torch
import torchvision
The provided code snippet includes necessary dependencies for implementing the `glob_imgs` function. Write a Python function `def glob_imgs(path, exts=['*.png', '*.PNG', '*.jpg', '*.jpeg', '*.JPG', '*.JPEG'])` to solve the following problem:
Util... | Utility to find images in some path. Args: path (str): Path to search images in. exts (list of str): List of extensions to try. Returns: (list of str): List of paths that were found. |
23,042 | import os
import glob
import numpy as np
import torch
import torchvision
def chw_to_hwc(img):
"""Converts [C,H,W] to [H,W,C].
Args:
img (torch.Tensor): [C,H,W] image.
Returns:
(torch.Tensor): [H,W,C] image.
"""
return img.permute(1, 2, 0)
The provided code snippet includes necessary... | Loads an image. Args: path (str): Path to the image. noramlize (bool): If True, will return [0,1] floating point values. Otherwise returns [0,255] ints. Returns: (np.array): Image as an array of shape [H,W,C] |
23,043 | import skimage
import skimage.metrics
import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `psnr` function. Write a Python function `def psnr(rgb, gts)` to solve the following problem:
Calculate the PSNR metric. Assumes the RGB image is in [0,1] Args: rgb (torc... | Calculate the PSNR metric. Assumes the RGB image is in [0,1] Args: rgb (torch.FloatTensor): Image tensor of shape [H,W,3] gts (torch.FloatTensor): Image tensor of shape [H,W,3] Returns: (float): The PSNR score |
23,044 | import skimage
import skimage.metrics
import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `lpips` function. Write a Python function `def lpips(rgb, gts, lpips_model=None)` to solve the following problem:
Calculate the LPIPS metric. Assumes the RGB image is in ... | Calculate the LPIPS metric. Assumes the RGB image is in [0,1] Args: rgb (torch.FloatTensor): Image tensor of shape [H,W,3] gts (torch.FloatTensor): Image tensor of shape [H,W,3] Returns: (float): The LPIPS score |
23,045 | import skimage
import skimage.metrics
import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `ssim` function. Write a Python function `def ssim(rgb, gts)` to solve the following problem:
Calculate the SSIM metric. Assumes the RGB image is in [0,1] Args: rgb (torc... | Calculate the SSIM metric. Assumes the RGB image is in [0,1] Args: rgb (torch.FloatTensor): Image tensor of shape [H,W,3] gts (torch.FloatTensor): Image tensor of shape [H,W,3] Returns: (float): The SSIM score |
23,046 | import numpy as np
import torch
import wisp._C as _C
The provided code snippet includes necessary dependencies for implementing the `find_depth_bound` function. Write a Python function `def find_depth_bound(query, nug_depth, info, curr_idxes=None)` to solve the following problem:
r"""Associate query points to the clos... | r"""Associate query points to the closest depth bound in-order. TODO: Document the input. |
23,047 | import numpy as np
import torch
import wisp._C as _C
The provided code snippet includes necessary dependencies for implementing the `sample_unif_sphere` function. Write a Python function `def sample_unif_sphere(n)` to solve the following problem:
Sample uniformly random points on a sphere. Args: n (int): Number of sam... | Sample uniformly random points on a sphere. Args: n (int): Number of samples. Returns: (np.array): Positions of shape [n, 3] |
23,048 | import numpy as np
import torch
import wisp._C as _C
The provided code snippet includes necessary dependencies for implementing the `sample_fib_sphere` function. Write a Python function `def sample_fib_sphere(n)` to solve the following problem:
Evenly distributed points on sphere using Fibonnaci sequence. From <http:/... | Evenly distributed points on sphere using Fibonnaci sequence. From <http://extremelearning.com.au/evenly-distributing-points-on-a-sphere> WARNING: Order is not randomized. Args: n (int): Number of samples. Returns: (np.array): Positions of shape [n, 3] |
23,049 | import numpy as np
import torch
import wisp._C as _C
def normalized_grid(height, width, jitter=False, device='cuda', use_aspect=True):
"""Returns grid[x,y] -> coordinates for a normalized window.
This is generally confusing and terrible, but in the [XYZ] 3D space, the width generally corresponds to
the XZ a... | Returns a set of 3D coordinates for a slicing plane. Args: height (int): Grid height. width (int): Grid width. dim (int): Dimension to slice along. depth (float): The depth (from the 0 on the axis) for which the slicing will happen. device (str): Device to allocate the grid on. Returns: (torch.FloatTensor): Coords tens... |
23,050 | import numpy as np
import torch
import wisp._C as _C
The provided code snippet includes necessary dependencies for implementing the `spherical_envmap_numpy` function. Write a Python function `def spherical_envmap_numpy(ray_dir, normal)` to solve the following problem:
Computes matcap UV-coordinates from the ray direct... | Computes matcap UV-coordinates from the ray direction and normal. Args: ray_dir (torch.Tensor): incoming ray direction of shape [...., 3] normal (torch.Tensor): surface normal of shape [..., 3] Returns: (torch.FloatTensor): UV coordinates of shape [..., 2] |
23,051 | import torch
The provided code snippet includes necessary dependencies for implementing the `normalize_pointcloud` function. Write a Python function `def normalize_pointcloud(coords, return_scale=False)` to solve the following problem:
Normalizes pointcloud to an AABB within [-1, 1]. Args: coords (torch.FloatTensor): ... | Normalizes pointcloud to an AABB within [-1, 1]. Args: coords (torch.FloatTensor): 3D coordinates of shape [N, 3] return_scale (bool): If True, will return the center of the cloud and the scaling factor. Returns: (torch.FloatTensor) or (torch.FloatTensor, torch.FloatTensor, float): - Normalized 3D coordinates of shape ... |
23,052 | import torch
The provided code snippet includes necessary dependencies for implementing the `create_pointcloud_from_images` function. Write a Python function `def create_pointcloud_from_images(rgbs, masks, rays, depths)` to solve the following problem:
Given depth images, will create a RGB pointcloud. TODO (ttakikawa)... | Given depth images, will create a RGB pointcloud. TODO (ttakikawa): Probably make the input a tensor not a list... Args: rgbs (list of torch.FloatTensor): List of RGB tensors of shape [H, W, 3]. masks (list of torch.FloatTensor): List of mask tensors of shape [H, W, 1]. rays (list of wisp.core.Rays): List of rays.origi... |
23,053 | import torch
def compute_sdf_iou(pred, gts):
"""Compute intersection over union for SDFs.
Args:
pred (torch.FloatTensor): Predicted signed distances
gts (torch.FloatTensor): Groundtruth signed distances
Returns:
(float): The IOU score between 0 and 100.
"""
inside_pred = (pre... | Given a sparse SDF neural field, coordinates, and ground truth SDF, will calculate the narrowband IOU. In the case where the point does not exist in the bounds of the octree, will simply calculate those as intersections. Inputs: nef (wisp.models.NeuralFields) : The neural field. Assumed to be sparse. coords (torch.Floa... |
23,054 | import torch
The provided code snippet includes necessary dependencies for implementing the `sample_spc` function. Write a Python function `def sample_spc( corners : torch.Tensor, level : int, num_samples : int)` to solve the following problem:
Sample uniformly in [-1,1] bounding volume within SP... | Sample uniformly in [-1,1] bounding volume within SPC voxels Args: corners (tensor) : set of corners to sample from level (int) : level to sample from num_samples (int) : number of points to sample Returns: (torch.FloatTensor): samples of shape [num_samples, 3] |
23,055 | import torch
The provided code snippet includes necessary dependencies for implementing the `sample_from_depth_intervals` function. Write a Python function `def sample_from_depth_intervals(depth_intervals, num_samples)` to solve the following problem:
Convert depth intervals to samples. SPC raytrace will return a [num... | Convert depth intervals to samples. SPC raytrace will return a [num_nuggets, 2] array where the first element is the entry depth and the second element is the exit depth. This function will convert them into a [num_nuggets, num_samples, 3] array of samples. Args: depth_intervals (torch.FloatTensor): intervals of shape ... |
23,056 | import torch
The provided code snippet includes necessary dependencies for implementing the `expand_pack_boundary` function. Write a Python function `def expand_pack_boundary(pack_boundary, num_samples)` to solve the following problem:
Expands the pack boundaries according to the number of samples. Args: pack_boundary... | Expands the pack boundaries according to the number of samples. Args: pack_boundary (torch.BoolTensor): pack boundaries [N] num_samples (int): Number of samples Returns: (torch.BoolTensor): pack boundaries of shape [N*num_samples] |
23,057 | import torch
import numpy as np
import kaolin.ops.spc as spc_ops
The provided code snippet includes necessary dependencies for implementing the `create_dense_octree` function. Write a Python function `def create_dense_octree(level)` to solve the following problem:
Creates a dense SPC model Args: level (int): The level... | Creates a dense SPC model Args: level (int): The level at which the octree will be initialized to. Returns: (torch.ByteTensor): the octree tensor |
23,058 | import torch
import numpy as np
import kaolin.ops.spc as spc_ops
The provided code snippet includes necessary dependencies for implementing the `make_trilinear_spc` function. Write a Python function `def make_trilinear_spc(points, pyramid)` to solve the following problem:
Builds a trilinear spc from a regular spc. Arg... | Builds a trilinear spc from a regular spc. Args: points (torch.ShortTensor): The point_hierarchy. pyramid (torch.LongTensor): The pyramid tensor. Returns: (torch.ShortTensor, torch.LongTensor, torch.LongTensor, torch.LongTensor) - The dual point_hierarchy. - The dual pyramid. - The trinkets. - The parent pointers. |
23,059 | import torch
import kaolin.ops.spc as spc_ops
import wisp.ops.mesh as mesh_ops
from wisp.ops.spc.processing import dilate_points
def dilate_points(points, level):
"""Dilates the octree points.
Args:
points (torch.ShortTensor): The SPC points from some level
level (int): The level from which th... | Converts floating point coordinates to an octree. Args: pointcloud (torch.FloatTensor): 3D coordinates in [-1, 1] of shape [N, 3] level (int): Depth of the octreee attributes (torch.FloatTensor): Attributes of shape [N, F]. Will be averaged within voxels. dilate (int): Dilates the octree if specified. Returns: (torch.B... |
23,060 | import torch
import kaolin.ops.spc as spc_ops
import wisp.ops.mesh as mesh_ops
from wisp.ops.spc.processing import dilate_points
def mesh_to_spc(vertices, faces, level, num_samples=100000000):
"""Construct SPC from a mesh.
Args:
vertices (torch.FloatTensor): Vertices of shape [V, 3]
faces (torch... | Builds a trilinear spc from a regular spc. Args: vertices (torch.FloatTensor): Vertices of shape [V, 3] faces (torch.LongTensor): Face indices of shape [F, 3] level (int): The level of the octree Returns: (torch.ByteTensor, torch.ShortTensor, torch.LongTensor, torch.BoolTensor, torch.ShortTensor, torch.LongTensor, torc... |
23,061 | import torch
The provided code snippet includes necessary dependencies for implementing the `total_variation` function. Write a Python function `def total_variation(pidx, trinkets, features, level)` to solve the following problem:
Calculates total variation for the voxels specified by the pidx. Args: pidx : int tensor... | Calculates total variation for the voxels specified by the pidx. Args: pidx : int tensor of size [N] specifying the point indices to calculate TV on. trinkets : the trinkets. features : the features for the given level. (assumes the correct level is given) level : int specifying the level of spc Returns: (torch.FloatTe... |
23,062 | from typing import Union, Type, TYPE_CHECKING, List, Callable, Any, Optional
import dataclasses
The provided code snippet includes necessary dependencies for implementing the `autoconfig` function. Write a Python function `def autoconfig(*classes_and_callables: Type, exclude: List[Callable] = None) -> Any` to solve th... | Generates a list of Config dataclasses for each of the classes or functions (i.e. specific constructors). The class constructors / callables must be type annotated for this function to succeed. Otherwise, see configure(). Specifically, this function will: 1. Inspect the given classes in classes_and_callables and extrac... |
23,063 | from typing import Union, Type, TYPE_CHECKING, List, Callable, Any, Optional
import dataclasses
The provided code snippet includes necessary dependencies for implementing the `configure` function. Write a Python function `def configure(cls=None, /, *, target: Callable[..., Any] = None, import_error: str = None)` to so... | @configure decorates a given dataclass type, cls, as a configuration class that instantiates the target type. Use this function when configuring non-typed constructors, for example: ``` @configure(target=torch.optim.Adam) # This config can build torch.optim.Adam class ConfigAdam: lr: float betas: Tuple[float, float] = ... |
23,064 | from typing import Union, Type, TYPE_CHECKING, List, Callable, Any, Optional
import dataclasses
The provided code snippet includes necessary dependencies for implementing the `instantiate` function. Write a Python function `def instantiate(config, **kwargs)` to solve the following problem:
Builds an object from a conf... | Builds an object from a config dataclass. Given a config dataclass defined with @configure or autoconfig, and populated with values from CLI / yaml with parse_config, instantiate will invoke the constructor of the target and pass the arg values kept in the config. A common pattern is to instantiate a hierarchy of objec... |
23,065 | from typing import Union, Type, TYPE_CHECKING, List, Callable, Any, Optional
import dataclasses
def parse_args_tyro(config_type, yaml_arg: Optional[str]='--config'):
"""Parse args from a config dataclass.
args = parse_args_tyro(AppConfig)
Args:
config_type (type): The type for the config object.
... | This function will: 1. Parse args from the CLI and optional config yaml path. 2. Create and populate an instance of the config dataclass type. Usage example: ``` @dataclass class AppConfig: grid: autoconfig(TriplanarGrid, HashGrid) # type: Union[ConfigTriplanarGrid, ConfigHashGrid, ConfigHashGridFromGeometric, ...] ner... |
23,066 | from typing import Union, Type, TYPE_CHECKING, List, Callable, Any, Optional
import dataclasses
The provided code snippet includes necessary dependencies for implementing the `print_config` function. Write a Python function `def print_config(config, prefix="")` to solve the following problem:
Prettyprint the config da... | Prettyprint the config dataclass object. Args: config (dataclass): Dataclass config object. prefix (Optional[str]): If a base level indentation is desired, you can pass in a string. |
23,067 | from typing import Union, Type, TYPE_CHECKING, List, Callable, Any, Optional
import dataclasses
The provided code snippet includes necessary dependencies for implementing the `write_config_to_yaml` function. Write a Python function `def write_config_to_yaml(config, path)` to solve the following problem:
Write config t... | Write config to path as a yaml. write_config_to_path(config_object, "config.yaml") Args: config (dataclass): Dataclass config. path (str): Path to write the config file to. |
23,068 | from typing import Union, Type, TYPE_CHECKING, List, Callable, Any, Optional
import dataclasses
The provided code snippet includes necessary dependencies for implementing the `get_config_target` function. Write a Python function `def get_config_target(config)` to solve the following problem:
For config dataclasses gen... | For config dataclasses generated with autoconfig() or @configure (or hydra-zen in general), this function will return the target type this config constructs when calling instantiate(). If config is not a dataclass generated with autoconfig(), @configure or hydra-zen, a TypeError is raised. Args: config (dataclass): Dat... |
23,069 | import os, sys
import re
import yaml
import itertools
from typing_extensions import Annotated
from typing import List, Set, Dict, Optional
from collections import defaultdict
import dataclasses
import argparse
import tyro
from ._exceptions import handle_custom_errors, AmbiguousArgument
The provided code snippet includ... | Writes config to path in yaml format. Usage: write_config_to_path(config_object, "config.yaml") Args: config (dataclass): Dataclass config. path (str): Path to write the config file to. |
23,070 | from __future__ import annotations
import inspect
import enum
import copy
import typing
from typing import get_type_hints, Type, Callable, List, Optional, Any
from functools import lru_cache
import docstring_parser
from dataclasses import field
import hydra_zen
from hydra_zen import instantiate, builds, make_config, hy... | null |
23,071 | from __future__ import annotations
from typing import List, Tuple
import numpy as np
import torch
import kaolin.ops.spc as spc_ops
import kaolin.render.spc as spc_render
import wisp.ops.mesh as mesh_ops
import wisp.ops.spc as wisp_spc_ops
from wisp.accelstructs.base_as import BaseAS, ASQueryResults, ASRaytraceResults, ... | null |
23,072 | from __future__ import annotations
import os
from typing import Callable, Optional, Type
import collections
import inspect
import torch
from torch.utils.data._utils.collate import default_convert, default_collate_err_msg_format
from wisp.core import Rays
from wisp.datasets.base_datasets import WispDataset, MultiviewDat... | A convenience method which loads the MultiviewDataset class which best matches the files under dataset_path. The implementation relies on the `WispDataset.is_root_of_dataset()` function being implemented by WispDataset implementations. Dataset classes are allowed to specify unique terms which set them apart from other ... |
23,073 | from __future__ import annotations
import os
from typing import Callable, Optional, Type
import collections
import inspect
import torch
from torch.utils.data._utils.collate import default_convert, default_collate_err_msg_format
from wisp.core import Rays
from wisp.datasets.base_datasets import WispDataset, MultiviewDat... | r""" Function that extends torch.utils.data._utils.collate.default_collate to support custom wisp structures such as Rays and Batches. |
23,074 | from typing import Callable, Tuple, Union
from copy import deepcopy
import unittest
import random
import numpy as np
import torch
from kaolin.render.camera import Camera
from kaolin.render.camera.extrinsics import CameraExtrinsics
from torch.utils.data import Dataset
from wisp.utils import DotDict
from wisp.ops.raygen ... | generate camera pose from a spherical coordinate Args: size: batch size of generated poses. device: where to allocate the output. radius: camera radius theta_range: [min, max], should be in [0, pi] phi_range: [min, max], should be in [0, 2 * pi] Return: poses: [size, 4, 4] in OpenGL convention |
23,075 | import logging
import sys
import pprint
The provided code snippet includes necessary dependencies for implementing the `default_log_setup` function. Write a Python function `def default_log_setup(level=logging.INFO)` to solve the following problem:
Sets up default logging, always logging to stdout. :param level: loggi... | Sets up default logging, always logging to stdout. :param level: logging level, e.g. logging.INFO |
23,076 | import logging
import sys
import pprint
The provided code snippet includes necessary dependencies for implementing the `args_to_log_format` function. Write a Python function `def args_to_log_format(args_dict) -> str` to solve the following problem:
Convert args hierarchy to string representation suitable for logging (... | Convert args hierarchy to string representation suitable for logging (i.e. with Tensorboard). Args: args_dict : The parsed arguments, grouped within a dictionary. Returns: arg_str : The args encoded in a string format. |
23,077 | from pydispatch import dispatcher
The provided code snippet includes necessary dependencies for implementing the `watch` function. Write a Python function `def watch(watched_obj, field, status, handler)` to solve the following problem:
registers the handler for status updates on watched_obj.field. For example: watch(s... | registers the handler for status updates on watched_obj.field. For example: watch(scene_status, "cam_controller", "changed", app.on_camera_controller_changed) |
23,078 | from pydispatch import dispatcher
def _register_func(cls):
# __setattr__ already explicitly defined, use it as internal setter implementation
if '__setattr__' in cls.__dict__:
setter_func = cls.__dict__['__setattr__']
else: # __setattr__ not defined, use the default implementation which simply set... | Returns the class augmented with a custom __setattr__ implementation which notifies subscribers when class fields are updated. |
23,079 | from pydispatch import dispatcher
class watcheddict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__class__ = type(dict.__name__, (self.__class__, dict), {})
def __setitem__(self, item, value):
super().__setitem__(item, value)
dispatcher.send(... | null |
23,080 | import torch
import torch.nn as nn
import torch.nn.functional as F
class FullSort(nn.Module):
"""The "FullSort" activation function from https://arxiv.org/abs/1811.05381.
"""
def forward(self, x):
"""Sorts the feature dimension.
Args:
x (torch.FloatTensor): Some tensor of shape [... | Utility function to return an activation function class based on the string description. Args: activation_type (str): The name for the activation function. Returns: (Function): The activation function to be used. |
23,081 | from typing import Dict, Any
import torch
import torch.nn as nn
from wisp.core import WispModule
from scipy.stats import ortho_group
The provided code snippet includes necessary dependencies for implementing the `orthonormal` function. Write a Python function `def orthonormal(weight)` to solve the following problem:
I... | Initialize the layer as a random orthonormal matrix. Args: weight (torch.FloatTensor): Matrix of shape [M, N]. Only used for the shape. Returns: (torch.FloatTensor): Matrix of shape [M, N]. |
23,082 | from typing import Dict, Any
import torch
import torch.nn as nn
from wisp.core import WispModule
from scipy.stats import ortho_group
def svd(weight):
"""Initialize the layer with the U,V of SVD.
Args:
weight (torch.FloatTensor): Matrix of shape [M, N].
Returns:
(torch.FloatTensor): Matrix of... | Initialize the layer with spectral normalization. Args: weight (torch.FloatTensor): Matrix of shape [M, N]. Returns: (torch.FloatTensor): Matrix of shape [M, N]. |
23,083 | from typing import Dict, Any
import torch
import torch.nn as nn
from wisp.core import WispModule
from scipy.stats import ortho_group
The provided code snippet includes necessary dependencies for implementing the `identity` function. Write a Python function `def identity(weight)` to solve the following problem:
Initial... | Initialize the layer with identity matrix. Args: weight (torch.FloatTensor): Matrix of shape [M, N]. Returns: (torch.FloatTensor): Matrix of shape [M, N]. |
23,084 | from typing import Dict, Any
import torch
import torch.nn as nn
from wisp.core import WispModule
from scipy.stats import ortho_group
The provided code snippet includes necessary dependencies for implementing the `average` function. Write a Python function `def average(weight)` to solve the following problem:
Initializ... | Initialize the layer by normalizing the weights. Args: weight (torch.FloatTensor): Matrix of shape [M, N]. Returns: (torch.FloatTensor): Matrix of shape [M, N]. |
23,085 | from typing import Dict, Any
import torch
import torch.nn as nn
from wisp.core import WispModule
class PositionalEmbedder(WispModule):
"""PyTorch implementation of regular positional embedding, as used in the original NeRF and Transformer papers.
"""
def __init__(self, num_freq, max_freq_log2, log_sampling=... | Utility function to get a positional encoding embedding. Args: frequencies (int): The number of frequencies used to define the PE: [2^0, 2^1, 2^2, ... 2^(frequencies - 1)]. input_dim (int): The input coordinate dimension. include_input (bool): If true, will concatenate the input coords. Returns: (nn.Module, int): - The... |
23,086 |
The provided code snippet includes necessary dependencies for implementing the `position` function. Write a Python function `def position(position, features, layers, activation)` to solve the following problem:
Use the position as input (i.e. no conditioning) Args: position : [N, ..., d] tensor of coordinates feature... | Use the position as input (i.e. no conditioning) Args: position : [N, ..., d] tensor of coordinates features : [N, ..., f] tensor of features layers : nn.ModuleList of layers activation : activation function |
23,087 |
The provided code snippet includes necessary dependencies for implementing the `feature` function. Write a Python function `def feature(position, features, layers, activation)` to solve the following problem:
Use the features as input. Args: position : [N, ..., d] tensor of coordinates features : [N, ..., f] tensor o... | Use the features as input. Args: position : [N, ..., d] tensor of coordinates features : [N, ..., f] tensor of features layers : nn.ModuleList of layers activation : activation function |
23,088 |
The provided code snippet includes necessary dependencies for implementing the `concat` function. Write a Python function `def concat(position, features, layers, activation)` to solve the following problem:
Concatenates the input onto the features, and then feeds into the input of the neural network. Args: position :... | Concatenates the input onto the features, and then feeds into the input of the neural network. Args: position : [N, ..., d] tensor of coordinates features : [N, ..., f] tensor of features layers : nn.ModuleList of layers activation : activation function |
23,089 |
The provided code snippet includes necessary dependencies for implementing the `film_linear` function. Write a Python function `def film_linear(position, features, layers, activation)` to solve the following problem:
Applies film conditioning (multiply only) on the network. Args: position : [N, ..., d] tensor of coor... | Applies film conditioning (multiply only) on the network. Args: position : [N, ..., d] tensor of coordinates features : [N, ..., f] tensor of features layers : nn.ModuleList of layers activation : activation function |
23,090 |
The provided code snippet includes necessary dependencies for implementing the `film_translate` function. Write a Python function `def film_translate(position, features, layers, activation)` to solve the following problem:
Applies film conditioning (add only) on the network. Args: position : [N, ..., d] tensor of coo... | Applies film conditioning (add only) on the network. Args: position : [N, ..., d] tensor of coordinates features : [N, ..., f] tensor of features layers : nn.ModuleList of layers activation : activation function |
23,091 |
The provided code snippet includes necessary dependencies for implementing the `film` function. Write a Python function `def film(position, features, layers, activation)` to solve the following problem:
Applies film conditioning (add only) on the network. Args: position : [N, ..., d] tensor of coordinates features : ... | Applies film conditioning (add only) on the network. Args: position : [N, ..., d] tensor of coordinates features : [N, ..., f] tensor of features layers : nn.ModuleList of layers activation : activation function |
23,092 | import torch
import torch.nn as nn
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `normalize_frobenius` function. Write a Python function `def normalize_frobenius(x)` to solve the following problem:
Normalizes the matrix according to the Frobenius norm. A... | Normalizes the matrix according to the Frobenius norm. Args: x (torch.FloatTensor): A matrix. Returns: (torch.FloatTensor): A normalized matrix. |
23,093 | import torch
import torch.nn as nn
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `normalize_L_1` function. Write a Python function `def normalize_L_1(x)` to solve the following problem:
Normalizes the matrix according to the L1 norm. Args: x (torch.Float... | Normalizes the matrix according to the L1 norm. Args: x (torch.FloatTensor): A matrix. Returns: (torch.FloatTensor): A normalized matrix. |
23,094 | import torch
import torch.nn as nn
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `normalize_L_inf` function. Write a Python function `def normalize_L_inf(x)` to solve the following problem:
Normalizes the matrix according to the Linf norm. Args: x (torch... | Normalizes the matrix according to the Linf norm. Args: x (torch.FloatTensor): A matrix. Returns: (torch.FloatTensor): A normalized matrix. |
23,095 | import torch
import torch.nn as nn
import torch.nn.functional as F
class FrobeniusLinear(nn.Module):
"""A standard Linear layer which applies a Frobenius normalization in the forward pass.
"""
def __init__(self, *args, **kwargs):
super().__init__()
self.linear = nn.Linear(*args, **kwargs)
... | Convenience function to return the layer class name from text. Args: layer_type (str): Text name for the layer. Retunrs: (nn.Module): The layer to be used for the decoder. |
23,096 | import time
import torch
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
The provided code snippet includes necessary dependencies for implementing the `colorize_ti... | Returns colors based on the significance of the time elapsed. |
23,097 | import time
import torch
The provided code snippet includes necessary dependencies for implementing the `print_gpu_memory` function. Write a Python function `def print_gpu_memory()` to solve the following problem:
Prints GPU memory used.
Here is the function:
def print_gpu_memory():
"""Prints GPU memory used.
... | Prints GPU memory used. |
23,098 | import os
import urllib.request
import re
listpath="./model-list"
def find_Filename(keyword):
model_list=[]
for filename in os.listdir(listpath):
model_file=filename.casefold().split("_")
if keyword[0]=="all":
model_list.append(filename)
elif keyword[0]!=model_file[0]:
... | null |
23,099 | import os
import urllib.request
import re
def yaml2list(txt):
yaml_list=[]
for line in txt:
line=line[:-1]
line_list=line.split(":")
if len(line_list)>=2:
new_line_list=[]
hppts_flag=0
for x in line_list:
if hppts_flag==0:
... | null |
23,100 | import os
import urllib.request
import re
def process_bar(percent, start_str='', end_str='', total_length=0):
def download(loadLinkList):
def Schedule(a,b,c):
per=100.0*a*b/c
if per >100:
per=100
end_str = '100%'
process_bar(per/100, start_str='', end_str=end_str, total... | null |
23,101 | from nndct_shared.utils.tensor_util import DataFormatMap
from typing import List
def num_remaining_channels(num_channels, ratio, channel_divisible):
if num_channels <= channel_divisible:
return num_channels
value = int((1 - ratio) * num_channels)
return max(
channel_divisible,
int(value + channe... | null |
23,102 | from nndct_shared.utils.tensor_util import DataFormatMap
from typing import List
class DataFormatMap(object):
"""A dict mapping of framework and op type to its data format.
"""
_blob_format_map = {
FrameworkType.NNDCT: {
2: "NH",
3: "NLC",
4: "NHWC",
5: "NHWDC"
... | null |
23,103 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import copy
import json
import numpy as np
import os
from typing import List
from nndct_shared.base.key_names import FrameworkType
from nndct_shared.pruning import errors
from nndct_shared.pruning imp... | null |
23,104 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import collections
import os
import pickle
from nndct_shared.pruning import logging
from nndct_shared.pruning import pruning_lib
from nndct_shared.utils import io, logging
from typing import Mapping, ... | null |
23,105 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import collections
import os
import pickle
from nndct_shared.pruning import logging
from nndct_shared.pruning import pruning_lib
from nndct_shared.utils import io, logging
from typing import Mapping, ... | null |
23,106 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging as _logging
import os as _os
import sys as _sys
import time as _time
import traceback as _traceback
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging impor... | null |
23,107 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging as _logging
import os as _os
import sys as _sys
import time as _time
import traceback as _traceback
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging impor... | null |
23,108 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging as _logging
import os as _os
import sys as _sys
import time as _time
import traceback as _traceback
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging impor... | null |
23,109 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging as _logging
import os as _os
import sys as _sys
import time as _time
import traceback as _traceback
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging impor... | null |
23,110 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging as _logging
import os as _os
import sys as _sys
import time as _time
import traceback as _traceback
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging impor... | Return how much logging output will be produced. |
23,111 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging as _logging
import os as _os
import sys as _sys
import time as _time
import traceback as _traceback
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging impor... | Sets the threshold for what messages will be logged. |
23,112 | import collections
import json
import os
from nndct_shared.pruning.pruning_lib import PruningSpec, NodeGroup
from nndct_shared.pruning import errors
from nndct_shared.utils import io
from typing import List
import os
if not os.path.exists(BASE_DIR):
os.makedirs(BASE_DIR)
def save_searcher(searcher, filepath):
i... | null |
23,113 | import collections
import json
import os
from nndct_shared.pruning.pruning_lib import PruningSpec, NodeGroup
from nndct_shared.pruning import errors
from nndct_shared.utils import io
from typing import List
class SubnetSearcher(object):
def __init__(self, groups: List[NodeGroup]):
def set_supernet(self, score... | null |
23,114 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import List, Mapping, Any, Union, Tuple
import collections
from nndct_shared.base.key_names import NNDCT_OP as OpTypes
from nndct_shared.nndct_graph.base_node import Node
from nndct_shared.metaclass ... | null |
23,115 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import List, Mapping, Any, Union, Tuple
import collections
from nndct_shared.base.key_names import NNDCT_OP as OpTypes
from nndct_shared.nndct_graph.base_node import Node
from nndct_shared.metaclass ... | null |
23,116 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import List, Mapping, Any, Union, Tuple
import collections
from nndct_shared.base.key_names import NNDCT_OP as OpTypes
from nndct_shared.nndct_graph.base_node import Node
from nndct_shared.metaclass ... | null |
23,117 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import List, Mapping, Any, Union, Tuple
import collections
from nndct_shared.base.key_names import NNDCT_OP as OpTypes
from nndct_shared.nndct_graph.base_node import Node
from nndct_shared.metaclass ... | Divide convolution nodes into different groups. 1*1 conv only can expand or squeeze dim 3*3 conv 0 is_depthwise_conv 0 ancestor node 1 +/* node 1 not is_depthwise_conv 0 +/* node. |
23,118 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import List, Mapping, Any, Union, Tuple
import collections
from nndct_shared.base.key_names import NNDCT_OP as OpTypes
from nndct_shared.nndct_graph.base_node import Node
from nndct_shared.metaclass ... | find first and last conv layer. if second_node is depthwise_conv, add it. |
23,119 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import List, Mapping, Any, Union, Tuple
import collections
from nndct_shared.base.key_names import NNDCT_OP as OpTypes
from nndct_shared.nndct_graph.base_node import Node
from nndct_shared.metaclass ... | Looks up the node's modification function in the registry and calls it. This function takes a NndctGraph object, a NndctNode from it, and the dictionary of PruningInfo and if there's an associated modification method, calls it. If no function has been registered for the particular op type, a general fucntion will be ca... |
23,120 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import List, Mapping, Any, Union, Tuple
import collections
from nndct_shared.base.key_names import NNDCT_OP as OpTypes
from nndct_shared.nndct_graph.base_node import Node
from nndct_shared.metaclass ... | null |
23,121 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import List, Mapping, Any, Union, Tuple
import collections
from nndct_shared.base.key_names import NNDCT_OP as OpTypes
from nndct_shared.nndct_graph.base_node import Node
from nndct_shared.metaclass ... | null |
23,122 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import List, Mapping, Any, Union, Tuple
import collections
from nndct_shared.base.key_names import NNDCT_OP as OpTypes
from nndct_shared.nndct_graph.base_node import Node
from nndct_shared.metaclass ... | null |
23,123 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import List, Mapping, Any, Union, Tuple
import collections
from nndct_shared.base.key_names import NNDCT_OP as OpTypes
from nndct_shared.nndct_graph.base_node import Node
from nndct_shared.metaclass ... | null |
23,124 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import List, Mapping, Any, Union, Tuple
import collections
from nndct_shared.base.key_names import NNDCT_OP as OpTypes
from nndct_shared.nndct_graph.base_node import Node
from nndct_shared.metaclass ... | null |
23,125 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import List, Mapping, Any, Union, Tuple
import collections
from nndct_shared.base.key_names import NNDCT_OP as OpTypes
from nndct_shared.nndct_graph.base_node import Node
from nndct_shared.metaclass ... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.