repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
CIM | CIM-main/oatomobile/baselines/torch/transforms.py | # Copyright 2020 The OATomobile Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 2,479 | 32.513514 | 86 | py |
CIM | CIM-main/oatomobile/baselines/torch/dim/model.py | # Copyright 2020 The OATomobile Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 14,963 | 34.628571 | 107 | py |
CIM | CIM-main/oatomobile/baselines/torch/dim/agent.py | # Copyright 2020 The OATomobile Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 3,606 | 39.077778 | 118 | py |
CIM | CIM-main/oatomobile/baselines/torch/dim/train.py | # Copyright 2020 The OATomobile Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 12,084 | 29.987179 | 113 | py |
CIM | CIM-main/oatomobile/baselines/torch/cim/model.py | # Copyright 2020 The OATomobile Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 14,342 | 35.589286 | 111 | py |
CIM | CIM-main/oatomobile/baselines/torch/cim/agent.py | # Copyright 2020 The OATomobile Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 9,069 | 43.679803 | 138 | py |
CIM | CIM-main/oatomobile/baselines/torch/cim/train.py | # Copyright 2020 The OATomobile Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 11,930 | 30.070313 | 113 | py |
CIM | CIM-main/oatomobile/baselines/torch/cim/predictor/model.py | import torch
import torch.nn as nn
class MLP(nn.Module):
def __init__(self, lags = 3, encoder_hidden_dim = 16, fc_hidden_dim = 16, input_dim = 2):
super(MLP, self).__init__()
self.encoders = []
for i in range(input_dim):
self.encoders.append(nn.Sequential(
nn.Li... | 2,367 | 29.753247 | 93 | py |
CIM | CIM-main/oatomobile/baselines/torch/cim/predictor/train.py | # Copyright 2020 The OATomobile Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 5,195 | 30.490909 | 114 | py |
CIM | CIM-main/oatomobile/baselines/torch/cim/perception/model.py | """model.py"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torch.autograd import Variable
from oatomobile.baselines.torch.cim.perception.types_ import *
from oatomobile.baselines.torch import transforms
from oatomobile.core.typing import ShapeLike
from typing ... | 7,685 | 34.09589 | 104 | py |
CIM | CIM-main/oatomobile/baselines/torch/cim/perception/types_.py | from typing import List, Callable, Union, Any, TypeVar, Tuple
# from torch import tensor as Tensor
Tensor = TypeVar('torch.tensor') | 132 | 32.25 | 61 | py |
CIM | CIM-main/oatomobile/baselines/torch/cim/perception/train.py | # Copyright 2020 The OATomobile Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 11,669 | 31.873239 | 118 | py |
CIM | CIM-main/oatomobile/baselines/torch/cil/model.py | # Copyright 2020 The OATomobile Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 5,226 | 30.487952 | 80 | py |
CIM | CIM-main/oatomobile/baselines/torch/cil/agent.py | # Copyright 2020 The OATomobile Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 3,687 | 36.632653 | 108 | py |
CIM | CIM-main/oatomobile/baselines/torch/cil/train.py | # Copyright 2020 The OATomobile Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 9,138 | 30.622837 | 102 | py |
CIM | CIM-main/oatomobile/baselines/torch/rip/agent.py | # Copyright 2020 The OATomobile Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 5,695 | 36.473684 | 108 | py |
CIM | CIM-main/oatomobile/datasets/carla.py | # Copyright 2020 The OATomobile Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 25,367 | 31.274809 | 92 | py |
AQUAVS | AQUAVS-main/fashionmnist_AQUAVS.py | # -*- coding: utf-8 -*-
"""FashionMNIST_SVAE.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1RGZCc5UM4co2XBKW3wA-TuTo6KFIxZh_
"""
datasetName = "FashionMNIST"
import numpy as np
import tensorflow as tf
from tensorflow.keras import backend as K
... | 9,833 | 37.264591 | 145 | py |
AQUAVS | AQUAVS-main/mnist_AQUAVS.py | # -*- coding: utf-8 -*-
"""20_SVAE_MNIST_Final.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1PC_gw0ASDNk9oCwSrYm8JbJnpL7OXZf7
"""
datasetName = "MNIST"
"""<h3>Supervised VAE</h3>"""
import numpy as np
import tensorflow as tf
from tensorflow.... | 10,046 | 36.349442 | 145 | py |
AQUAVS | AQUAVS-main/mnist_fashionmnist_training.py | # -*- coding: utf-8 -*-
"""MNIST_fashionMNIST_training.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Ifw4dtUitUh87iiFkisFd0YGL-epdKDz
"""
datasetName = "MNIST"
# datasetName = "FashionMNIST"
from tensorflow.keras import layers, models
def ge... | 3,114 | 35.22093 | 121 | py |
AQUAVS | AQUAVS-main/cifar_training.py | # -*- coding: utf-8 -*-
"""CIFAR_training.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1XcUVE2Bt2CVgmD9uHwATsBJ40MC9w0PC
"""
datasetName = "CIFAR-100"
# datasetName = "CIFAR-10"
if (datasetName == "CIFAR-100"):
tc = 100
if (datasetName == ... | 9,209 | 30.326531 | 122 | py |
meta_sequential_prediction | meta_sequential_prediction-main/training_loops.py | import math
import torch
from torch import nn
import pytorch_pfn_extras as ppe
from utils.clr import simclr
from utils.misc import freq_to_wave
from tqdm import tqdm
def loop_seqmodel(manager, model, optimizer, train_loader, config, device):
while not manager.stop_trigger:
for images in train_loader:
... | 2,461 | 40.728814 | 132 | py |
meta_sequential_prediction | meta_sequential_prediction-main/run.py | import os
import argparse
import yaml
import copy
import functools
import random
import argparse
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader
import pytorch_pfn_extras as ppe
from pytorch_pfn_extras.training import extensions
from utils import yaml_utils ... | 3,593 | 31.972477 | 140 | py |
meta_sequential_prediction | meta_sequential_prediction-main/models/seqae.py | import numpy as np
import torch
import torch.nn as nn
from models import dynamics_models
import torch.nn.utils.parametrize as P
from models.dynamics_models import LinearTensorDynamicsLSTSQ, MultiLinearTensorDynamicsLSTSQ, HigherOrderLinearTensorDynamicsLSTSQ
from models.base_networks import ResNetEncoder, ResNetDecoder... | 21,519 | 33.935065 | 151 | py |
meta_sequential_prediction | meta_sequential_prediction-main/models/base_networks.py | import numpy as np
import torch
from torch import nn
from models.resblock import Block, Conv1d1x1Block
from einops.layers.torch import Rearrange
from einops import repeat
class Conv1d1x1Encoder(nn.Sequential):
def __init__(self,
dim_out=16,
dim_hidden=128,
act=nn... | 2,505 | 33.805556 | 125 | py |
meta_sequential_prediction | meta_sequential_prediction-main/models/resblock.py | import sys
import os
import math
import torch
import torch.nn as nn
from torch.nn import functional as F
from utils.weight_standarization import WeightStandarization, WeightStandarization1d
import torch.nn.utils.parametrize as P
from utils.emb2d import Emb2D
def upsample_conv(x, conv):
# Upsample -> Conv
x = ... | 4,914 | 32.209459 | 90 | py |
meta_sequential_prediction | meta_sequential_prediction-main/models/simclr_models.py | import torch
import torch.nn as nn
from models.base_networks import ResNetEncoder
from einops import rearrange
class ResNetwProjHead(nn.Module):
def __init__(self, dim_mlp=512, dim_head=128, k=1, act=nn.ReLU(), n_blocks=3):
super().__init__()
self.enc = ResNetEncoder(
dim_latent=0, k=... | 1,078 | 28.162162 | 82 | py |
meta_sequential_prediction | meta_sequential_prediction-main/models/dynamics_models.py | import numpy as np
import torch
import torch.nn as nn
from utils.laplacian import make_identity_like, tracenorm_of_normalized_laplacian, make_identity, make_diagonal
import einops
import pytorch_pfn_extras as ppe
def _rep_M(M, T):
return einops.repeat(M, "n a1 a2 -> n t a1 a2", t=T)
def _loss(A, B):
return ... | 7,338 | 33.134884 | 111 | py |
meta_sequential_prediction | meta_sequential_prediction-main/datasets/three_dim_shapes.py | import numpy as np
import torch
import torchvision
from collections import OrderedDict
import os
_FACTORS_IN_ORDER = ['floor_hue', 'wall_hue', 'object_hue', 'scale', 'shape',
'orientation']
_NUM_VALUES_PER_FACTOR = OrderedDict({'floor_hue': 10, 'wall_hue': 10, 'object_hue': 10,
... | 4,023 | 33.991304 | 153 | py |
meta_sequential_prediction | meta_sequential_prediction-main/datasets/small_norb.py | import numpy as np
import torch
import torchvision
from collections import OrderedDict
import os
import numpy as np
_FACTORS_IN_ORDER = ['category', 'instance',
'lighting', 'elevation', 'azimuth']
_ELEV_V = [30, 35, 40, 45, 50, 55, 60, 65, 70]
_AZIM_V = np.arange(0, 350, 20)
assert len(_AZIM_V) =... | 4,475 | 32.402985 | 103 | py |
meta_sequential_prediction | meta_sequential_prediction-main/datasets/seq_mnist.py | import os
import numpy as np
import cv2
import torch
import torchvision
import math
import colorsys
from skimage.transform import resize
from copy import deepcopy
from utils.misc import get_RTmat
from utils.misc import freq_to_wave
class SequentialMNIST():
# Rotate around z axis only.
default_active_actions ... | 7,439 | 42.508772 | 104 | py |
meta_sequential_prediction | meta_sequential_prediction-main/utils/misc.py | import math
import torch
from torch import nn
from einops import repeat
import numpy as np
def freq_to_wave(freq, is_radian=True):
_freq_rad = 2 * math.pi * freq if not is_radian else freq
return torch.hstack([torch.cos(_freq_rad), torch.sin(_freq_rad)])
def unsqueeze_at_the_end(x, n):
return x[(...,) +... | 1,664 | 29.272727 | 69 | py |
meta_sequential_prediction | meta_sequential_prediction-main/utils/clr.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import pytorch_pfn_extras as ppe
def simclr(zs, temperature=1.0, normalize=True, loss_type='cossim'):
if normalize:
zs = [F.normalize(z, p=2, dim=1) for z in zs]
m = len(zs)
n = zs[0].shape[0]
device = zs[0].device
mask = t... | 834 | 28.821429 | 73 | py |
meta_sequential_prediction | meta_sequential_prediction-main/utils/optimize_bd_cob.py | import torch
import torch.nn as nn
from einops import repeat
from utils.laplacian import tracenorm_of_normalized_laplacian, make_identity_like
def optimize_bd_cob(mats, batchsize=32, n_epochs=50, epochs_monitor=10):
# Optimize change of basis matrix U by minimizing block diagonalization loss
class ChangeOfBa... | 1,579 | 37.536585 | 81 | py |
meta_sequential_prediction | meta_sequential_prediction-main/utils/emb2d.py | import math
import numpy as np
import torch
import torch.nn as nn
class Emb2D(nn.modules.lazy.LazyModuleMixin, nn.Module):
def __init__(self, dim=64):
super().__init__()
self.dim = dim
self.emb = torch.nn.parameter.UninitializedParameter()
def __call__(self, x):
if torch.nn.pa... | 1,949 | 36.5 | 98 | py |
meta_sequential_prediction | meta_sequential_prediction-main/utils/laplacian.py | import torch
import numpy as np
from einops import repeat
def make_identity(N, D, device):
if N is None:
return torch.Tensor(np.array(np.eye(D))).to(device)
else:
return torch.Tensor(np.array([np.eye(D)] * N)).to(device)
def make_identity_like(A):
assert A.shape[-2] == A.shape[-1] # Ensur... | 1,012 | 28.794118 | 79 | py |
meta_sequential_prediction | meta_sequential_prediction-main/utils/weight_standarization.py | import torch.nn as nn
import torch.nn.functional as F
class WeightStandarization(nn.Module):
def forward(self, weight):
weight_mean = weight.mean(dim=1, keepdim=True).mean(dim=2,
keepdim=True).mean(dim=3, keepdim=True)
weight = weight - weight_mean
std = we... | 1,165 | 37.866667 | 81 | py |
bcts | bcts-main/main.py | import argparse
from argparse import Namespace
from datetime import datetime
import random
import torch
from tqdm import tqdm
import wandb
import sys
sys.path.append("../Rainbow/")
from bcts_agent import BCTSAgent
from env import Env
from cule_env import CuleEnv
from memory import ReplayMemory
from test import test... | 10,120 | 46.294393 | 122 | py |
bcts | bcts-main/cule_env.py | import torch
import cv2 # Note that importing cv2 before torch may cause segfaults?
from env import Env
from torchcule.atari import Env as AtariEnv
from torchcule.atari import Rom as AtariRom
class CuleEnv(Env):
def __init__(self, args, full_env_name):
super(CuleEnv, self).__init__(args)
env_nam... | 2,453 | 37.952381 | 113 | py |
bcts | bcts-main/test.py | import os
import plotly
from plotly.graph_objs import Scatter
from plotly.graph_objs.scatter import Line
import torch
from cule_env import CuleEnv
from tqdm import tqdm
import numpy as np
import time
from scipy.stats import mstats
import wandb
from copy import deepcopy
FIRE_LIST = ['Breakout', 'Beam']
# Globals
Ts,... | 5,371 | 36.566434 | 156 | py |
bcts | bcts-main/cule_bfs.py | import torch
import numpy as np
from torchcule.atari import Env as AtariEnv
from torchcule.atari import Rom as AtariRom
import time
RAND_FIRE_LIST = ['Breakout']
CROSSOVER_DICT = {'MsPacman': 1, 'Breakout': 2, 'Assault': 2, 'Krull': 2, 'Pong': 1, 'Boxing': 1, 'Asteroids': 1}
OP_FACTOR_DICT = {'Video': [1.1] * 4, 'Spac... | 17,191 | 48.260745 | 158 | py |
bcts | bcts-main/bcts_agent.py | import random
import torch
from agent import Agent
from cule_bfs import CuleBFS
import os
class BCTSAgent(Agent):
def __init__(self, args, env, full_env_name):
super(BCTSAgent, self).__init__(args, env)
self.args = args
self.full_env_name = full_env_name
if args.use_cule:
... | 1,933 | 42.954545 | 114 | py |
PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching-main/main.py | from __future__ import print_function, division
import argparse
import os
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
import torchvision.utils as vutils
import torch.nn.functional... | 13,595 | 50.5 | 150 | py |
PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching-main/models/tile_update.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .FE import BasicConv2d
from .tile_warping import TileWarping, TileWarping1
from .submodules import DispUpsampleBySlantedPlane, SlantDUpsampleBySlantedPlaneT4T4, SlantD2xUpsampleBySlantedPlaneT4T2
import pdb
from utils.write_pfm import write_pfm_ten... | 12,738 | 53.67382 | 145 | py |
PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching-main/models/FE.py | import torch.nn.functional as F
import torch
import torch.nn as nn
class feature_extraction_conv(nn.Module):
"""
UNet for HITNet
"""
def __init__(self, args):
super(feature_extraction_conv, self).__init__()
self.conv1x_0 = nn.Sequential(
BasicConv2d(3, 16, 3, 1, 1, 1),
... | 3,853 | 36.784314 | 114 | py |
PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching-main/models/HITNet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .FE import feature_extraction_conv
from .initialization import INIT
from .tile_warping import TileWarping
from .tile_update import TileUpdate, PostTileUpdate, FinalTileUpdate, PostTileUpdateNoUp
from models.submodules import DispUpsampleBySlantedPl... | 9,149 | 51.285714 | 147 | py |
PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching-main/models/initialization.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .FE import BasicConv2d
import pdb
from .submodules import BuildVolume2d
class INIT(nn.Module):
"""
Tile hypothesis initialization
input: dual feature pyramid
output: initial tile hypothesis pyramid
"""
def __init__(self, a... | 7,608 | 41.038674 | 110 | py |
PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching-main/models/submodules.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class DispUpsampleBySlantedPlane(nn.Module):
def __init__(self, upscale, ts=4):
super(DispUpsampleBySlantedPlane, self).__init__()
self.upscale = upscale
self.center = (upscale - 1) / 2
self.DUC = nn.PixelShuffle(up... | 4,805 | 38.393443 | 119 | py |
PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching-main/models/tile_warping.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import pdb
from .submodules import DispUpsampleBySlantedPlane, BuildVolume2dChaos
class TileWarping(nn.Module):
def __init__(self, args):
super(TileWarping, self).__init__()
self.disp_up = DispUpsampleBySlantedPlane(4)
self... | 3,259 | 42.466667 | 120 | py |
PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching-main/datasets/kitti_dataset.py | import os
import random
from torch.utils.data import Dataset
from PIL import Image
import numpy as np
from datasets.data_io import get_transform, read_all_lines, pfm_imread
import torchvision.transforms.functional as photometric
import pdb
class KITTIDataset(Dataset):
def __init__(self, datapath, list_filename, t... | 7,074 | 43.21875 | 119 | py |
PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching-main/datasets/data_io.py | import numpy as np
import re
import torchvision.transforms as transforms
def get_transform():
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
return transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=mean, std=std),
])
# read all lines in a file
def read_... | 1,439 | 23.40678 | 78 | py |
PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching-main/loss/total_loss.py | import torch
import torch.nn.functional as F
from loss.initialization_loss import init_loss
from loss.propagation_loss import prop_loss, slant_loss, w_loss
def global_loss(init_cv_cost_pyramid, prop_disp_pyramid, dx_pyramid, dy_pyramid, w_pyramid,
d_gt, dx_gt, dy_gt, maxdisp,
lambda_in... | 5,696 | 33.95092 | 162 | py |
PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching-main/loss/initialization_loss.py | import torch
import torch.nn.functional as F
import pdb
def init_loss(pred_init_cost: torch.Tensor, d_gt: torch.Tensor, maxdisp, beta=1):
"""
Initialization loss, HITNet paper eqt(10
:param pred_init_cost:
:param d_gt:
:param beta:
:return: init loss [B*1*H*W]
"""
cost_gt = subpix_cost... | 2,006 | 30.857143 | 148 | py |
PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching-main/loss/propagation_loss.py | import torch
import torch.nn.functional as F
import pdb
import math
def prop_loss(d_diff, A=1, alpha=1, c=0.1):
"""
Loss from HITNet eqt(12
:param d_diff: d^gt - d^
:param A: The truncation value
:param alpha: shape param
:param c > 0: scale param
:return: torch.Tensor: L^prop [B*1*H*W]
... | 2,213 | 29.328767 | 111 | py |
PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching-main/utils/visualization.py | from __future__ import print_function
import torch
import torch.nn as nn
import torch.utils.data
from torch.autograd import Variable, Function
import torch.nn.functional as F
import math
import numpy as np
def gen_error_colormap():
cols = np.array(
[[0 / 3.0, 0.1875 / 3.0, 49, 54, 149],
[0.1875 /... | 2,198 | 36.271186 | 100 | py |
PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching-main/utils/experiment.py | from __future__ import print_function, division
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
from torch.autograd import Variable
import torchvision.utils as vutils
import torch.nn.functional as F
import numpy as np
import copy
def make_iterative_func(func):
def wrapper(vars)... | 5,660 | 31.164773 | 126 | py |
PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching-main/utils/saver.py | import os
import shutil
import torch
from collections import OrderedDict
import glob
import torch.distributed as dist
import json
class Saver(object):
def __init__(self, args, use_dist=False):
self.args = args
self.use_dist = use_dist
# self.directory = os.path.join('run', args.dataset, a... | 1,309 | 37.529412 | 119 | py |
PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching-main/utils/metrics.py | import torch
import torch.nn.functional as F
from utils.experiment import make_nograd_func
from torch.autograd import Variable
from torch import Tensor
# Update D1 from >3px to >=3px & >5%
# matlab code:
# E = abs(D_gt - D_est);
# n_err = length(find(D_gt > 0 & E > tau(1) & E. / abs(D_gt) > tau(2)));
# n_total = leng... | 2,428 | 35.80303 | 95 | py |
CEAR | CEAR-main/main.py | # encoding:utf-8
import os
import nni
import math
import time
import json
import torch
import argparse
import torch.nn.functional as F
from tqdm import tqdm
from torch.utils.data import DataLoader
from torch.optim import AdamW
from transformers import BertTokenizer, BertModel
from nni.utils import merge_parameter
fro... | 19,179 | 44.129412 | 206 | py |
CEAR | CEAR-main/utils.py | import os
import copy
import torch
import random
import numpy as np
import torch.nn.functional as F
from tqdm import tqdm
from torch.utils.data import DataLoader
from sklearn.cluster import KMeans
def set_random_seed(args):
seed = args.seed
torch.manual_seed(seed)
if torch.cuda.is_available() and args.cud... | 9,913 | 35.718519 | 147 | py |
CEAR | CEAR-main/model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from utils import compute_cos_sim
from torch.nn import CrossEntropyLoss
from transformers import BertModel
class BertEncoder(nn.Module):
def __init__(self, args, tokenizer, encode_style="emarker"):
super().__init__()
self.args = a... | 4,900 | 40.533898 | 130 | py |
CEAR | CEAR-main/aca.py | # encoding:utf-8
import os
import nni
import math
import time
import json
import torch
import argparse
import torch.nn.functional as F
from tqdm import tqdm
from torch.utils.data import DataLoader
from torch.optim import AdamW
from transformers import BertTokenizer, BertModel
from nni.utils import merge_parameter
fro... | 18,878 | 43.95 | 206 | py |
conditional_kde | conditional_kde-main/docs/conf.py | #!/usr/bin/env python
#
# conditional_kde documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.... | 5,443 | 28.427027 | 81 | py |
avatarify-python | avatarify-python-master/afy/predictor_local.py | from scipy.spatial import ConvexHull
import torch
import yaml
from modules.keypoint_detector import KPDetector
from modules.generator_optim import OcclusionAwareGenerator
from sync_batchnorm import DataParallelWithCallback
import numpy as np
import face_alignment
def normalize_kp(kp_source, kp_driving, kp_driving_ini... | 5,348 | 38.622222 | 127 | py |
monodle | monodle-main/lib/helpers/decode_helper.py | import numpy as np
import torch
import torch.nn as nn
from lib.datasets.utils import class2angle
def decode_detections(dets, info, calibs, cls_mean_size, threshold):
'''
NOTE: THIS IS A NUMPY FUNCTION
input: dets, numpy array, shape in [batch x max_dets x dim]
input: img_info, dict, necessary informat... | 7,269 | 34.637255 | 117 | py |
monodle | monodle-main/lib/helpers/scheduler_helper.py | import torch.nn as nn
import torch.optim.lr_scheduler as lr_sched
import math
def build_lr_scheduler(cfg, optimizer, last_epoch):
def lr_lbmd(cur_epoch):
cur_decay = 1
for decay_step in cfg['decay_list']:
if cur_epoch >= decay_step:
cur_decay = cur_decay * cfg['decay_ra... | 3,831 | 29.903226 | 100 | py |
monodle | monodle-main/lib/helpers/trainer_helper.py | import os
import tqdm
import torch
import numpy as np
import torch.nn as nn
from lib.helpers.save_helper import get_checkpoint_state
from lib.helpers.save_helper import load_checkpoint
from lib.helpers.save_helper import save_checkpoint
from lib.losses.centernet_loss import compute_centernet3d_loss
class Trainer(ob... | 3,871 | 34.522936 | 123 | py |
monodle | monodle-main/lib/helpers/save_helper.py | import os
import torch
import torch.nn as nn
def model_state_to_cpu(model_state):
model_state_cpu = type(model_state)() # ordered dict
for key, val in model_state.items():
model_state_cpu[key] = val.cpu()
return model_state_cpu
def get_checkpoint_state(model=None, optimizer=None, epoch=None):
... | 1,501 | 33.136364 | 87 | py |
monodle | monodle-main/lib/helpers/optimizer_helper.py | import math
import torch
import torch.optim as optim
from torch.optim.optimizer import Optimizer
def build_optimizer(cfg_optimizer, model):
weights, biases = [], []
for name, param in model.named_parameters():
if 'bias' in name:
biases += [param]
else:
weights += [param]... | 5,576 | 41.9 | 116 | py |
monodle | monodle-main/lib/helpers/dataloader_helper.py | import torch
import numpy as np
from torch.utils.data import DataLoader
from lib.datasets.kitti.kitti_dataset import KITTI_Dataset
# init datasets and dataloaders
def my_worker_init_fn(worker_id):
np.random.seed(np.random.get_state()[1][0] + worker_id)
def build_dataloader(cfg, workers=4):
# perpare dataset... | 1,336 | 35.135135 | 78 | py |
monodle | monodle-main/lib/helpers/tester_helper.py | import os
import tqdm
import torch
from lib.helpers.save_helper import load_checkpoint
from lib.helpers.decode_helper import extract_dets_from_outputs
from lib.helpers.decode_helper import decode_detections
class Tester(object):
def __init__(self, cfg, model, dataloader, logger, eval=False):
self.cfg =... | 4,732 | 38.441667 | 121 | py |
monodle | monodle-main/lib/helpers/utils_helper.py | import torch
import numpy as np
import logging
import random
def create_logger(log_file, rank=0):
log_format = '%(asctime)s %(levelname)5s %(message)s'
logging.basicConfig(level=logging.INFO if rank == 0 else 'ERROR',
format=log_format,
filename=log_file)
c... | 844 | 31.5 | 69 | py |
monodle | monodle-main/lib/models/centernet3d.py | import os
import cv2
import torch
import torch.nn as nn
import numpy as np
from lib.backbones import dla
from lib.backbones.dlaup import DLAUp
from lib.backbones.hourglass import get_large_hourglass_net
from lib.backbones.hourglass import load_pretrian_model
class CenterNet3D(nn.Module):
def __init__(self, back... | 2,712 | 32.085366 | 129 | py |
monodle | monodle-main/lib/datasets/kitti/kitti_dataset.py | import os
import numpy as np
import torch.utils.data as data
from PIL import Image
from lib.datasets.utils import angle2class
from lib.datasets.utils import gaussian_radius
from lib.datasets.utils import draw_umich_gaussian
from lib.datasets.kitti.kitti_utils import get_objects_from_label
from lib.datasets.kitti.kitti... | 13,676 | 42.419048 | 136 | py |
monodle | monodle-main/lib/losses/uncertainty_loss.py | import numpy as np
import torch
def laplacian_aleatoric_uncertainty_loss(input, target, log_variance, reduction='mean'):
'''
References:
MonoPair: Monocular 3D Object Detection Using Pairwise Spatial Relationships, CVPR'20
Geometry and Uncertainty in Deep Learning for Computer Vision, Universi... | 1,082 | 35.1 | 95 | py |
monodle | monodle-main/lib/losses/dim_aware_loss.py | import torch
import torch.nn.functional as F
def dim_aware_l1_loss(input, target, dimension):
dimension = dimension.clone().detach()
loss = torch.abs(input - target)
loss /= dimension
with torch.no_grad():
compensation_weight = F.l1_loss(input, target) / loss.mean()
loss *= compensation_w... | 521 | 22.727273 | 68 | py |
monodle | monodle-main/lib/losses/focal_loss.py | import torch
import torch.nn as nn
def focal_loss(input, target, alpha=0.25, gamma=2.):
'''
Args:
input: prediction, 'batch x c x h x w'
target: ground truth, 'batch x c x h x w'
alpha: hyper param, default in 0.25
gamma: hyper param, default in 2.0
Reference: Focal Loss ... | 1,687 | 24.19403 | 86 | py |
monodle | monodle-main/lib/losses/centernet_loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from lib.helpers.decode_helper import _transpose_and_gather_feat
from lib.losses.focal_loss import focal_loss_cornernet
from lib.losses.uncertainty_loss import laplacian_aleatoric_uncertainty_loss
from lib.losses.dim_aware_loss import dim_aware_l1_loss... | 5,440 | 40.853846 | 131 | py |
monodle | monodle-main/lib/backbones/dla.py | import os
import math
import numpy as np
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
BatchNorm = nn.BatchNorm2d
def get_model_url(data='imagenet', name='dla34', hash='ba72cf86'):
return os.path.join('http://dl.yf.io/dla/models', data, '{}-{}.pth'.format(name, hash))
def conv3x... | 14,554 | 34.413625 | 91 | py |
monodle | monodle-main/lib/backbones/dlaup.py | import os, sys
import math
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(os.path.dirname(BASE_DIR))
sys.path.append(ROOT_DIR)
import numpy as np
import torch
import torch.nn as nn
class Conv2d(nn.Module):
def __init__(self, in_planes, out_planes, kernal_szie=3, stride=1, bias=... | 8,927 | 36.991489 | 104 | py |
monodle | monodle-main/lib/backbones/hourglass.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import torch
import torch.nn as nn
class convolution(nn.Module):
def __init__(self, k, inp_dim, out_dim, stride=1, with_bn=True):
super(convolution, self).__init__()
pa... | 11,068 | 31.365497 | 118 | py |
PalmTree | PalmTree-master/src/train_palmtree.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.autograd import Variable
from config import *
import numpy as np
import palmtree
from palmtree import dataset
from palmtree import trainer
import pickle as pkl
print(palmtree.__file__)
vocab_path = "cd... | 2,202 | 32.378788 | 117 | py |
PalmTree | PalmTree-master/src/palmtree/trainer/pretrain.py | import torch
import torch.nn as nn
from torch.optim import Adam, AdamW
from torch.utils.data import DataLoader
from ..model import BERTLM, BERT
from .optim_schedule import ScheduledOptim
import tqdm
class BERTTrainer:
"""
BERTTrainer make the pretrained BERT model with two LM training method.
1. Ma... | 6,299 | 39.645161 | 192 | py |
PalmTree | PalmTree-master/src/palmtree/dataset/dataset.py | from torch.utils.data import Dataset
import tqdm
import torch
import random
import pickle as pkl
class BERTDataset(Dataset):
def __init__(self, dfg_corpus_path, cfg_corpus_path, vocab, seq_len, encoding="utf-8", corpus_lines=None, on_memory=True):
self.vocab = vocab
self.seq_len = seq_len
... | 8,441 | 36.189427 | 135 | py |
PalmTree | PalmTree-master/src/palmtree/dataset/vocab.py | import pickle
import tqdm
from collections import Counter
class TorchVocab(object):
"""Defines a vocabulary object that will be used to numericalize a field.
Attributes:
freqs: A collections.Counter object holding the frequencies of tokens
in the data used to build the Vocab.
stoi:... | 6,797 | 35.352941 | 93 | py |
PalmTree | PalmTree-master/src/palmtree/model/bert.py | import torch.nn as nn
from .transformer import TransformerBlock
from .embedding import BERTEmbedding
class BERT(nn.Module):
"""
BERT model : Bidirectional Encoder Representations from Transformers.
"""
def __init__(self, vocab_size, hidden=768, n_layers=12, attn_heads=12, dropout=0.1):
"""
... | 2,088 | 29.720588 | 97 | py |
PalmTree | PalmTree-master/src/palmtree/model/transformer.py | import torch.nn as nn
from .attention import MultiHeadedAttention
from .utils import SublayerConnection, PositionwiseFeedForward
class TransformerBlock(nn.Module):
"""
Bidirectional Encoder = Transformer (self-attention)
Transformer = MultiHead_Attention + Feed_Forward with sublayer connection
"""
... | 1,276 | 38.90625 | 110 | py |
PalmTree | PalmTree-master/src/palmtree/model/language_model.py | import torch.nn as nn
import torch
from .bert import BERT
class BERTLM(nn.Module):
"""
BERT Language Model
Next Sentence Prediction Model + Masked Language Model
"""
def __init__(self, bert: BERT, vocab_size):
"""
:param bert: BERT model which should be trained
:param voc... | 1,740 | 24.602941 | 68 | py |
PalmTree | PalmTree-master/src/palmtree/model/embedding/bert.py | import torch.nn as nn
from .token import TokenEmbedding
from .position import PositionalEmbedding
from .segment import SegmentEmbedding
class BERTEmbedding(nn.Module):
"""
BERT Embedding which is consisted with under features
1. TokenEmbedding : normal embedding matrix
2. PositionalEmbedding :... | 1,261 | 37.242424 | 88 | py |
PalmTree | PalmTree-master/src/palmtree/model/embedding/position.py | import torch.nn as nn
import torch
import math
class PositionalEmbedding(nn.Module):
def __init__(self, d_model, max_len=512):
super().__init__()
# Compute the positional encodings once in log space.
pe = torch.zeros(max_len, d_model).float()
pe.require_grad = False
posi... | 710 | 26.346154 | 95 | py |
PalmTree | PalmTree-master/src/palmtree/model/embedding/segment.py | import torch.nn as nn
class SegmentEmbedding(nn.Embedding):
def __init__(self, embed_size=512):
super().__init__(3, embed_size, padding_idx=0)
| 157 | 21.571429 | 54 | py |
PalmTree | PalmTree-master/src/palmtree/model/embedding/token.py | import torch.nn as nn
class TokenEmbedding(nn.Embedding):
def __init__(self, vocab_size, embed_size=512):
super().__init__(vocab_size, embed_size, padding_idx=0)
| 176 | 24.285714 | 63 | py |
PalmTree | PalmTree-master/src/palmtree/model/attention/multi_head.py | import torch.nn as nn
from .single import Attention
class MultiHeadedAttention(nn.Module):
"""
Take in model size and number of heads.
"""
def __init__(self, h, d_model, dropout=0.1):
super().__init__()
assert d_model % h == 0
# We assume d_v always equals d_k
self.d_... | 1,268 | 32.394737 | 91 | py |
PalmTree | PalmTree-master/src/palmtree/model/attention/single.py | import torch.nn as nn
import torch.nn.functional as F
import torch
import math
class Attention(nn.Module):
"""
Compute 'Scaled Dot Product Attention
"""
def forward(self, query, key, value, mask=None, dropout=None):
scores = torch.matmul(query, key.transpose(-2, -1)) \
/ mat... | 596 | 21.961538 | 66 | py |
PalmTree | PalmTree-master/src/palmtree/model/utils/gelu.py | import torch.nn as nn
import torch
import math
class GELU(nn.Module):
"""
Paper Section 3.4, last paragraph notice that BERT used the GELU instead of RELU
"""
def forward(self, x):
return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
| 301 | 22.230769 | 100 | py |
PalmTree | PalmTree-master/src/palmtree/model/utils/feed_forward.py | import torch.nn as nn
from .gelu import GELU
class PositionwiseFeedForward(nn.Module):
"Implements FFN equation."
def __init__(self, d_model, d_ff, dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
... | 488 | 27.764706 | 67 | py |
PalmTree | PalmTree-master/src/palmtree/model/utils/sublayer.py | import torch.nn as nn
from .layer_norm import LayerNorm
class SublayerConnection(nn.Module):
"""
A residual connection followed by a layer norm.
Note for code simplicity the norm is first as opposed to last.
"""
def __init__(self, size, dropout):
super(SublayerConnection, self).__init__()... | 565 | 28.789474 | 71 | py |
PalmTree | PalmTree-master/src/palmtree/model/utils/layer_norm.py | import torch.nn as nn
import torch
class LayerNorm(nn.Module):
"Construct a layernorm module (See citation for details)."
def __init__(self, features, eps=1e-6):
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(features))
self.b_2 = nn.Parameter(torch.zeros(feature... | 519 | 27.888889 | 66 | py |
PalmTree | PalmTree-master/src/extrinsic_evaluation/gemini/data_loader.py | """"
Here we implement a class for loading data.
"""
import torch
from torch.autograd import Variable
from vocab import *
from config import *
import numpy as np
import random
import re
np.random.seed(0)
class DataLoader:
EOS = 0 # to mean end of sentence
UNK = 1 # to mean unknown token
maxlen = MAXL... | 3,295 | 30.390476 | 113 | py |
PalmTree | PalmTree-master/src/extrinsic_evaluation/gemini/eval_utils.py | from model import UniSkip, Encoder
from data_loader import DataLoader
from vocab import load_dictionary
from config import *
from torch import nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch
import re
import numpy as np
import pickle
class UsableTransformer:
# @profile
def... | 1,852 | 28.412698 | 63 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.