id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
20,291 | import numpy as np
import torch
def img2mse(x, y, mask):
if mask is None:
return torch.mean((x - y) ** 2)
else:
return torch.sum((x - y) ** 2 * mask) / mask.sum() | null |
20,292 | import numpy as np
import torch
def mse2psnr(x):
return -10.0 * torch.log(x) / np.log(10) | null |
20,293 | import numpy as np
import torch
def cast_rays(t_vals, origins, directions, radii, ray_shape):
t0 = t_vals[..., :-1]
t1 = t_vals[..., 1:]
if ray_shape == "cone":
gaussian_fn = conical_frustum_to_gaussian
elif ray_shape == "cylinder":
gaussian_fn = cylinder_to_gaussian
else:
as... | null |
20,294 | import numpy as np
import torch
def sorted_piecewise_constant_pdf(
bins, weights, num_samples, randomized, float_min_eps=2**-32
):
def cast_rays(t_vals, origins, directions, radii, ray_shape):
def resample_along_rays(
rays_o,
rays_d,
radii,
t_vals,
weights,
randomized,
ray_shape,
st... | null |
20,295 | import numpy as np
import torch
def expected_sin(x, x_var):
def integrated_pos_enc(samples, min_deg, max_deg):
x, x_cov_diag = samples
scales = torch.tensor([2**i for i in range(min_deg, max_deg)]).type_as(x)
shape = list(x.shape[:-1]) + [-1]
y = torch.reshape(x[..., None, :] * scales[:, None], shape)
... | null |
20,296 | import numpy as np
import torch
def volumetric_rendering(rgb, density, t_vals, dirs, white_bkgd):
t_mids = 0.5 * (t_vals[..., :-1] + t_vals[..., 1:])
t_dists = t_vals[..., 1:] - t_vals[..., :-1]
delta = t_dists * torch.norm(dirs[..., None, :], dim=-1)
# Note that we're quietly turning density from [...... | null |
20,297 | import numpy as np
import torch
def pos_enc(x, min_deg, max_deg, append_identity):
scales = torch.tensor([2**i for i in range(min_deg, max_deg)]).type_as(x)
xb = torch.reshape((x[..., None, :] * scales[:, None]), list(x.shape[:-1]) + [-1])
four_feat = torch.sin(torch.cat([xb, xb + 0.5 * np.pi], dim=-1))
... | null |
20,298 | import itertools
import functorch
import numpy as np
import torch
import torch.nn.functional as F
def img2mse(x, y):
return torch.mean((x - y) ** 2) | null |
20,299 | import itertools
import functorch
import numpy as np
import torch
import torch.nn.functional as F
def mse2psnr(x):
return -10.0 * torch.log(x) / np.log(10) | null |
20,300 | import itertools
import functorch
import numpy as np
import torch
import torch.nn.functional as F
def contract(mean, cov, is_train=True):
bsz, num_samples, dim = mean.shape
def _contract(x):
x_mag_sq = torch.sum(x**2, dim=-1, keepdim=True).clip(min=1e-32)
z = torch.where(
x_mag_sq... | null |
20,301 | import itertools
import functorch
import numpy as np
import torch
import torch.nn.functional as F
def lift_and_diagonalize(means, covs, basis):
fn_mean = means @ basis
fn_cov_diag = torch.sum(basis[None, None, ...] * (covs @ basis), dim=-2)
return fn_mean, fn_cov_diag | null |
20,302 | import itertools
import functorch
import numpy as np
import torch
import torch.nn.functional as F
def expected_sin(mean, var):
def integrated_pos_enc(mean, var, min_deg, max_deg):
scales = 2 ** torch.arange(min_deg, max_deg).type_as(mean)
shape = list(mean.shape[:-1]) + [
-1,
]
scaled_mean = to... | null |
20,303 | import itertools
import functorch
import numpy as np
import torch
import torch.nn.functional as F
def pos_enc(x, min_deg, max_deg, append_identity):
scales = 2 ** torch.arange(min_deg, max_deg).type_as(x)
xb = torch.reshape((x[..., None, :] * scales[:, None]), x.shape[:-1] + (-1,))
four_feat = torch.sin(to... | null |
20,304 | import itertools
import functorch
import numpy as np
import torch
import torch.nn.functional as F
eps = 1.1920929e-07
def inner_outer(t0, t1, y1):
cy1 = torch.cat([torch.zeros_like(y1[..., :1]), torch.cumsum(y1, dim=-1)], dim=-1)
idx_lo, idx_hi = searchsorted(t1, t0)
cy1_lo = torch.take_along_dim(cy1, idx_l... | null |
20,305 | import itertools
import functorch
import numpy as np
import torch
import torch.nn.functional as F
def lossfun_distortion(t, w):
ut = (t[..., 1:] + t[..., :-1]) / 2
dut = torch.abs(ut[..., :, None] - ut[..., None, :])
loss_inter = torch.sum(w * torch.sum(w[..., None, :] * dut, dim=-1), dim=-1)
loss_int... | null |
20,306 | import itertools
import functorch
import numpy as np
import torch
import torch.nn.functional as F
def construct_ray_warps(t_near, t_far):
s_near, s_far = 1 / t_near, 1 / t_far
t_to_s = lambda t: (1 / t - s_near) / (s_far - s_near)
s_to_t = lambda s: 1 / (s * s_far + (1 - s) * s_near)
return t_to_s, s_t... | null |
20,307 | import itertools
import functorch
import numpy as np
import torch
import torch.nn.functional as F
eps = 1.1920929e-07
def max_dilate(t, w, dilation, domain):
t0 = t[..., :-1] - dilation
t1 = t[..., 1:] + dilation
t_dilate = torch.sort(torch.cat([t, t0, t1], dim=-1), dim=-1).values
t_dilate = torch.clip(... | null |
20,308 | import itertools
import functorch
import numpy as np
import torch
import torch.nn.functional as F
def compute_alpha_weights(density, tdist, dirs, opaque_background=False):
t_delta = tdist[..., 1:] - tdist[..., :-1]
delta = t_delta * torch.norm(dirs[..., None, :], dim=-1)
density_delta = density * delta
... | null |
20,309 | import itertools
import functorch
import numpy as np
import torch
import torch.nn.functional as F
def volumetric_rendering(
rgbs, weights, tdist, bg_rgbs, t_far, compute_extras, extras=None
):
rendering = {}
acc = weights.sum(dim=-1)
bg_w = torch.clip(1 - acc[..., None], min=0) # The weight of the ba... | null |
20,310 | import itertools
import functorch
import numpy as np
import torch
import torch.nn.functional as F
def conical_frustum_to_gaussian(d, t0, t1, radius, diag):
mu = (t0 + t1) / 2
hw = (t1 - t0) / 2
t_mean = mu + (2 * mu * hw**2) / (3 * mu**2 + hw**2).clip(min=eps)
denom = (3 * mu**2 + hw**2).clip(min=eps)
... | null |
20,311 | import itertools
import functorch
import numpy as np
import torch
import torch.nn.functional as F
def sample(
randomized,
t,
w_logits,
num_samples,
single_jitter=False,
deterministic_center=False,
):
if not randomized:
if deterministic_center:
pad = 1 / (2 * num_samples)
... | null |
20,312 | import itertools
import functorch
import numpy as np
import torch
import torch.nn.functional as F
def compute_sq_dist(mat0, mat1=None):
"""Compute the squared Euclidean distance between all pairs of columns."""
if mat1 is None:
mat1 = mat0
# Use the fact that ||x - y||^2 == ||x||^2 + ||y||^2 - 2 x^T... | Generates a 3D basis by tesselating a geometric polyhedron. Args: base_shape: string, the name of the starting polyhedron, must be either 'icosahedron' or 'octahedron'. angular_tesselation: int, the number of times to tesselate the polyhedron, must be >= 1 (a value of 1 is a no-op to the polyhedron). remove_symmetries:... |
20,313 | import numpy as np
import torch
import torch.nn.functional as F
def img2mse(x, y):
return torch.mean((x - y) ** 2) | null |
20,314 | import numpy as np
import torch
import torch.nn.functional as F
def mse2psnr(x):
return -10.0 * torch.log(x) / np.log(10) | null |
20,315 | import numpy as np
import torch
import torch.nn.functional as F
def cast_rays(t_vals, origins, directions):
return origins[..., None, :] + t_vals[..., None] * directions[..., None, :]
def depth2pts_outside(rays_o, rays_d, depth):
"""Compute the points along the ray that are outside of the unit sphere.
Args:... | null |
20,316 | import numpy as np
import torch
import torch.nn.functional as F
def pos_enc(x, min_deg, max_deg):
scales = torch.tensor([2**i for i in range(min_deg, max_deg)]).type_as(x)
xb = torch.reshape((x[..., None, :] * scales[:, None]), list(x.shape[:-1]) + [-1])
four_feat = torch.sin(torch.cat([xb, xb + 0.5 * np.p... | null |
20,317 | import numpy as np
import torch
import torch.nn.functional as F
def volumetric_rendering(rgb, density, t_vals, dirs, white_bkgd, in_sphere, t_far=None):
eps = 1e-10
if in_sphere:
dists = t_vals[..., 1:] - t_vals[..., :-1]
dists = torch.cat([dists, t_far - t_vals[..., -1:]], dim=-1)
di... | null |
20,318 | import numpy as np
import torch
import torch.nn.functional as F
def cast_rays(t_vals, origins, directions):
return origins[..., None, :] + t_vals[..., None] * directions[..., None, :]
def sorted_piecewise_constant_pdf(
bins, weights, num_samples, randomized, float_min_eps=2**-32
):
eps = 1e-5
weight_sum... | null |
20,319 | import numpy as np
import torch
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `intersect_sphere` function. Write a Python function `def intersect_sphere(rays_o, rays_d)` to solve the following problem:
Compute the depth of the intersection point between ... | Compute the depth of the intersection point between this ray and unit sphere. Args: rays_o: [num_rays, 3]. Ray origins. rays_d: [num_rays, 3]. Ray directions. Returns: depth: [num_rays, 1]. Depth of the intersection point. |
20,320 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
def img2mse(x, y):
return torch.mean((x - y) ** 2) | null |
20,321 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
def mse2psnr(x):
return -10.0 * torch.log(x) / np.log(10) | null |
20,322 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
def inthroot(x: int, n: int):
if x <= 0:
return None
lo, hi = 1, x
while lo <= hi:
mi = lo + (hi - lo) // 2
p = mi**n
if p == x:
retu... | null |
20,323 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
def _unexpand_bits(v):
v &= 0x49249249
v = (v | (v >> 2)) & 0xC30C30C3
v = (v | (v >> 4)) & 0xF00F00F
v = (v | (v >> 8)) & 0xFF0000FF
v = (v | (v >> 16)) & 0x0000FFFF
... | null |
20,324 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
def is_pow2(x: int):
return x > 0 and (x & (x - 1)) == 0
def morton_code_3(x, y, z):
xx = _expand_bits(x)
yy = _expand_bits(y)
zz = _expand_bits(z)
return (xx << 2) + (yy... | null |
20,325 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
SH_C0 = 0.28209479177387814
SH_C1 = 0.4886025119029199
SH_C2 = [
1.0925484305920792,
-1.0925484305920792,
0.31539156525252005,
-1.0925484305920792,
0.5462742152960396,
]
... | Evaluate spherical harmonics bases at unit directions, without taking linear combination. At each point, the final result may the be obtained through simple multiplication. :param basis_dim: int SH basis dim. Currently, 1-25 square numbers supported :param dirs: torch.Tensor (..., 3) unit directions :return: torch.Tens... |
20,326 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
class CubemapCoord:
ax: torch.Tensor
ori: torch.Tensor
u: torch.Tensor
v: torch.Tensor
def query_in(self, cubemap: torch.Tensor):
face = self.ax * 2 + self.ori
... | Convert a direction on a sphere (not necessarily normalized) :param xyz: direction (not necessarily normalized) :param face_reso: int, resolution of cubemap face :param eac: bool, if true (default) then uses equi-angular cubemaps (EAC) instead of standard cubemap; see https://blog.google/products/google-ar-vr/bringing-... |
20,327 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
class CubemapCoord:
ax: torch.Tensor
ori: torch.Tensor
u: torch.Tensor
v: torch.Tensor
def query_in(self, cubemap: torch.Tensor):
face = self.ax * 2 + self.ori
... | Compute the points on the cubemap for bilinear slinear_simple interpolates per-face, while linear also interpolates across edges (this is the only one supported in CUDAarest, linear_simple, linear; linear_simple interpolates per-face, while linear also interpolates across edges (this is the only one supported in CUDA) ... |
20,328 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
class CubemapBilerpQuery:
i00: CubemapCoord
i01: CubemapCoord
i10: CubemapCoord
i11: CubemapCoord
du: torch.Tensor
dv: torch.Tensor
The provided code snippet include... | Perform bilinear sampling on a cubemap given a query from cubemap_build_query :param cubemap: torch.Tensor float (6, face_reso, face_reso, C) or (B, 6, face_reso, face_reso, C) :param idx4: CubemapBilerpQuery from cubemap_build_query where each tensor has batch size B :return: (B, C) |
20,329 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
def memlog(device="cuda"):
# Memory debugging
print(torch.cuda.memory_summary(device))
import gc
for obj in gc.get_objects():
try:
if torch.is_tensor(ob... | null |
20,330 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `spher2cart` function. Write a Python function `def spher2cart(theta: torch.Tensor, phi: torch.Tensor)` to sol... | Convert spherical coordinates into Cartesian coordinates on unit sphere. |
20,331 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `eval_sg_at_dirs` function. Write a Python function `def eval_sg_at_dirs(sg_lambda: torch.Tensor, sg_mu: torch... | Evaluate spherical Gaussian functions at unit directions using learnable SG basis, without taking linear combination Works with torch. ... Can be 0 or more batch dimensions. N is the number of SG basis we use. :math:`Output = \sigma_{i}{exp ^ {\lambda_i * (\dot(\mu_i, \dirs) - 1)}` :param sg_lambda: The sharpness of th... |
20,332 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
def init_weights(m):
if type(m) == nn.Linear:
nn.init.xavier_uniform_(m.weight)
m.bias.data.fill_(0.0) | null |
20,333 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `cross_broadcast` function. Write a Python function `def cross_broadcast(x: torch.Tensor, y: torch.Tensor)` to... | Cross broadcasting for 2 tensors :param x: torch.Tensor :param y: torch.Tensor, should have the same ndim as x :return: tuple of cross-broadcasted tensors x, y. Any dimension where the size of x or y is 1 is expanded to the maximum size in that dimension among the 2. Formally, say the shape of x is (a1, ... an) and of ... |
20,334 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
def net_to_dict(out_dict: dict, prefix: str, model: nn.Module):
for child in model.named_children():
layer_name = child[0]
layer_params = {}
for param in child[1... | null |
20,335 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
def net_from_dict(in_dict, prefix: str, model: nn.Module):
for child in model.named_children():
layer_name = child[0]
layer_params = {}
for param in child[1].nam... | null |
20,336 | import math
from dataclasses import dataclass
from functools import partial
import numpy as np
import torch
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `xyz2equirect` function. Write a Python function `def xyz2equirect(bearings, reso)` to solve the following pro... | Convert ray direction vectors into equirectangular pixel coordinates. Inverse of equirect2xyz. Taken from Vickie Ye |
20,337 |
def _get_c_extension():
from warnings import warn
try:
import lib.plenoxel as _C
if not hasattr(_C, "sample_grid"):
_C = None
except:
_C = None
return _C | null |
20,340 | import numpy as np
import torch
import torch.nn.functional as F
def cast_rays(t_vals, origins, directions):
return origins[..., None, :] + t_vals[..., None] * directions[..., None, :]
def sample_along_rays(
rays_o,
rays_d,
num_samples,
near,
far,
randomized,
lindisp,
):
bsz = rays_o... | null |
20,342 | import numpy as np
import torch
import torch.nn.functional as F
def volumetric_rendering(rgb, density, t_vals, dirs, white_bkgd):
eps = 1e-10
dists = torch.cat(
[
t_vals[..., 1:] - t_vals[..., :-1],
torch.ones(t_vals[..., :1].shape, device=t_vals.device) * 1e10,
],
... | null |
20,343 | import numpy as np
import torch
import torch.nn.functional as F
def cast_rays(t_vals, origins, directions):
def sorted_piecewise_constant_pdf(
bins, weights, num_samples, randomized, float_min_eps=2**-32
):
def sample_pdf(bins, weights, origins, directions, t_vals, num_samples, randomized):
t_samples = sorted... | null |
20,344 | import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `reflect` function. Write a Python function `def reflect(viewdirs, normals)` to solve the following problem:
Reflect view directions about normals. The reflection of a vector v about a unit vector n is a vect... | Reflect view directions about normals. The reflection of a vector v about a unit vector n is a vector u such that dot(v, n) = dot(u, n), and dot(u, u) = dot(v, v). The solution to these two equations is u = 2 dot(n, v) n - v. Args: viewdirs: [..., 3] array of view directions. normals: [..., 3] array of normal direction... |
20,345 | import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `l2_normalize` function. Write a Python function `def l2_normalize(x, eps=torch.finfo(torch.float32).eps)` to solve the following problem:
Normalize x to unit length along last axis.
Here is the function:
d... | Normalize x to unit length along last axis. |
20,346 | import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `compute_weighted_mae` function. Write a Python function `def compute_weighted_mae(weights, normals, normals_gt)` to solve the following problem:
Compute weighted mean angular error, assuming normals are unit... | Compute weighted mean angular error, assuming normals are unit length. |
20,347 | import numpy as np
import torch
def generate_ide_fn(deg_view):
"""Generate integrated directional encoding (IDE) function.
This function returns a function that computes the integrated directional
encoding from Equations 6-8 of arxiv.org/abs/2112.03907.
Args:
deg_view: number of spherical harmon... | Generate directional encoding (DE) function. Args: deg_view: number of spherical harmonics degrees to use. Returns: A function for evaluating directional encoding. |
20,348 | import itertools
import numpy as np
import torch
def img2mse(x, y):
return torch.mean((x - y) ** 2) | null |
20,349 | import itertools
import numpy as np
import torch
def mse2psnr(x):
return -10.0 * torch.log(x) / np.log(10) | null |
20,350 | import itertools
import numpy as np
import torch
def linear_to_srgb(linear, eps=1e-10):
eps = torch.finfo(torch.float32).eps
srgb0 = 323 / 25 * linear
srgb1 = (
211 * torch.fmax(torch.full_like(linear, eps), linear) ** (5 / 12) - 11
) / 200
return torch.where(linear <= 0.0031308, srgb0, srg... | null |
20,351 | import itertools
import numpy as np
import torch
def cast_rays(t_vals, origins, directions, radii, ray_shape):
def sample_along_rays(
rays_o,
rays_d,
radii,
num_samples,
near,
far,
randomized,
lindisp,
ray_shape,
):
bsz = rays_o.shape[0]
t_vals = torch.linspace(0.0, 1.0, num... | null |
20,352 | import itertools
import numpy as np
import torch
def sorted_piecewise_constant_pdf(
bins, weights, num_samples, randomized, float_min_eps=2**-32
):
eps = 1e-5
weight_sum = weights.sum(dim=-1, keepdims=True)
padding = torch.fmax(torch.zeros_like(weight_sum), eps - weight_sum)
weights += padding / wei... | null |
20,353 | import itertools
import numpy as np
import torch
def expected_sin(x, x_var):
def integrated_pos_enc(means, covs, min_deg, max_deg):
scales = torch.tensor([2**i for i in range(min_deg, max_deg)]).type_as(means)
shape = list(means.shape[:-1]) + [-1]
scaled_means = torch.reshape(means[..., None, :] * scales[:... | null |
20,354 | import itertools
import numpy as np
import torch
def volumetric_rendering(rgb, density, t_vals, dirs, white_bkgd):
t_mids = 0.5 * (t_vals[..., :-1] + t_vals[..., 1:])
t_dists = t_vals[..., 1:] - t_vals[..., :-1]
delta = t_dists * torch.norm(dirs[..., None, :], dim=-1)
# Note that we're quietly turning ... | null |
20,355 | import itertools
import numpy as np
import torch
def pos_enc(x, min_deg, max_deg, append_identity):
scales = torch.tensor([2**i for i in range(min_deg, max_deg)]).type_as(x)
xb = torch.reshape((x[..., None, :] * scales[:, None]), list(x.shape[:-1]) + [-1])
four_feat = torch.sin(torch.cat([xb, xb + 0.5 * np... | null |
20,356 | import itertools
import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `lift_and_diagonalize` function. Write a Python function `def lift_and_diagonalize(samples, basis)` to solve the following problem:
Project `mean` and `cov` onto basis and diagonalize the pro... | Project `mean` and `cov` onto basis and diagonalize the projected cov. |
20,357 | import itertools
import numpy as np
import torch
def compute_sq_dist(mat0, mat1=None):
"""Compute the squared Euclidean distance between all pairs of columns."""
if mat1 is None:
mat1 = mat0
# Use the fact that ||x - y||^2 == ||x||^2 + ||y||^2 - 2 x^T y.
sq_norm0 = np.sum(mat0**2, 0)
sq_norm... | Generates a 3D basis by tesselating a geometric polyhedron. Args: base_shape: string, the name of the starting polyhedron, must be either 'icosahedron' or 'octahedron'. angular_tesselation: int, the number of times to tesselate the polyhedron, must be >= 1 (a value of 1 is a no-op to the polyhedron). remove_symmetries:... |
20,358 | import argparse
import logging
import os
import shutil
from typing import *
import gin
import torch
from pytorch_lightning import Trainer
from pytorch_lightning import loggers as pl_loggers
from pytorch_lightning import seed_everything
from pytorch_lightning.callbacks import (
LearningRateMonitor,
ModelCheckpoi... | null |
20,359 | import argparse
import logging
import os
import shutil
from typing import *
import gin
import torch
from pytorch_lightning import Trainer
from pytorch_lightning import loggers as pl_loggers
from pytorch_lightning import seed_everything
from pytorch_lightning.callbacks import (
LearningRateMonitor,
ModelCheckpoi... | null |
20,360 | import os
import imageio
import numpy as np
from PIL import Image
def to8b(x):
def norm8b(x):
x = (x - x.min()) / (x.max() - x.min())
return to8b(x) | null |
20,361 | import os
import imageio
import numpy as np
from PIL import Image
def to8b(x):
def store_image(dirpath, rgbs):
for (i, rgb) in enumerate(rgbs):
imgname = f"image{str(i).zfill(3)}.png"
rgbimg = Image.fromarray(to8b(rgb.detach().cpu().numpy()))
imgpath = os.path.join(dirpath, imgname)
... | null |
20,362 | import os
import imageio
import numpy as np
from PIL import Image
def to8b(x):
return (255 * np.clip(x, 0, 1)).astype(np.uint8)
def store_video(dirpath, rgbs, depths):
rgbimgs = [to8b(rgb.cpu().detach().numpy()) for rgb in rgbs]
video_dir = os.path.join(dirpath, "videos")
os.makedirs(video_dir, exist_o... | null |
20,363 | import os
import torch
import warnings
import numpy as np
import random
from time import sleep
from random import randint
import src.utils.logging as logging
from src.configs.config import get_cfg
from src.data import loader as data_loader
from src.engine.evaluator import Evaluator
from src.engine.trainer import Traine... | null |
20,364 | import os
import warnings
from time import sleep
from random import randint
from src.configs.config import get_cfg
from src.utils.file_io import PathManager
from train import train as train_main
from launch import default_argument_parser
def setup(args, lr, wd, check_runtime=True):
"""
Create configs and perfor... | null |
20,365 | import os
import warnings
from time import sleep
from random import randint
from src.configs.config import get_cfg
from src.utils.file_io import PathManager
from train import train as train_main
from launch import default_argument_parser
def setup(args, lr, wd, check_runtime=True):
"""
Create configs and perfor... | null |
20,366 | import os
import warnings
from time import sleep
from random import randint
from src.configs.config import get_cfg
from src.utils.file_io import PathManager
from train import train as train_main
from launch import default_argument_parser
def setup(args, lr, wd, check_runtime=True):
"""
Create configs and perfor... | null |
20,367 | import os
import warnings
from time import sleep
from random import randint
from src.configs.config import get_cfg
from src.utils.file_io import PathManager
from train import train as train_main
from launch import default_argument_parser
def setup(args, lr, wd, check_runtime=True):
"""
Create configs and perfor... | null |
20,368 | import os
import warnings
from time import sleep
from random import randint
from src.configs.config import get_cfg
from src.utils.file_io import PathManager
from train import train as train_main
from launch import default_argument_parser
def setup(args, lr, wd, check_runtime=True):
"""
Create configs and perfor... | null |
20,369 | import os
import warnings
from time import sleep
from random import randint
from src.configs.config import get_cfg
from src.utils.file_io import PathManager
from train import train as train_main
from launch import default_argument_parser
def setup(args, lr, wd, check_runtime=True):
def prompt_main(args):
lr_range ... | null |
20,370 | import os
import warnings
from time import sleep
from random import randint
from src.configs.config import get_cfg
from src.utils.file_io import PathManager
from train import train as train_main
from launch import default_argument_parser
def setup(args, lr, wd, check_runtime=True):
"""
Create configs and perfor... | null |
20,371 | import torchvision as tv
def get_transforms(split, size):
normalize = tv.transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
)
if size == 448:
resize_dim = 512
crop_dim = 448
elif size == 224:
resize_dim = 256
crop_dim = 224
elif size ... | null |
20,372 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
from . import base as base
from .registry import Registry
def _count_preprocess_fn(x):
return {"image": x["image"],
... | null |
20,373 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
from . import base as base
from .registry import Registry
def _count_cylinders_preprocess_fn(x):
# Class distribution:
... | null |
20,374 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
from . import base as base
from .registry import Registry
def _closest_object_preprocess_fn(x):
dist = tf.reduce_min(x["... | null |
20,375 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
from . import base as base
from .registry import Registry
The provided code snippet includes necessary dependencies for im... | Count all objects. |
20,376 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
from . import base as base
from .registry import Registry
The provided code snippet includes necessary dependencies for im... | Counting vehicles. |
20,377 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
from . import base as base
from .registry import Registry
The provided code snippet includes necessary dependencies for im... | Count objects on the left hand side of the camera. |
20,378 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
from . import base as base
from .registry import Registry
The provided code snippet includes necessary dependencies for im... | Counts objects far from the camera. |
20,379 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
from . import base as base
from .registry import Registry
The provided code snippet includes necessary dependencies for im... | Counts objects close to the camera. |
20,380 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
from . import base as base
from .registry import Registry
The provided code snippet includes necessary dependencies for im... | Predict the distance to the closest object. |
20,381 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
from . import base as base
from .registry import Registry
The provided code snippet includes necessary dependencies for im... | Predict the distance to the closest vehicle. |
20,382 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
from . import base as base
from .registry import Registry
The provided code snippet includes necessary dependencies for im... | Predict the absolute x position of the closest object. |
20,383 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ast
import functools
The provided code snippet includes necessary dependencies for implementing the `partialclass` function. Write a Python function `def partialclass(cls, *base_args, **base_kwargs)` to ... | Builds a subclass with partial application of the given args and keywords. Equivalent to functools.partial performance, base_args are preprended to the positional arguments given during object initialization and base_kwargs are updated with the kwargs given later. Args: cls: The base class. *base_args: Positional argum... |
20,384 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ast
import functools
The provided code snippet includes necessary dependencies for implementing the `parse_name` function. Write a Python function `def parse_name(string_to_parse)` to solve the following... | Parses input to the registry's lookup function. Args: string_to_parse: can be either an arbitrary name or function call (optionally with positional and keyword arguments). e.g. "multiclass", "resnet50_v2(filters_factor=8)". Returns: A tuple of input name and a dctinary with arguments. Examples: "multiclass" -> ("multic... |
20,385 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import six
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
The provided code snippet includes necessary dependencies for implementing the `make_get_tensors_fn` function. Write a ... | Create a function that outputs a collection of tensors from the dataset. |
20,386 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import six
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
The provided code snippet includes necessary dependencies for implementing the `make_get_and_cast_tensors_fn` function.... | Create a function that gets and casts a set of tensors from the dataset. Optionally, you can also rename the tensors. Examples: # This simply gets "image" and "label" tensors without any casting. # Note that this is equivalent to make_get_tensors_fn(["image", "label"]). make_get_and_cast_tensors_fn({ "image": None, "la... |
20,387 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import six
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
The provided code snippet includes necessary dependencies for implementing the `compose_preprocess_fn` function. Write ... | Compose two or more preprocessing functions. Args: *functions: Sequence of preprocess functions to compose. Returns: The composed function. |
20,388 | import functools
import tensorflow.compat.v1 as tf
import torch
import torch.utils.data
import numpy as np
from collections import Counter
from torch import Tensor
from ..vtab_datasets import base
from ..vtab_datasets import caltech
from ..vtab_datasets import cifar
from ..vtab_datasets import clevr
from ..vtab_dataset... | Builds a tf data instance, then transform to a list of tensors and labels |
20,389 | import functools
import tensorflow.compat.v1 as tf
import torch
import torch.utils.data
import numpy as np
from collections import Counter
from torch import Tensor
from ..vtab_datasets import base
from ..vtab_datasets import caltech
from ..vtab_datasets import cifar
from ..vtab_datasets import clevr
from ..vtab_dataset... | null |
20,390 | import math
import torch.optim as optim
from fvcore.common.config import CfgNode
from torch.optim.lr_scheduler import LambdaLR
class WarmupCosineSchedule(LambdaLR):
""" Linear warmup and then cosine decay.
Linearly increases learning rate from 0 to 1 over `warmup_steps`.
Decreases learning rate from... | null |
20,391 | import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional
from ..utils import logging
LOSS = {
"softmax": SoftmaxLoss,
}
def build_loss(cfg):
loss_name = cfg.SOLVER.LOSS
assert loss_name in LOSS, \
f'loss name {loss_name} is not supported'
loss_fn = LOSS[los... | null |
20,392 | import math
import torch
from fvcore.common.config import CfgNode
from torch.optim import Optimizer
import torch.optim as optim
from typing import Any, Callable, Iterable, List, Tuple, Optional
from ..utils import logging
logger = logging.get_logger("visual_prompt")
class AdamW(Optimizer):
""" Implements Adam algor... | null |
20,393 | import ml_collections
The provided code snippet includes necessary dependencies for implementing the `get_testing` function. Write a Python function `def get_testing()` to solve the following problem:
Returns a minimal configuration for testing.
Here is the function:
def get_testing():
"""Returns a minimal confi... | Returns a minimal configuration for testing. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.