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 |
|---|---|---|---|---|---|---|
crpn | crpn-master/lib/rpn/proposal_target_layer.py | # --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick and Sean Bell
# --------------------------------------------------------
import caffe
import numpy as np
import numpy.random as n... | 7,625 | 37.321608 | 98 | py |
crpn | crpn-master/lib/rpn/labelmap_layer.py | # --------------------------------------------------------
# CRPN
# Written by Linjie Deng
# --------------------------------------------------------
import caffe
import numpy as np
import numpy.random as npr
from fast_rcnn.config import cfg
DEBUG = False
class LabelMapLayer(caffe.Layer):
def setup(self, botto... | 6,016 | 39.38255 | 87 | py |
crpn | crpn-master/lib/transform/torch_image_transform_layer.py | # --------------------------------------------------------
# Fast/er R-CNN
# Licensed under The MIT License [see LICENSE for details]
# --------------------------------------------------------
""" Transform images for compatibility with models trained with
https://github.com/facebook/fb.resnet.torch.
Usage in model p... | 2,000 | 29.784615 | 72 | py |
AdaptSky | AdaptSky-main/Sub-6.py | import gym
import math
import random
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import math
from collections import namedtuple
from itertools import count
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision.transforms as T
import cv... | 23,348 | 29.402344 | 178 | py |
AdaptSky | AdaptSky-main/AdaptSky [Commented Version] .py | #Import used libraries
%matplotlib inline
import math
import random
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import math
from collections import namedtuple
from itertools import count
from PIL import Image
import cv2
import time
from ipywidgets.widgets.interaction import show_inline_matplo... | 36,953 | 32.965074 | 203 | py |
greedy | greedy-master/docs/conf.py | # -*- coding: utf-8 -*-
#
# greedy documentation build configuration file, created by
# sphinx-quickstart on Tue Apr 2 14:36:59 2019.
#
# 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.
#
# Al... | 5,243 | 29.312139 | 79 | py |
CADP | CADP-main/CADP-PG/onpolicy/config.py | import argparse
def get_config():
"""
The configuration parser for common hyperparameters of all environment.
Please reach each `scripts/train/<env>_runner.py` file to find private hyperparameters
only used in <env>.
Prepare parameters:
--algorithm_name <algorithm_name>
speci... | 16,591 | 55.435374 | 261 | py |
CADP | CADP-main/CADP-PG/onpolicy/envs/env_wrappers.py | """
Modified from OpenAI Baselines code to work with multi-agent envs
"""
import numpy as np
import torch
from multiprocessing import Process, Pipe
from abc import ABC, abstractmethod
from onpolicy.utils.util import tile_images
class CloudpickleWrapper(object):
"""
Uses cloudpickle to serialize contents (other... | 28,209 | 33.277035 | 118 | py |
CADP | CADP-main/CADP-PG/onpolicy/algorithms/r_mappo/r_mappo.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from onpolicy.utils.util import get_gard_norm, huber_loss, mse_loss
from onpolicy.utils.valuenorm import ValueNorm
from onpolicy.algorithms.utils.util import check
class R_MAPPO():
"""
Trainer class for MAPPO to update polici... | 11,116 | 44.938017 | 147 | py |
CADP | CADP-main/CADP-PG/onpolicy/algorithms/r_mappo/algorithm/r_actor_critic.py | import torch
import torch.nn as nn
from onpolicy.algorithms.utils.util import init, check
from onpolicy.algorithms.utils.cnn import CNNBase
from onpolicy.algorithms.utils.mlp import MLPBase
from onpolicy.algorithms.utils.rnn import RNNLayer
from onpolicy.algorithms.utils.act import ACTLayer
from onpolicy.algorithms.uti... | 8,201 | 48.409639 | 121 | py |
CADP | CADP-main/CADP-PG/onpolicy/algorithms/r_mappo/algorithm/r_actor_critic_cadp.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from onpolicy.algorithms.utils.util import init, check
from onpolicy.algorithms.utils.cnn import CNNBase
from onpolicy.algorithms.utils.mlp import MLPBase
from onpolicy.algorithms.utils.rnn import RNNLayer
from onpolicy.algorithms.utils.act import ACTLa... | 11,332 | 45.069106 | 121 | py |
CADP | CADP-main/CADP-PG/onpolicy/algorithms/r_mappo/algorithm/rMAPPOPolicy.py | import torch
from onpolicy.algorithms.r_mappo.algorithm.r_actor_critic import R_Actor, R_Critic
from onpolicy.algorithms.r_mappo.algorithm.r_actor_critic_cadp import R_Actor as R_Actor_CADP
from onpolicy.algorithms.r_mappo.algorithm.r_actor_critic_cadp import R_Critic as R_Critic_CADP
from onpolicy.utils.util import up... | 7,896 | 56.224638 | 120 | py |
CADP | CADP-main/CADP-PG/onpolicy/algorithms/utils/distributions.py | import torch
import torch.nn as nn
from .util import init
"""
Modify standard PyTorch distributions so they to make compatible with this codebase.
"""
#
# Standardize distribution interfaces
#
# Categorical
class FixedCategorical(torch.distributions.Categorical):
def sample(self):
return super().sample(... | 3,475 | 28.210084 | 86 | py |
CADP | CADP-main/CADP-PG/onpolicy/algorithms/utils/cnn.py | import torch.nn as nn
from .util import init
"""CNN Modules and utils."""
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size(0), -1)
class CNNLayer(nn.Module):
def __init__(self, obs_shape, hidden_size, use_orthogonal, use_ReLU, kernel_size=3, stride=1):
super(CNNLayer, sel... | 1,852 | 30.40678 | 124 | py |
CADP | CADP-main/CADP-PG/onpolicy/algorithms/utils/mlp.py | import torch.nn as nn
from .util import init, get_clones
"""MLP modules."""
class MLPLayer(nn.Module):
def __init__(self, input_dim, hidden_size, layer_N, use_orthogonal, use_ReLU):
super(MLPLayer, self).__init__()
self._layer_N = layer_N
active_func = [nn.Tanh(), nn.ReLU()][use_ReLU]
... | 1,892 | 32.803571 | 93 | py |
CADP | CADP-main/CADP-PG/onpolicy/algorithms/utils/popart.py | import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class PopArt(torch.nn.Module):
def __init__(self, input_shape, output_shape, norm_axes=1, beta=0.99999, epsilon=1e-5, device=torch.device("cpu")):
super(PopArt, self).__init__()
self.bet... | 3,944 | 38.848485 | 119 | py |
CADP | CADP-main/CADP-PG/onpolicy/algorithms/utils/util.py | import copy
import numpy as np
import torch
import torch.nn as nn
def init(module, weight_init, bias_init, gain=1):
weight_init(module.weight.data, gain=gain)
bias_init(module.bias.data)
return module
def get_clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
def chec... | 425 | 22.666667 | 76 | py |
CADP | CADP-main/CADP-PG/onpolicy/algorithms/utils/act.py | from .distributions import Bernoulli, Categorical, DiagGaussian
import torch
import torch.nn as nn
class ACTLayer(nn.Module):
"""
MLP Module to compute actions.
:param action_space: (gym.Space) action space.
:param inputs_dim: (int) dimension of network input.
:param use_orthogonal: (bool) whether ... | 7,872 | 47.300613 | 121 | py |
CADP | CADP-main/CADP-PG/onpolicy/algorithms/utils/rnn.py | import torch
import torch.nn as nn
"""RNN modules."""
class RNNLayer(nn.Module):
def __init__(self, inputs_dim, outputs_dim, recurrent_N, use_orthogonal):
super(RNNLayer, self).__init__()
self._recurrent_N = recurrent_N
self._use_orthogonal = use_orthogonal
self.rnn = nn.GRU(inpu... | 2,849 | 34.185185 | 116 | py |
CADP | CADP-main/CADP-PG/onpolicy/scripts/train/train_smac.py | #!/usr/bin/env python
import sys
import os
sys.path.append("../")
import wandb
import socket
import setproctitle
import numpy as np
from pathlib import Path
import torch
from onpolicy.config import get_config
from onpolicy.envs.starcraft2.StarCraft2_Env import StarCraft2Env
from onpolicy.envs.starcraft2.smac_maps impor... | 6,859 | 35.296296 | 132 | py |
CADP | CADP-main/CADP-PG/onpolicy/runner/shared/smac_runner.py | import time
import wandb
import numpy as np
from functools import reduce
import torch
from onpolicy.runner.shared.base_runner import Runner
def _t2n(x):
return x.detach().cpu().numpy()
class SMACRunner(Runner):
"""Runner class to perform training, evaluation. and data collection for SMAC. See parent class for... | 11,392 | 48.320346 | 167 | py |
CADP | CADP-main/CADP-PG/onpolicy/runner/shared/base_runner.py | import wandb
import os
import numpy as np
import torch
from tensorboardX import SummaryWriter
from onpolicy.utils.shared_buffer import SharedReplayBuffer
def _t2n(x):
"""Convert torch tensor to a numpy array."""
return x.detach().cpu().numpy()
class Runner(object):
"""
Base class for training recurren... | 8,591 | 42.836735 | 132 | py |
CADP | CADP-main/CADP-PG/onpolicy/runner/separated/base_runner.py |
import time
import wandb
import os
import numpy as np
from itertools import chain
import torch
from tensorboardX import SummaryWriter
from onpolicy.utils.separated_buffer import SeparatedReplayBuffer
from onpolicy.utils.util import update_linear_schedule
def _t2n(x):
return x.detach().cpu().numpy()
class Ru... | 7,371 | 42.364706 | 150 | py |
CADP | CADP-main/CADP-PG/onpolicy/utils/valuenorm.py |
import numpy as np
import torch
import torch.nn as nn
class ValueNorm(nn.Module):
""" Normalize a vector of observations - across the first norm_axes dimensions"""
def __init__(self, input_shape, norm_axes=1, beta=0.99999, per_element_update=False, epsilon=1e-5):
super(ValueNorm, self).__init__()
... | 3,132 | 38.658228 | 105 | py |
CADP | CADP-main/CADP-PG/onpolicy/utils/shared_buffer.py | import torch
import numpy as np
from onpolicy.utils.util import get_shape_from_obs_space, get_shape_from_act_space
def _flatten(T, N, x):
return x.reshape(T * N, *x.shape[2:])
def _cast(x):
return x.transpose(1, 2, 0, 3).reshape(-1, *x.shape[3:])
class SharedReplayBuffer(object):
"""
Buffer to sto... | 27,173 | 53.89697 | 120 | py |
CADP | CADP-main/CADP-PG/onpolicy/utils/util.py | import numpy as np
import math
import torch
def get_params_size(params_list):
# params_size = sum([np.prod(list(p.size())) for p in params_list]) * 4 / 1024
# return "{:.0f}KB".format(params_size)
params_size = sum([np.prod(list(p.size())) for p in params_list]) / 1000
return "{:.0f}K".format(params_s... | 2,520 | 30.5125 | 82 | py |
CADP | CADP-main/CADP-PG/onpolicy/utils/separated_buffer.py | import torch
import numpy as np
from collections import defaultdict
from onpolicy.utils.util import check, get_shape_from_obs_space, get_shape_from_act_space
def _flatten(T, N, x):
return x.reshape(T * N, *x.shape[2:])
def _cast(x):
return x.transpose(1,0,2).reshape(-1, *x.shape[2:])
class SeparatedReplayBu... | 21,466 | 53.484772 | 231 | py |
CADP | CADP-main/CADP-VD/src/main.py | import numpy as np
import os
import collections
from os.path import dirname, abspath
from copy import deepcopy
from sacred import Experiment, SETTINGS
from sacred.observers import FileStorageObserver
from sacred.utils import apply_backspaces_and_linefeeds
import sys
import torch as th
from utils.logging import get_logg... | 3,050 | 29.51 | 121 | py |
CADP | CADP-main/CADP-VD/src/run.py | import datetime
import os
import pprint
import time
import threading
import torch as th
from types import SimpleNamespace as SN
from utils.logging import Logger
from utils.timehelper import time_left, time_str
from os.path import dirname, abspath
from learners import REGISTRY as le_REGISTRY
from runners import REGISTR... | 8,281 | 33.65272 | 116 | py |
CADP | CADP-main/CADP-VD/src/modules/mixers/qmix.py | import torch as th
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class QMixer(nn.Module):
def __init__(self, args):
super(QMixer, self).__init__()
self.args = args
self.n_agents = args.n_agents
self.state_dim = int(np.prod(args.state_shape))
sel... | 2,505 | 40.081967 | 101 | py |
CADP | CADP-main/CADP-VD/src/modules/mixers/vdn.py | import torch as th
import torch.nn as nn
class VDNMixer(nn.Module):
def __init__(self):
super(VDNMixer, self).__init__()
def forward(self, agent_qs, batch):
return th.sum(agent_qs, dim=2, keepdim=True) | 228 | 21.9 | 52 | py |
CADP | CADP-main/CADP-VD/src/modules/mixers/qplex.py | import torch as th
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class DMAQ_QattenMixer(nn.Module):
def __init__(self, args):
super(DMAQ_QattenMixer, self).__init__()
self.args = args
self.n_agents = args.n_agents
self.n_actions = args.n_actions
... | 12,201 | 48.601626 | 121 | py |
CADP | CADP-main/CADP-VD/src/modules/agents/rnn_agent.py | import torch.nn as nn
import torch.nn.functional as F
class RNNAgent(nn.Module):
def __init__(self, input_shape, args):
super(RNNAgent, self).__init__()
self.args = args
self.fc1 = nn.Linear(input_shape, args.rnn_hidden_dim)
self.rnn = nn.GRUCell(args.rnn_hidden_dim, args.rnn_hidd... | 770 | 31.125 | 71 | py |
CADP | CADP-main/CADP-VD/src/modules/agents/atten_rnn_agent.py | import torch.nn as nn
import torch.nn.functional as F
import torch as th
import numpy as np
import torch.nn.init as init
from modules.layers.self_atten import SelfAttention
class ATTRNNAgent(nn.Module):
def __init__(self, input_shape, args):
super(ATTRNNAgent, self).__init__()
self.args = args
... | 2,252 | 37.844828 | 98 | py |
CADP | CADP-main/CADP-VD/src/modules/layers/self_atten.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class SelfAttention(nn.Module):
def __init__(self, input_size, heads, embed_size):
super().__init__()
self.input_size = input_size
self.heads = heads
self.emb_size = embed_size
self.tokeys = nn.Linear(self.i... | 1,762 | 36.510638 | 93 | py |
CADP | CADP-main/CADP-VD/src/envs/gfootball/gfootball.py | import numpy as np
import gfootball.env as football_env
from gfootball.env import observation_preprocessing
from ..multiagentenv import MultiAgentEnv
import gym
import torch as th
import logging.config
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': True,
})
class GoogleFootballEnv(Multi... | 12,325 | 38.633441 | 136 | py |
CADP | CADP-main/CADP-VD/src/components/episode_buffer.py | import torch as th
import numpy as np
from types import SimpleNamespace as SN
class EpisodeBatch:
def __init__(self,
scheme,
groups,
batch_size,
max_seq_length,
data=None,
preprocess=None,
device... | 10,894 | 42.75502 | 134 | py |
CADP | CADP-main/CADP-VD/src/components/action_selectors.py | import torch as th
from torch.distributions import Categorical
from .epsilon_schedules import DecayThenFlatSchedule
REGISTRY = {}
class MultinomialActionSelector():
def __init__(self, args):
self.args = args
self.schedule = DecayThenFlatSchedule(args.epsilon_start, args.epsilon_finish, args.eps... | 2,225 | 32.727273 | 112 | py |
CADP | CADP-main/CADP-VD/src/components/transforms.py | import torch as th
class Transform:
def transform(self, tensor):
raise NotImplementedError
def infer_output_info(self, vshape_in, dtype_in):
raise NotImplementedError
class OneHot(Transform):
def __init__(self, out_dim):
self.out_dim = out_dim
def transform(self, tensor):
... | 568 | 24.863636 | 71 | py |
CADP | CADP-main/CADP-VD/src/runners/parallel_runner.py | from envs import REGISTRY as env_REGISTRY
from functools import partial
from components.episode_buffer import EpisodeBatch
from multiprocessing import Pipe, Process
import numpy as np
import torch as th
# Based (very) heavily on SubprocVecEnv from OpenAI Baselines
# https://github.com/openai/baselines/blob/master/bas... | 10,322 | 37.518657 | 133 | py |
CADP | CADP-main/CADP-VD/src/controllers/basic_controller.py | from modules.agents import REGISTRY as agent_REGISTRY
from components.action_selectors import REGISTRY as action_REGISTRY
import torch as th
# This multi-agent controller shares parameters between agents
class BasicMAC:
def __init__(self, scheme, groups, args):
self.n_agents = args.n_agents
self.a... | 4,411 | 42.254902 | 125 | py |
CADP | CADP-main/CADP-VD/src/controllers/n_controller.py | from modules.agents import REGISTRY as agent_REGISTRY
from components.action_selectors import REGISTRY as action_REGISTRY
from .basic_controller import BasicMAC
import torch as th
import numpy as np
# This multi-agent controller shares parameters between agents
class NMAC(BasicMAC):
def __init__(self, scheme, grou... | 1,211 | 43.888889 | 117 | py |
CADP | CADP-main/CADP-VD/src/utils/th_utils.py | import torch
import numpy as np
from torch import nn
def get_params_size(params_list):
params_size = sum([np.prod(list(p.size())) for p in params_list]) * 4 / 1024
return "{:.0f}KB".format(params_size)
def clip_by_tensor(t, t_min, t_max):
"""
clip_by_tensor
:param t: tensor
:param t_min: min
... | 1,031 | 24.8 | 82 | py |
CADP | CADP-main/CADP-VD/src/utils/rl_utils.py | import torch as th
def build_td_lambda_targets(rewards, terminated, mask, target_qs, n_agents, gamma, td_lambda):
# Assumes <target_qs > in B*T*A and <reward >, <terminated >, <mask > in (at least) B*T-1*1
# Initialise last lambda -return for not terminated episodes
ret = target_qs.new_zeros(*targe... | 774 | 47.4375 | 110 | py |
CADP | CADP-main/CADP-VD/src/learners/q_learner_teacher.py | import copy
from components.episode_buffer import EpisodeBatch
from modules.mixers.vdn import VDNMixer
from modules.mixers.qmix import QMixer
import torch as th
from torch.optim import RMSprop, Adam
import numpy as np
import torch.nn.functional as F
class QLearner:
def __init__(self, mac, scheme, logger, args):
... | 6,785 | 41.679245 | 132 | py |
CADP | CADP-main/CADP-VD/src/learners/qplex_learner_teacher.py | import copy
from components.episode_buffer import EpisodeBatch
from modules.mixers.qplex import DMAQ_QattenMixer
import torch as th
import numpy as np
from torch.optim import RMSprop, Adam
from utils.th_utils import get_params_size
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
def entropy(x... | 19,168 | 48.5323 | 140 | py |
CADP | CADP-main/CADP-VD/src/learners/q_learner.py | import copy
from components.episode_buffer import EpisodeBatch
from modules.mixers.vdn import VDNMixer
from modules.mixers.qmix import QMixer
import torch as th
from torch.optim import RMSprop
class QLearner:
def __init__(self, mac, scheme, logger, args):
self.args = args
self.mac = mac
se... | 5,998 | 40.659722 | 132 | py |
lbox-open | lbox-open-main/lbox_open/pipeline/lbox_open_pipeline.py | # LBox Open
# Copyright (c) 2022-present LBox Co. Ltd.
# CC BY-NC 4.0
from pathlib import Path
import pytorch_lightning as pl
import torch
from lbox_open import openprompt_wrapper
from lbox_open.data_module.data_precedent import PrecedentDataModule
from lbox_open.model.generative_baseline_model import GenerativePars... | 5,491 | 28.212766 | 93 | py |
lbox-open | lbox-open-main/lbox_open/openprompt_wrapper/pipeline_base.py | # Wonseok add PromptForGenerationCustom by copying and tweak OpenPrompt-v1.0.0 PromptForGeneration class.
# We modify two things: (1) L343--L345 for the compatibility with transformesr 4.19.4, and
# (2) recover "confidences" which was available in the initial version of OpenPrompt
from copy i... | 22,706 | 44.143141 | 228 | py |
lbox-open | lbox-open-main/lbox_open/utils/general_utils.py | # LBox Open
# Copyright (c) 2022-present LBox Co. Ltd.
# CC BY-NC 4.0
import json
import os
import pickle
import subprocess
import time
from pathlib import Path
from tqdm import tqdm
def stop_flag(idx, toy_size):
# idx + 1 = length
data_size = idx + 1
if toy_size is not None:
if toy_size <= data... | 2,569 | 20.239669 | 75 | py |
lbox-open | lbox-open-main/lbox_open/model/model_optimizer.py | # LBox Open
# Copyright (c) 2022-present LBox Co. Ltd.
# CC BY-NC 4.0
import torch
import transformers
map_optimizers_name_to_type = {
"sgd": torch.optim.SGD,
"adam": torch.optim.Adam,
"adamw": torch.optim.AdamW,
}
def get_optimizer(mparam, tparam, model):
# todo: plm training part
_lr_type, lr_... | 3,533 | 28.949153 | 87 | py |
lbox-open | lbox-open-main/lbox_open/model/generative_baseline_model.py | # LBox Open
# Copyright (c) 2022-present LBox Co. Ltd.
# CC BY-NC 4.0
import os
from collections import defaultdict
from itertools import zip_longest
from pathlib import Path
from pprint import pprint
import datasets
import pytorch_lightning as pl
import torch
from openprompt.utils.metrics import generation_metric
f... | 13,092 | 35.985876 | 99 | py |
lbox-open | lbox-open-main/lbox_open/data_module/data_precedent.py | # LBox Open
# Copyright (c) 2022-present LBox Co. Ltd.
# CC BY-NC 4.0
import datasets
import pytorch_lightning as pl
from openprompt import PromptDataLoader
from pytorch_lightning.trainer.supporters import CombinedLoader
from lbox_open import openprompt_wrapper
from lbox_open.template import prompt_generation_utils
... | 8,799 | 35.514523 | 83 | py |
x-transformers | x-transformers-main/setup.py | from setuptools import setup, find_packages
setup(
name = 'x-transformers',
packages = find_packages(exclude=['examples']),
version = '1.16.21',
license='MIT',
description = 'X-Transformers - Pytorch',
author = 'Phil Wang',
author_email = 'lucidrains@gmail.com',
url = 'https://github.com/lucidrains/x-t... | 803 | 25.8 | 65 | py |
x-transformers | x-transformers-main/examples/enwik8_simple/train_nar.py | from x_transformers import (
TransformerWrapper,
Encoder,
NonAutoregressiveWrapper
)
import random
import tqdm
import gzip
import numpy as np
import torch
import torch.optim as optim
from torch.nn import functional as F
from torch.utils.data import DataLoader, Dataset
# constants
NUM_BATCHES = int(1e8)
B... | 2,980 | 24.478632 | 112 | py |
x-transformers | x-transformers-main/examples/enwik8_simple/train.py | from x_transformers import TransformerWrapper, Decoder
from x_transformers.autoregressive_wrapper import AutoregressiveWrapper
import random
import tqdm
import gzip
import numpy as np
import torch
import torch.optim as optim
from torch.nn import functional as F
from torch.utils.data import DataLoader, Dataset
# const... | 2,942 | 26.504673 | 91 | py |
x-transformers | x-transformers-main/examples/toy_tasks/enc_dec_copy.py | import tqdm
import torch
import torch.optim as optim
from x_transformers import XTransformer
# constants
NUM_BATCHES = int(1e5)
BATCH_SIZE = 32
LEARNING_RATE = 3e-4
GENERATE_EVERY = 100
NUM_TOKENS = 16 + 2
ENC_SEQ_LEN = 32
DEC_SEQ_LEN = 64 + 1
# helpers
def cycle():
while True:
prefix = torch.ones((BAT... | 1,739 | 23.166667 | 83 | py |
x-transformers | x-transformers-main/x_transformers/x_transformers.py | import math
from random import random
import torch
from torch import nn, einsum, Tensor
import torch.nn.functional as F
from functools import partial, wraps
from inspect import isfunction
from collections import namedtuple
from dataclasses import dataclass
from typing import List
from einops import rearrange, repeat... | 54,584 | 33.635152 | 290 | py |
x-transformers | x-transformers-main/x_transformers/attend.py | from functools import partial
import torch
from torch import nn, einsum, Tensor
import torch.nn.functional as F
from collections import namedtuple
from functools import wraps
from packaging import version
from dataclasses import dataclass
from einops import rearrange
# constants
EfficientAttentionConfig = namedtup... | 11,319 | 30.887324 | 163 | py |
x-transformers | x-transformers-main/x_transformers/nonautoregressive_wrapper.py | import math
from random import random
from contextlib import nullcontext
from collections import namedtuple
import torch
import torch.nn.functional as F
from torch import nn
from einops import rearrange, repeat, pack, unpack
from x_transformers.x_transformers import TransformerWrapper
from typing import Optional
# ... | 10,414 | 29.453216 | 130 | py |
x-transformers | x-transformers-main/x_transformers/autoregressive_wrapper.py | from math import ceil
import torch
from torch import nn
import torch.nn.functional as F
from einops import rearrange, pack, unpack
def exists(val):
return val is not None
def eval_decorator(fn):
def inner(self, *args, **kwargs):
was_training = self.training
self.eval()
out = fn(self, ... | 4,446 | 28.646667 | 151 | py |
x-transformers | x-transformers-main/x_transformers/xl_autoregressive_wrapper.py | from math import ceil
import torch
from torch import nn
import torch.nn.functional as F
from einops import rearrange, pack, unpack
from x_transformers.autoregressive_wrapper import top_p, top_k, eval_decorator
# helper functions
def exists(val):
return val is not None
def divisible_by(numer, denom):
return... | 3,988 | 25.071895 | 89 | py |
x-transformers | x-transformers-main/x_transformers/continuous_autoregressive_wrapper.py | import torch
from torch import nn
import torch.nn.functional as F
def exists(val):
return val is not None
class ContinuousAutoregressiveWrapper(nn.Module):
def __init__(self, net, ignore_index = -100, pad_value = 0):
super().__init__()
self.net = net
self.max_seq_len = net.max_seq_len
... | 1,575 | 25.711864 | 103 | py |
x-transformers | x-transformers-main/x_transformers/__init__.py | import torch
from packaging import version
if version.parse(torch.__version__) >= version.parse('2.0.0'):
from einops._torch_specific import allow_ops_in_compiled_graph
allow_ops_in_compiled_graph()
from x_transformers.x_transformers import XTransformer, Encoder, Decoder, CrossAttender, Attention, Transformer... | 701 | 49.142857 | 170 | py |
PastNet | PastNet-main/utils.py | import os
import logging
import torch
import random
import numpy as np
import torch.backends.cudnn as cudnn
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
cudnn.deterministic = True
def print_log(message):
print(message)
logging.info(message)
def output_nam... | 574 | 20.296296 | 52 | py |
PastNet | PastNet-main/exp_vq.py | import os
import os.path as osp
import json
import torch
import pickle
import logging
import numpy as np
from models.PastNet_Model import PastNetModel
from tqdm import tqdm
from API import *
from utils import *
def relative_l1_error(true_values, predicted_values):
error = torch.abs(true_values - predicted_values)... | 12,654 | 44.685921 | 170 | py |
PastNet | PastNet-main/modules/DiscreteSTModel_modules.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class VectorQuantizer(nn.Module):
def __init__(self, num_embeddings, embedding_dim, commitment_cost):
super(VectorQuantizer, self).__init__()
self._embedding_dim = embedding_dim # D
self._num_embeddings = num_embeddings ... | 9,313 | 40.212389 | 106 | py |
PastNet | PastNet-main/modules/Fourier_modules.py | from functools import partial
from collections import OrderedDict
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
from torch.utils.checkpoint import checkpoint_sequential
from params import get_fourcastnet_args
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.fft
import ... | 6,604 | 36.95977 | 121 | py |
PastNet | PastNet-main/modules/DiscreteSTModel_modules_BN.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class VectorQuantizer(nn.Module):
def __init__(self, num_embeddings, embedding_dim, commitment_cost):
super(VectorQuantizer, self).__init__()
self._embedding_dim = embedding_dim # D
self._num_embeddings = num_embeddings ... | 6,713 | 41.764331 | 106 | py |
PastNet | PastNet-main/modules/DiscreteSTModel_modules_GN.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class VectorQuantizer(nn.Module):
def __init__(self, num_embeddings, embedding_dim, commitment_cost):
super(VectorQuantizer, self).__init__()
self._embedding_dim = embedding_dim # D
self._num_embeddings = num_embeddings ... | 6,722 | 41.283019 | 106 | py |
PastNet | PastNet-main/modules/STConvEncoderDecoder_modules.py | from torch import nn
class BasicConv2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding, transpose=False, act_norm=False):
super(BasicConv2d, self).__init__()
self.act_norm=act_norm
if not transpose:
self.conv = nn.Conv2d(in_channels, out_c... | 2,469 | 36.424242 | 153 | py |
PastNet | PastNet-main/API/recorder.py | import numpy as np
import torch
class Recorder:
def __init__(self, verbose=False, delta=0):
self.verbose = verbose
self.best_score = None
self.val_loss_min = np.Inf
self.delta = delta
def __call__(self, val_loss, model, path):
score = -val_loss
if self.best_scor... | 861 | 34.916667 | 111 | py |
PastNet | PastNet-main/API/dataloader_taxibj.py | import torch
import numpy as np
from torch.utils.data import Dataset
class TrafficDataset(Dataset):
def __init__(self, X, Y):
super(TrafficDataset, self).__init__()
self.X = (X + 1) / 2
self.Y = (Y + 1) / 2
self.mean = 0
self.std = 1
def __len__(self):
return s... | 1,231 | 32.297297 | 115 | py |
PastNet | PastNet-main/API/dataloader_caltech0.py |
import os
import cv2
import numpy as np
import torch
from torch.utils.data import Dataset
split_string = "\xFF\xD8\xFF\xE0\x00\x10\x4A\x46\x49\x46"
def read_seq(path):
f = open(path, 'rb+')
string = f.read().decode('latin-1')
str_list = string.split(split_string)
print(len(str_list))
f.close()
... | 4,898 | 35.288889 | 127 | py |
PastNet | PastNet-main/API/dataloader_sevir.py | import torch.nn as nn
import numpy as np
import random
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import torch
class VilDataset(Dataset):
def __init__(self, train=True, root='./data', transform=None):
... | 2,836 | 33.597561 | 110 | py |
PastNet | PastNet-main/API/dataloader_caltech.py |
import os
import cv2
import numpy as np
import torch
import bisect
from torch.utils.data import Dataset
split_string = "\xFF\xD8\xFF\xE0\x00\x10\x4A\x46\x49\x46"
def read_seq(path):
f = open(path, 'rb+')
string = f.read().decode('latin-1')
str_list = string.split(split_string)
# print(len(str_list))
... | 5,495 | 34.921569 | 152 | py |
PastNet | PastNet-main/API/dataloader_moving_mnist.py | import os
import gzip
import random
import numpy as np
import torch
import torch.utils.data as data
def load_mnist(root):
# Load MNIST dataset for generating training data.
path = os.path.join(root, 'moving_mnist/train-images-idx3-ubyte.gz')
with gzip.open(path, 'rb') as f:
mnist = np.frombuffer(f... | 5,613 | 33.441718 | 101 | py |
PastNet | PastNet-main/API/dataloader_moving_mnist_v2.py | import numpy as np
import torch
import torch.utils.data as data
class MovingMnistSequence(data.Dataset):
def __init__(self, train=True, shuffle=True, root='./data', transform=None):
super().__init__()
if train:
npz = 'mnist_train.npz'
self.data = np.load(f'{root}/{npz}')['i... | 1,873 | 36.48 | 101 | py |
PastNet | PastNet-main/models/PastNet_Model.py | import torch
from utils import *
import logging
from torch import nn
from modules.DiscreteSTModel_modules import *
from modules.Fourier_modules import *
def stride_generator(N, reverse=False):
strides = [1, 2]*10
if reverse:
return list(reversed(strides[:N]))
else:
return strides[:N]
cl... | 12,255 | 34.627907 | 123 | py |
PastNet | PastNet-main/models/Fourier.py | from modules.Fourier_modules import *
class FPG(nn.Module):
def __init__(self,
img_size=224,
patch_size=16,
in_channels=20,
out_channels=20,
input_frames=20,
embed_dim=768,
depth=12,
... | 4,028 | 33.144068 | 123 | py |
maxent_base | maxent_base-master/cart_entropy_policy.py | import numpy as np
import time
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical
from torch.distributions import Normal
import gym
from gym import wrappers
import utils
# Get the initial zero-state for the env.
def... | 8,320 | 32.019841 | 101 | py |
maxent_base | maxent_base-master/collect_baseline.py | # Collect entropy-based reward policies.
# Changed from using all-1 reward to init to one-hot at: 2018_11_30-10-00
# python collect_baseline.py --env="MountainCarContinuous-v0" --T=200 --train_steps=400 --episodes=300 --epochs=50 --exp_name=test
# USES LOCAL FORK OF GYM
import sys
import os
home_dir = os.getenv('HOM... | 10,116 | 33.294915 | 130 | py |
maxent_base | maxent_base-master/curiosity.py | # experimenting with curiosity exploration method.
# Code derived from: https://github.com/pytorch/examples/blob/master/reinforcement_learning/reinforce.py
# example command setting args in utils.py
# python curiosity.py --models_dir=models-MountainCarContinuous-v0/models_2018_11_28-17-45/ --env="MountainCarContinuou... | 2,947 | 29.081633 | 125 | py |
AgML | AgML-main/scripts/convert_lightning_pytorch_ckpt.py | # Copyright 2021 UC Davis Plant AI and Biophysics Lab
#
# 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 applicable law ... | 3,201 | 34.186813 | 89 | py |
AgML | AgML-main/experiments/benchmarking/detection_learning.py | # Copyright 2021 UC Davis Plant AI and Biophysics Lab
#
# 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 applicable law ... | 21,691 | 38.44 | 100 | py |
AgML | AgML-main/experiments/benchmarking/classification.py | # Copyright 2021 UC Davis Plant AI and Biophysics Lab
#
# 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 applicable law ... | 8,586 | 36.497817 | 93 | py |
AgML | AgML-main/experiments/benchmarking/segmentation_lightning.py | # Copyright 2021 UC Davis Plant AI and Biophysics Lab
#
# 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 applicable law ... | 11,264 | 34.424528 | 110 | py |
AgML | AgML-main/experiments/benchmarking/classification_lightning.py | # Copyright 2021 UC Davis Plant AI and Biophysics Lab
#
# 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 applicable law ... | 9,116 | 33.665399 | 90 | py |
AgML | AgML-main/experiments/benchmarking/detection_lightning.py | # Copyright 2021 UC Davis Plant AI and Biophysics Lab
#
# 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 applicable law ... | 8,378 | 36.914027 | 89 | py |
AgML | AgML-main/experiments/benchmarking/finetune_evaluation.py | # Copyright 2021 UC Davis Plant AI and Biophysics Lab
#
# 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 applicable law ... | 6,788 | 35.304813 | 89 | py |
AgML | AgML-main/experiments/benchmarking/experiment.py | # Copyright 2021 UC Davis Plant AI and Biophysics Lab
#
# 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 applicable law ... | 5,443 | 37.609929 | 90 | py |
AgML | AgML-main/experiments/benchmarking/detection_data.py | # Copyright 2021 UC Davis Plant AI and Biophysics Lab
#
# 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 applicable law ... | 10,965 | 34.374194 | 97 | py |
AgML | AgML-main/experiments/benchmarking/detection_lightning_multiple.py | # Copyright 2021 UC Davis Plant AI and Biophysics Lab
#
# 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 applicable law ... | 22,292 | 36.848896 | 100 | py |
AgML | AgML-main/experiments/benchmarking/detection_lightning_ssd.py | # Copyright 2021 UC Davis Plant AI and Biophysics Lab
#
# 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 applicable law ... | 6,654 | 29.953488 | 82 | py |
AgML | AgML-main/experiments/benchmarking/mean_average_precision_torch.py | import torch
import numpy as np
from tqdm import tqdm
def _scalar_to_array(*args):
"""Converts 0-dimensional scalar arrays to 1-d arrays."""
cvt = lambda x: np.expand_dims(x, 0) if x.ndim == 0 else x
outs = [cvt(arg) for arg in args]
return outs[0] if len(args) == 1 else outs
def _add_truth_scores_... | 11,134 | 35.749175 | 84 | py |
AgML | AgML-main/experiments/benchmarking/tools.py | # Copyright 2021 UC Davis Plant AI and Biophysics Lab
#
# 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 applicable law ... | 4,718 | 30.885135 | 109 | py |
AgML | AgML-main/experiments/benchmarking/map_evaluation.py | import torch
import numpy as np
from tqdm import tqdm
def _scalar_to_array(*args):
"""Converts 0-dimensional scalar arrays to 1-d arrays."""
cvt = lambda x: np.expand_dims(x, 0) if x.ndim == 0 else x
outs = [cvt(arg) for arg in args]
return outs[0] if len(args) == 1 else outs
def _add_truth_scores_... | 11,134 | 35.749175 | 84 | py |
AgML | AgML-main/experiments/benchmarking/accuracy_evaluation.py | # Copyright 2021 UC Davis Plant AI and Biophysics Lab
#
# 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 applicable law ... | 3,960 | 30.688 | 90 | py |
AgML | AgML-main/experiments/benchmarking/map_evaluation_multiple.py | # Copyright 2021 UC Davis Plant AI and Biophysics Lab
#
# 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 applicable law ... | 6,711 | 36.082873 | 107 | py |
AgML | AgML-main/experiments/benchmarking/segmentation_lightning_pretrained.py | # Copyright 2021 UC Davis Plant AI and Biophysics Lab
#
# 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 applicable law ... | 10,211 | 33.268456 | 91 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.