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 |
|---|---|---|---|---|---|---|
CP2 | CP2-main/main.py | import argparse
import builtins
import math
import os
import random
import shutil
import time
import warnings
import logging
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.multiprocessing as mp
import tor... | 16,052 | 39.537879 | 120 | py |
CP2 | CP2-main/builder.py | # The CP2_MoCo model is built upon moco v2 code base:
# https://github.com/facebookresearch/moco
# Copyright (c) Facebook, Inc. and its affilates. All Rights Reserved
import torch
import torch.nn as nn
from mmseg.models import build_segmentor
class CP2_MOCO(nn.Module):
def __init__(self, cfg, dim=128, K=65536, m=0... | 6,009 | 34.146199 | 97 | py |
CP2 | CP2-main/tools/train.py | import argparse
import copy
import os
import os.path as osp
import time
import mmcv
import torch
from mmcv.runner import init_dist
from mmcv.utils import Config, DictAction, get_git_hash
from mmseg import __version__
from mmseg.apis import set_random_seed, train_segmentor
from mmseg.datasets import build_dataset
from... | 6,051 | 33.19209 | 92 | py |
CP2 | CP2-main/mmseg/apis/inference.py | import matplotlib.pyplot as plt
import mmcv
import torch
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from mmseg.datasets.pipelines import Compose
from mmseg.models import build_segmentor
def init_segmentor(config, checkpoint=None, device='cuda:0'):
"""Initialize a segmentor... | 4,582 | 32.698529 | 79 | py |
CP2 | CP2-main/mmseg/apis/test.py | import os.path as osp
import pickle
import shutil
import tempfile
import mmcv
import numpy as np
import torch
import torch.distributed as dist
from mmcv.image import tensor2imgs
from mmcv.runner import get_dist_info
def np2tmp(array, temp_file_name=None):
"""Save ndarray to local numpy file.
Args:
a... | 8,209 | 33.351464 | 79 | py |
CP2 | CP2-main/mmseg/apis/train.py | import random
import warnings
import time
import numpy as np
import torch
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import build_optimizer, build_runner
from mmseg.core import DistEvalHook, EvalHook
from mmseg.datasets import build_dataloader, build_dataset
from mmseg.utils ... | 4,066 | 32.61157 | 83 | py |
CP2 | CP2-main/mmseg/core/evaluation/eval_hooks.py | import os.path as osp
import torch.distributed as dist
from mmcv.runner import DistEvalHook as _DistEvalHook
from mmcv.runner import EvalHook as _EvalHook
from torch.nn.modules.batchnorm import _BatchNorm
class EvalHook(_EvalHook):
"""Single GPU EvalHook, with efficient test support.
Args:
by_epoch ... | 3,528 | 36.147368 | 79 | py |
CP2 | CP2-main/mmseg/core/evaluation/metrics.py | from collections import OrderedDict
import mmcv
import numpy as np
import torch
def f_score(precision, recall, beta=1):
"""calcuate the f-score value.
Args:
precision (float | torch.Tensor): The precision value.
recall (float | torch.Tensor): The recall value.
beta (int): Determines ... | 13,051 | 38.914373 | 79 | py |
CP2 | CP2-main/mmseg/core/seg/sampler/ohem_pixel_sampler.py | import torch
import torch.nn.functional as F
from ..builder import PIXEL_SAMPLERS
from .base_pixel_sampler import BasePixelSampler
@PIXEL_SAMPLERS.register_module()
class OHEMPixelSampler(BasePixelSampler):
"""Online Hard Example Mining Sampler for segmentation.
Args:
context (nn.Module): The contex... | 3,155 | 39.987013 | 103 | py |
CP2 | CP2-main/mmseg/models/decode_heads/fcn_head.py | import torch
import torch.nn as nn
from mmcv.cnn import ConvModule
from ..builder import HEADS
from .decode_head import BaseDecodeHead
@HEADS.register_module()
class FCNHead(BaseDecodeHead):
"""Fully Convolution Networks for Semantic Segmentation.
This head is implemented of `FCNNet <https://arxiv.org/abs/1... | 3,166 | 33.423913 | 77 | py |
CP2 | CP2-main/mmseg/models/decode_heads/decode_head.py | from abc import ABCMeta, abstractmethod
import torch
import torch.nn as nn
from mmcv.cnn import normal_init
from mmcv.cnn import constant_init
from mmcv.runner import auto_fp16, force_fp32
from mmcv.runner import load_checkpoint
from mmseg.utils import get_root_logger
from mmseg.core import build_pixel_sampler
from m... | 9,545 | 38.283951 | 78 | py |
CP2 | CP2-main/mmseg/models/decode_heads/aspp_head.py | import torch
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmseg.ops import resize
from mmseg.models.builder import HEADS
from mmseg.models.decode_heads.decode_head import BaseDecodeHead
class ASPPModule(nn.ModuleList):
"""Atrous Spatial Pyramid Pooling (ASPP) Module.
Args:
dilations (t... | 3,807 | 31.547009 | 76 | py |
CP2 | CP2-main/mmseg/models/utils/se_layer.py | import mmcv
import torch.nn as nn
from mmcv.cnn import ConvModule
from .make_divisible import make_divisible
class SELayer(nn.Module):
"""Squeeze-and-Excitation Module.
Args:
channels (int): The input (and output) channels of the SE layer.
ratio (int): Squeeze ratio in SELayer, the intermedi... | 2,103 | 35.275862 | 79 | py |
CP2 | CP2-main/mmseg/models/utils/weight_init.py | """Modified from https://github.com/rwightman/pytorch-image-
models/blob/master/timm/models/layers/drop.py."""
import math
import warnings
import torch
def _no_grad_trunc_normal_(tensor, mean, std, a, b):
"""Reference: https://people.sc.fsu.edu/~jburkardt/presentations
/truncated_normal.pdf"""
def norm... | 2,327 | 35.952381 | 76 | py |
CP2 | CP2-main/mmseg/models/utils/res_layer.py | from mmcv.cnn import build_conv_layer, build_norm_layer
from torch import nn as nn
class ResLayer(nn.Sequential):
"""ResLayer to build ResNet style backbone.
Args:
block (nn.Module): block used to build ResLayer.
inplanes (int): inplanes of block.
planes (int): planes of block.
... | 3,315 | 33.905263 | 79 | py |
CP2 | CP2-main/mmseg/models/utils/self_attention_block.py | import torch
from mmcv.cnn import ConvModule, constant_init
from torch import nn as nn
from torch.nn import functional as F
class SelfAttentionBlock(nn.Module):
"""General self-attention block/non-local block.
Please refer to https://arxiv.org/abs/1706.03762 for details about key,
query and value.
A... | 6,125 | 37.2875 | 78 | py |
CP2 | CP2-main/mmseg/models/utils/up_conv_block.py | import torch
import torch.nn as nn
from mmcv.cnn import ConvModule, build_upsample_layer
class UpConvBlock(nn.Module):
"""Upsample convolution block in decoder for UNet.
This upsample convolution block consists of one upsample module
followed by one convolution block. The upsample module expands the
... | 3,968 | 37.911765 | 79 | py |
CP2 | CP2-main/mmseg/models/utils/inverted_residual.py | from mmcv.cnn import ConvModule
from torch import nn
from torch.utils import checkpoint as cp
from .se_layer import SELayer
class InvertedResidual(nn.Module):
"""InvertedResidual block for MobileNetV2.
Args:
in_channels (int): The input channels of the InvertedResidual block.
out_channels (i... | 7,005 | 32.521531 | 79 | py |
CP2 | CP2-main/mmseg/models/utils/drop.py | """Modified from https://github.com/rwightman/pytorch-image-
models/blob/master/timm/models/layers/drop.py."""
import torch
from torch import nn
class DropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of
residual blocks).
Args:
drop_prob (float): Drop r... | 1,015 | 30.75 | 78 | py |
CP2 | CP2-main/mmseg/models/segmentors/base.py | import logging
import warnings
from abc import ABCMeta, abstractmethod
from collections import OrderedDict
import mmcv
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
from mmcv.runner import auto_fp16
class BaseSegmentor(nn.Module):
"""Base class for segmentors."""
__m... | 10,350 | 36.777372 | 79 | py |
CP2 | CP2-main/mmseg/models/segmentors/encoder_decoder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmseg.core import add_prefix
from mmseg.ops import resize
from .. import builder
from ..builder import SEGMENTORS
from .base import BaseSegmentor
@SEGMENTORS.register_module()
class EncoderDecoder(BaseSegmentor):
"""Encoder Decoder segmentor... | 11,752 | 36.790997 | 79 | py |
CP2 | CP2-main/mmseg/models/losses/dice_loss.py | """Modified from https://github.com/LikeLy-Journey/SegmenTron/blob/master/
segmentron/solver/loss.py (Apache-2.0 License)"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import get_class_weight, weighted_loss
@weighted_loss
def dice_loss(pred,
... | 4,239 | 34.333333 | 79 | py |
CP2 | CP2-main/mmseg/models/losses/lovasz_loss.py | """Modified from https://github.com/bermanmaxim/LovaszSoftmax/blob/master/pytor
ch/lovasz_losses.py Lovasz-Softmax and Jaccard hinge loss in PyTorch Maxim
Berman 2018 ESAT-PSI KU Leuven (MIT License)"""
import mmcv
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .u... | 11,391 | 36.473684 | 79 | py |
CP2 | CP2-main/mmseg/models/losses/utils.py | import functools
import mmcv
import numpy as np
import torch.nn.functional as F
def get_class_weight(class_weight):
"""Get class weight for loss function.
Args:
class_weight (list[float] | str | None): If class_weight is a str,
take it as a file name and read from it.
"""
if isin... | 3,690 | 29.254098 | 79 | py |
CP2 | CP2-main/mmseg/models/losses/accuracy.py | import torch.nn as nn
def accuracy(pred, target, topk=1, thresh=None):
"""Calculate accuracy according to the prediction and target.
Args:
pred (torch.Tensor): The model prediction, shape (N, num_class, ...)
target (torch.Tensor): The target of each prediction, shape (N, , ...)
topk (... | 2,970 | 36.607595 | 79 | py |
CP2 | CP2-main/mmseg/models/losses/cross_entropy_loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import get_class_weight, weight_reduce_loss
def cross_entropy(pred,
label,
weight=None,
class_weight=None,
reduction='mean',
... | 7,437 | 36.376884 | 79 | py |
CP2 | CP2-main/mmseg/models/backbones/resnet.py | import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import (build_conv_layer, build_norm_layer, build_plugin_layer,
constant_init, kaiming_init)
from mmcv.runner import load_checkpoint
from mmcv.utils.parrots_wrapper import _BatchNorm
from mmseg.utils import get_root_logger
fr... | 24,210 | 34.139332 | 79 | py |
CP2 | CP2-main/mmseg/models/backbones/vit.py | """Modified from https://github.com/rwightman/pytorch-image-
models/blob/master/timm/models/vision_transformer.py."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as cp
from mmcv.cnn import (Conv2d, Linear, build_activation_layer, build_norm_layer,
... | 18,574 | 38.270613 | 128 | py |
CP2 | CP2-main/mmseg/datasets/custom.py | import os
import os.path as osp
from collections import OrderedDict
from functools import reduce
import mmcv
import numpy as np
from mmcv.utils import print_log
from prettytable import PrettyTable
from torch.utils.data import Dataset
from mmseg.core import eval_metrics
from mmseg.utils import get_root_logger
from .bu... | 14,628 | 35.481297 | 79 | py |
CP2 | CP2-main/mmseg/datasets/dataset_wrappers.py | from torch.utils.data.dataset import ConcatDataset as _ConcatDataset
from .builder import DATASETS
@DATASETS.register_module()
class ConcatDataset(_ConcatDataset):
"""A wrapper of concatenated dataset.
Same as :obj:`torch.utils.data.dataset.ConcatDataset`, but
concat the group flag for image aspect rati... | 1,499 | 28.411765 | 78 | py |
CP2 | CP2-main/mmseg/datasets/builder.py | import copy
import platform
import random
from functools import partial
import numpy as np
from mmcv.parallel import collate
from mmcv.runner import get_dist_info
from mmcv.utils import Registry, build_from_cfg
from mmcv.utils.parrots_wrapper import DataLoader, PoolDataLoader
from torch.utils.data import DistributedSa... | 5,871 | 33.541176 | 79 | py |
CP2 | CP2-main/mmseg/datasets/pipelines/formating.py | from collections.abc import Sequence
import mmcv
import numpy as np
import torch
from mmcv.parallel import DataContainer as DC
from ..builder import PIPELINES
def to_tensor(data):
"""Convert objects of various python types to :obj:`torch.Tensor`.
Supported types are: :class:`numpy.ndarray`, :class:`torch.T... | 9,228 | 30.934256 | 79 | py |
CP2 | CP2-main/mmseg/ops/wrappers.py | import warnings
import torch.nn as nn
import torch.nn.functional as F
def resize(input,
size=None,
scale_factor=None,
mode='nearest',
align_corners=None,
warning=True):
if warning:
if size is not None and align_corners:
input_h, input_w =... | 1,827 | 34.843137 | 79 | py |
CP2 | CP2-main/mmseg/ops/encoding.py | import torch
from torch import nn
from torch.nn import functional as F
class Encoding(nn.Module):
"""Encoding Layer: a learnable residual encoder.
Input is of shape (batch_size, channels, height, width).
Output is of shape (batch_size, num_codes, channels).
Args:
channels: dimension of the ... | 2,788 | 36.186667 | 78 | py |
CP2 | CP2-main/configs/config_pretrain.py | norm_cfg = dict(type='BN', requires_grad=True)
pretrain_path = None # Please set the path to pretrained weights for Quick Tuning
model = dict(
type='EncoderDecoder',
pretrained=pretrain_path,
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
... | 952 | 27.029412 | 84 | py |
CP2 | CP2-main/configs/config_finetune.py | # model settings
norm_cfg = dict(type='SyncBN', requires_grad=True)
pretrain_path = '' # Please set the path to pretrained model
data_root = '' # Please set the path to your finetuing dataset (PASCAL VOC 2012)
model = dict(
type='EncoderDecoder',
pretrained=pretrain_path,
backbone=dict(
typ... | 3,664 | 29.798319 | 85 | py |
SA-UNet | SA-UNet-master/Dropblock.py | import keras
import keras.backend as K
class DropBlock1D(keras.layers.Layer):
"""See: https://arxiv.org/pdf/1810.12890.pdf"""
def __init__(self,
block_size,
keep_prob,
sync_channels=False,
data_format=None,
**kwargs):
... | 7,815 | 38.474747 | 103 | py |
SA-UNet | SA-UNet-master/Train_chase.py | import os
import numpy as np
import cv2
from keras.callbacks import TensorBoard, ModelCheckpoint
np.random.seed(42)
import scipy.misc as mc
import matplotlib.pyplot as plt
data_location = ''
training_images_loc = data_location + 'CHASE/train/imageS/'
training_label_loc = data_location + 'CHASE/train/labelS/'
validate_... | 4,715 | 35.84375 | 143 | py |
SA-UNet | SA-UNet-master/Train_drive.py | import os
import cv2
from keras.callbacks import TensorBoard, ModelCheckpoint
import matplotlib.pyplot as plt
import numpy as np
from scipy.misc.pilutil import *
data_location = ''
training_images_loc = data_location + 'DRIVE/train/images/'
training_label_loc = data_location + 'DRIVE/train/labels/'
validate_images_... | 4,541 | 35.336 | 119 | py |
SA-UNet | SA-UNet-master/SA_UNet.py |
from keras.optimizers import *
from keras.models import Model
from keras.layers import Input,Conv2DTranspose, MaxPooling2D,BatchNormalization,concatenate,Activation
from Spatial_Attention import *
def Backbone(input_size=(512, 512, 3), block_size=7,keep_prob=0.9,start_neurons=16,lr=1e-3):
inputs = Input(input_... | 9,007 | 45.43299 | 102 | py |
SA-UNet | SA-UNet-master/Spatial_Attention.py | from keras.layers import GlobalAveragePooling2D, GlobalMaxPooling2D, Reshape, Dense, multiply, Permute, Concatenate, \
Conv2D, Add, Activation, Lambda,Conv1D
from Dropblock import *
def spatial_attention(input_feature):
kernel_size = 7
if K.image_data_format() == "channels_first":
channel = input_... | 1,364 | 40.363636 | 118 | py |
pegnn | pegnn-master/train_autoencoder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch_geometric.loader import DataLoader
import json
from src.datasets import CSVDataset
from src.utils.scaler import LatticeScaler
from src.utils.visualize import get_fig
from src.utils.debug import check_grad
from sr... | 6,650 | 31.602941 | 88 | py |
pegnn | pegnn-master/train_benchmark.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch_geometric.loader import DataLoader
import json
from src.datasets import CSVDataset
from src.utils.scaler import LatticeScaler
from src.utils.visualize import get_fig
from src.utils.debug import check_grad
from sr... | 7,547 | 32.251101 | 93 | py |
pegnn | pegnn-master/src/models/operator/loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from src.datasets.data import CrystalData
from src.utils.scaler import LatticeScaler
from src.models.operator.utils import lattice_params_to_matrix_torch
from typing import Dict, Tuple
def get_metrics(batch: CrystalData, reconstructed: torch.FloatT... | 2,878 | 32.476744 | 148 | py |
pegnn | pegnn-master/src/models/operator/utils.py | import torch
import torch.nn as nn
import tqdm
import os
import json
from dataclasses import dataclass
def save_step(spike_dir, batch, model, opti):
os.makedirs(spike_dir, exist_ok=True)
batch_dict = {
"cell": batch.cell.tolist(),
"pos": batch.pos.tolist(),
"z": batch.z.tolist(),
... | 8,969 | 28.409836 | 90 | py |
pegnn | pegnn-master/src/models/operator/denoise.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import src.models.layers.operator.gnn as ops
from src.models.operator.utils import build_mlp, lattice_params_to_matrix_torch
from src.utils.geometry import Geometry
from torch_scatter import scatter_mean
class Denoise(nn.Module):
def __init__(
... | 4,657 | 29.051613 | 79 | py |
pegnn | pegnn-master/src/models/operator/autoencoder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import src.models.layers.operator.gnn as ops
from src.models.operator.utils import build_mlp
from src.utils.geometry import Geometry
from torch_scatter import scatter_mean
from typing import Tuple
class AutoEncoder(nn.Module):
def __init__(
... | 4,223 | 25.236025 | 88 | py |
pegnn | pegnn-master/src/models/layers/random.py | import torch
import torch.nn as nn
class RandomMatrixSL3Z(nn.Module):
def __init__(self):
super().__init__()
generators = torch.tensor(
[
[[1, 0, 1], [0, -1, -1], [0, 1, 0]],
[[0, 1, 0], [0, 0, 1], [1, 0, 0]],
[[0, 1, 0], [1, 0, 0], [-1,... | 1,510 | 25.982143 | 85 | py |
pegnn | pegnn-master/src/models/layers/operator/gnn.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_scatter import scatter
from typing import Tuple
from src.utils.geometry import Geometry
from src.utils.shape import build_shapes, assert_tensor_match, shape
from src.models.layers.operator.operator import Operator, make_operator
class E... | 10,092 | 29.492447 | 88 | py |
pegnn | pegnn-master/src/models/layers/operator/operator.py | import torch
import torch.nn as nn
from src.utils.geometry import Geometry
from src.models.layers.operator.grad import Grad
import enum
from typing import List
import abc
class Operator(nn.Module):
def __init__(self, operators_edges, operators_triplets, normalize: bool = True):
super().__init__()
... | 11,933 | 31.254054 | 103 | py |
pegnn | pegnn-master/src/models/layers/operator/grad_unittest.py | import torch
import torch.nn as nn
from torch.autograd.functional import jacobian
from .grad import Grad
import unittest
import time
class TestGrad(unittest.TestCase):
batch_size = 1024
verbose = True
def log(self, *args, **kwargs):
if TestGrad.verbose:
print(*args, **kwargs)
d... | 11,560 | 31.566197 | 75 | py |
pegnn | pegnn-master/src/models/layers/operator/grad.py | import torch
import torch.nn as nn
class Grad(nn.Module):
def __init__(self):
super().__init__()
self.I = nn.Parameter(torch.eye(3), requires_grad=False)
self.K = nn.Parameter(torch.tensor([[[0, 0, 0], [0, 0, 1], [0, -1, 0]], [[0, 0, -1], [0, 0, 0], [
1, 0, 0... | 7,661 | 36.014493 | 120 | py |
pegnn | pegnn-master/src/datasets/data.py | from __future__ import annotations
import torch
import torch.nn.functional as F
from torch_geometric.data import Data
class CrystalData(Data):
def __init__(self, *args, **kwargs):
if "pos_cart" in kwargs:
assert isinstance(kwargs["cell"], torch.FloatTensor)
assert isinstance(kwarg... | 2,855 | 27.848485 | 88 | py |
pegnn | pegnn-master/src/datasets/csv_dataset.py | from typing import Iterator
from torch_geometric.data import InMemoryDataset, Data
from torch_geometric.loader import DataLoader
import torch
import pandas as pd
import numpy as np
from pymatgen.core.structure import Structure
from pymatgen.io.ase import AseAtomsAdaptor
from ase.neighborlist import neighbor_list
from ... | 4,203 | 28.194444 | 172 | py |
pegnn | pegnn-master/src/utils/scaler.py | import torch
import torch.nn as nn
import numpy as np
from torch_geometric.loader import DataLoader
import tqdm
from src.utils.geometry import Geometry
from typing import Tuple
class LatticeScaler(nn.Module):
def __init__(self):
super(LatticeScaler, self).__init__()
self.mean = nn.Parameter(... | 6,553 | 32.269036 | 128 | py |
pegnn | pegnn-master/src/utils/shape.py | import torch
from typing import Tuple, List, Union, Dict
from collections import namedtuple
class shape:
def __init__(self, *dim: Union[int, str], dtype=None):
assert isinstance(dim, tuple)
for d in dim:
assert (type(d) == int and -1 <= d) or type(d) == str
assert (dtype is N... | 2,051 | 27.901408 | 100 | py |
pegnn | pegnn-master/src/utils/polar.py | import torch
import unittest
__all__ = ["polar"]
def polar(a: torch.FloatTensor, side: str = "right"):
if side not in ["right", "left"]:
raise ValueError("`side` must be either 'right' or 'left'")
assert a.ndim == 3 and a.shape[1] == a.shape[2]
w, s, vh = torch.linalg.svd(a, full_matrices=False... | 3,936 | 25.782313 | 83 | py |
pegnn | pegnn-master/src/utils/encoder.py | import torch
import json
import numpy as np
from ase.spacegroup import Spacegroup
__all__ = ["CrystalEncoder"]
class CrystalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, torch.Tensor):
return obj.t... | 561 | 27.1 | 59 | py |
pegnn | pegnn-master/src/utils/replay.py | import torch
class Replay:
def __init__(self, batch_size: int, max_depth: int = 32, proba_in: float = 0.1):
self.batch_size = batch_size
self.max_depth = max_depth
self.proba_in = proba_in
self.cell = torch.zeros(0, 3, 3, dtype=torch.float32)
self.pos = torch.zeros(0, 3, d... | 2,510 | 36.477612 | 88 | py |
pegnn | pegnn-master/src/utils/geometry.py | import torch
import torch.nn.functional as F
from .shape import build_shapes, assert_tensor_match, shape
from .timeout import timeout
from dataclasses import dataclass
import crystallographic_graph
@dataclass(init=False)
class Geometry:
batch: torch.LongTensor
batch_edges: torch.LongTensor
batch_triple... | 11,649 | 30.233244 | 79 | py |
pegnn | pegnn-master/src/utils/io.py | from ctypes import Structure
import torch
import torch.nn.functional as F
from ase.spacegroup import crystal
import ase.io as io
import pandas as pd
from src.utils.visualize import select
import os
def write_cif(file_name, idx, cell, pos, z, num_atoms):
cell, pos, z = select(idx, cell, pos, z, num_atoms)
... | 2,197 | 27.179487 | 75 | py |
pegnn | pegnn-master/src/utils/visualize.py | import torch
from ase.spacegroup import crystal
from ase.visualize.plot import plot_atoms
import matplotlib.pyplot as plt
from src.utils.elements import elements
from src.models.operator.utils import lattice_params_to_matrix_torch
def select(idx, cell, pos, z, num_atoms):
struct_idx = torch.arange(num_atoms.shap... | 3,558 | 28.172131 | 80 | py |
T2TL | T2TL-main/src/T2TL.py |
import argparse
import time
import datetime
import torch
import torch_ac
import tensorboardX
import sys
import glob
from math import floor
import utils
from model import ACModel
from context_model import ContextACModel
if __name__ == '__main__':
# Parse arguments
parser = argparse.ArgumentParser()
## G... | 17,759 | 50.32948 | 296 | py |
T2TL | T2TL-main/src/T1TL_pretrain.py |
import argparse
import time
import datetime
import torch
import torch_ac
import tensorboardX
import sys
import glob
from math import floor
import utils
from model import ACModel
from recurrent_model import RecurrentACModel
if __name__ == '__main__':
# Parse arguments
parser = argparse.ArgumentParser()
... | 16,899 | 50.057402 | 265 | py |
T2TL | T2TL-main/src/context_model.py | """
This is the description of the deep NN currently being used.
It is a small CNN for the features with an GRU encoding of the LTL task.
The features and LTL are preprocessed by utils.format.get_obss_preprocessor(...) function:
- In that function, I transformed the LTL tuple representation into a text representati... | 24,186 | 42.817029 | 122 | py |
T2TL | T2TL-main/src/T2TL_pretrain.py |
import argparse
import time
import datetime
import torch
import torch_ac
import tensorboardX
import sys
import glob
from math import floor
import utils
from model import ACModel
from context_model import ContextACModel
if __name__ == '__main__':
# Parse arguments
parser = argparse.ArgumentParser()
## G... | 18,009 | 51.354651 | 313 | py |
T2TL | T2TL-main/src/env_model.py | import torch
import torch.nn as nn
from envs import *
from gym.envs.classic_control import PendulumEnv
def getEnvModel(env, obs_space):
env = env.unwrapped
if isinstance(env, ZonesEnv):
return ZonesEnvModel(obs_space)
# Add your EnvModel here...
# The default case (No environment observati... | 4,146 | 28.204225 | 98 | py |
T2TL | T2TL-main/src/model.py | """
This is the description of the deep NN currently being used.
It is a small CNN for the features with an GRU encoding of the LTL task.
The features and LTL are preprocessed by utils.format.get_obss_preprocessor(...) function:
- In that function, I transformed the LTL tuple representation into a text representati... | 22,185 | 42.247563 | 136 | py |
T2TL | T2TL-main/src/train_PreGNNAgent.py |
import argparse
import time
import datetime
import torch
import torch_ac
import tensorboardX
import sys
import glob
from math import floor
import utils
from model import ACModel
from recurrent_model import RecurrentACModel
if __name__ == '__main__':
# Parse arguments
parser = argparse.ArgumentParser()
... | 16,595 | 49.443769 | 265 | py |
T2TL | T2TL-main/src/transEncoder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
class ContextTransformer(nn.Module):
def __init__(self, obs_size, obsr_dim, d_model, d_out, pool, args, context=False):
super(ContextTransformer, self).__init__()
self.context = context
self.obsr_dim = obsr_dim
... | 15,896 | 43.90678 | 121 | py |
T2TL | T2TL-main/src/test_safety.py | import argparse
import time
import sys
import numpy as np
import glfw
import utils
import torch
import gym
import safety_gym
import ltl_wrappers
import ltl_progression
from gym import wrappers, logger
from envs.safety import safety_wrappers
class RandomAgent(object):
"""This agent picks actions randomly"""
de... | 4,800 | 33.292857 | 153 | py |
T2TL | T2TL-main/src/recurrent_model.py | """
This is the description of the deep NN currently being used.
It is a small CNN for the features with an GRU encoding of the LTL task.
The features and LTL are preprocessed by utils.format.get_obss_preprocessor(...) function:
- In that function, I transformed the LTL tuple representation into a text representati... | 6,302 | 37.2 | 134 | py |
T2TL | T2TL-main/src/policy_network.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Categorical, Normal
from gym.spaces import Box, Discrete
class PolicyNetwork(nn.Module):
def __init__(self, in_dim, action_space, hiddens=[], scales=None, activation=nn.Tanh()):
super().__init__()
... | 2,026 | 33.355932 | 92 | py |
T2TL | T2TL-main/src/T1TL.py |
import argparse
import time
import datetime
import torch
import torch_ac
import tensorboardX
import sys
import glob
from math import floor
import utils
from model import ACModel
from recurrent_model import RecurrentACModel
if __name__ == '__main__':
# Parse arguments
parser = argparse.ArgumentParser()
... | 16,666 | 49.506061 | 268 | py |
T2TL | T2TL-main/src/torch_ac/format.py | import torch
def default_preprocess_obss(obss, device=None):
return torch.tensor(obss, device=device) | 106 | 25.75 | 47 | py |
T2TL | T2TL-main/src/torch_ac/model.py | from abc import abstractmethod, abstractproperty
import torch.nn as nn
import torch.nn.functional as F
class ACModel:
recurrent = False
@abstractmethod
def __init__(self, obs_space, action_space):
pass
@abstractmethod
def forward(self, obs):
pass
class RecurrentACModel(ACModel):
... | 485 | 17.692308 | 48 | py |
T2TL | T2TL-main/src/torch_ac/__init__.py | from torch_ac.algos import A2CAlgo, PPOAlgo
from torch_ac.model import ACModel, RecurrentACModel
from torch_ac.utils import DictList | 132 | 43.333333 | 52 | py |
T2TL | T2TL-main/src/torch_ac/algos/base.py | from abc import ABC, abstractmethod
import torch
from torch_ac.format import default_preprocess_obss
from torch_ac.utils import DictList, ParallelEnv
import numpy as np
from collections import deque
class BaseAlgo(ABC):
"""The base class for RL algorithms."""
def __init__(self, envs, acmodel, device, num_fr... | 17,512 | 49.469741 | 152 | py |
T2TL | T2TL-main/src/torch_ac/algos/a2c.py | import numpy
import torch
import torch.nn.functional as F
from torch_ac.algos.base import BaseAlgo
class A2CAlgo(BaseAlgo):
"""The Advantage Actor-Critic algorithm."""
def __init__(self, envs, acmodel, device=None, num_frames_per_proc=None, discount=0.99, lr=0.01, gae_lambda=0.95,
entropy_co... | 3,659 | 31.972973 | 117 | py |
T2TL | T2TL-main/src/torch_ac/algos/ppo.py | import numpy
import torch
import torch.nn.functional as F
from torch_ac.algos.base import BaseAlgo
class PPOAlgo(BaseAlgo):
"""The Proximal Policy Optimization algorithm
([Schulman et al., 2015](https://arxiv.org/abs/1707.06347))."""
def __init__(self, envs, acmodel, device=None, num_frames_per_proc=None... | 6,682 | 39.50303 | 125 | py |
T2TL | T2TL-main/src/torch_ac/algos/__init__.py | from torch_ac.algos.a2c import A2CAlgo
from torch_ac.algos.ppo import PPOAlgo | 77 | 38 | 38 | py |
T2TL | T2TL-main/src/torch_ac/utils/__init__.py | from torch_ac.utils.dictlist import DictList
from torch_ac.utils.penv import ParallelEnv | 88 | 43.5 | 44 | py |
T2TL | T2TL-main/src/utils/ast_builder.py | import ring
import numpy as np
import torch
import dgl
import networkx as nx
from sklearn.preprocessing import OneHotEncoder
edge_types = {k:v for (v, k) in enumerate(["self", "arg", "arg1", "arg2"])}
"""
A class that can take an LTL formula and generate the Abstract Syntax Tree (AST) of it. This
code can generate tr... | 5,910 | 37.383117 | 197 | py |
T2TL | T2TL-main/src/utils/storage.py | import csv
import os
import torch
import logging
import sys
import pickle
import utils
def create_folders_if_necessary(path):
dirname = os.path.dirname(path)
if not os.path.isdir(dirname):
os.makedirs(dirname)
def get_storage_dir():
if "RL_STORAGE" in os.environ:
return os.environ["RL_S... | 1,978 | 22.282353 | 105 | py |
T2TL | T2TL-main/src/utils/format.py | """
These functions preprocess the observations.
When trying more sophisticated encoding for LTL, we might have to modify this code.
"""
import os
import json
import re
import torch
import torch_ac
import gym
import numpy as np
import utils
from envs import *
from ltl_wrappers import LTLEnv
def get_obss_preprocessor... | 4,698 | 35.710938 | 161 | py |
T2TL | T2TL-main/src/utils/evaluator.py | import time
import torch
from torch_ac.utils.penv import ParallelEnv
#import tensorboardX
import utils
import argparse
import datetime
class Eval:
def __init__(self, env, model_name, ltl_sampler,
seed=0, device="cpu", argmax=False,
num_procs=1, ignoreLTL=False, progression_mode=Tru... | 6,373 | 42.067568 | 189 | py |
T2TL | T2TL-main/src/utils/agent.py | import torch
import utils
from model import ACModel
from recurrent_model import RecurrentACModel
class Agent:
"""An agent.
It is able:
- to choose an action given an observation,
- to analyze the feedback (i.e. reward and done state) of its action."""
def __init__(self, env, obs_space, action_sp... | 2,374 | 33.926471 | 104 | py |
T2TL | T2TL-main/src/utils/other.py | import random
import numpy
import torch
import collections
def seed(seed):
random.seed(seed)
numpy.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
def synthesize(array):
d = collections.OrderedDict()
d["mean"] = numpy.mean(arra... | 941 | 21.97561 | 75 | py |
T2TL | T2TL-main/src/gnns/graphs/GCN.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl
from dgl.nn.pytorch.conv import GraphConv
from gnns.graphs.GNN import GNN
class GCN(GNN):
def __init__(self, input_dim, output_dim, **kwargs):
super().__init__(input_dim, output_dim)
hidden_dims = kw... | 2,927 | 31.898876 | 103 | py |
T2TL | T2TL-main/src/gnns/graphs/RGCN.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl
from dgl.nn.pytorch.conv import RelGraphConv
from gnns.graphs.GNN import GNN
from utils.ast_builder import edge_types
class RGCN(GNN):
def __init__(self, input_dim, output_dim, **kwargs):
super().__init__(in... | 3,153 | 32.913978 | 103 | py |
T2TL | T2TL-main/src/gnns/graphs/GNN.py | import torch
import torch.nn as nn
from gnns import *
class GNN(nn.Module):
def __init__(self, input_dim, output_dim):
super().__init__()
def forward(self, g):
raise NotImplementedError
def GNNMaker(gnn_type, input_dim, output_dim): # 'RGCN_8x32_ROOT_SHARED'; 22; 33
clazz = lookup(gnn_t... | 393 | 23.625 | 81 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/sudoku/MNIST_train.py | from __future__ import print_function
import argparse
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import... | 6,939 | 40.065089 | 97 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/sudoku/MNIST_sudoku.py | import pytoulbar2
import math, numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import pickle
import torch
from torchvision import datasets, transforms
import itertools
import pandas as pd
import hashlib
##########################################################################
# Image output rout... | 5,697 | 33.325301 | 98 | py |
toulbar2 | toulbar2-master/docs/source/conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | 7,750 | 28.471483 | 79 | py |
StyleFusion | StyleFusion-master/src/model.py | from shared import *
from tf_lib import *
from dataset import *
from decode import *
from evaluate import *
"""
AUTHOR: Xiang Gao (xiag@microsoft.com) at Microsoft Research
"""
class ModelBase:
def __init__(self):
self.fld = None # str
self.n_trained = None # int
self.max_n_trained = None # int
self.d... | 24,831 | 28.632458 | 127 | py |
StyleFusion | StyleFusion-master/src/tf_lib.py |
from keras.models import Model, load_model, model_from_yaml
from keras.layers import Input, GRU, Dense, Embedding, Dropout, Concatenate, Lambda, Add, Subtract, Multiply, GaussianNoise
from keras.utils import plot_model
from keras.callbacks import ModelCheckpoint
from keras.optimizers import Adam, RMSprop
from keras.ca... | 455 | 37 | 123 | py |
NBFNet | NBFNet-master/script/run.py | import os
import sys
import math
import pprint
import torch
from torchdrug import core
from torchdrug.utils import comm
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from nbfnet import dataset, layer, model, task, util
def train_and_validate(cfg, solver):
if cfg.train.num_epoch == 0:
retu... | 1,690 | 25.421875 | 64 | py |
NBFNet | NBFNet-master/script/visualize.py | import os
import sys
import pprint
import torch
from torchdrug import core
from torchdrug.utils import comm
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from nbfnet import dataset, layer, model, task, util
vocab_file = os.path.join(os.path.dirname(__file__), "../data/fb15k237_entity.txt")
vocab_file... | 3,106 | 34.306818 | 84 | py |
NBFNet | NBFNet-master/nbfnet/layer.py | import torch
from torch import nn
from torch.nn import functional as F
from torch_scatter import scatter_add, scatter_mean, scatter_max, scatter_min
from torchdrug import layers
from torchdrug.layers import functional
class GeneralizedRelationalConv(layers.MessagePassingBase):
eps = 1e-6
message2mul = {
... | 7,872 | 46.427711 | 119 | py |
NBFNet | NBFNet-master/nbfnet/task.py | import math
import torch
from torch.nn import functional as F
from torch.utils import data as torch_data
from ogb import linkproppred
from torchdrug import core, tasks, metrics
from torchdrug.layers import functional
from torchdrug.core import Registry as R
Evaluator = core.make_configurable(linkproppred.Evaluator... | 22,136 | 44.832298 | 119 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.