repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/modules/flows.py
import copy import math import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Normal def create_masks( input_size, hidden_size, n_hidden, input_order="sequential", input_degrees=None ): # MADE paper sec 4: # degrees of connections between layers -- ensure at m...
13,996
32.646635
177
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/modules/feature.py
from typing import List, Optional import torch import torch.nn as nn class FeatureEmbedder(nn.Module): def __init__(self, cardinalities: List[int], embedding_dims: List[int],) -> None: super().__init__() assert len(cardinalities) == len(embedding_dims), 'the length of two variables should match'...
2,938
32.397727
100
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/modules/block/activation.py
from typing import Optional, Union, List, Tuple # Third-party imports import torch.nn as nn from torch import Tensor class Activation(nn.Module): """ Activation fuction Parameters ---------- activation Activation function to use. """ def __init__( self, activati...
979
19.416667
55
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/modules/block/cnn.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
5,557
26.37931
83
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/modules/block/mlp.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
2,023
26.726027
94
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/modules/block/encoder.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
12,696
26.188437
118
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/modules/block/enc2dec.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
2,929
25.636364
77
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/modules/block/decoder.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
5,368
25.979899
100
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/modules/block/quantile_output.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
5,592
25.258216
79
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/modules/block/__init__.py
0
0
0
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/modules/distribution/constant.py
import torch from torch.distributions.distribution import Distribution class ConstantDistribution(Distribution): r""" Creates a constant distribution, i.e. Var(x) = 0 Args: loss_type: L1 or L2 mu (Tensor): mean """ def __init__(self, loss_type, mu, validate_args=None): ...
1,045
25.15
92
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/modules/distribution/tweedie.py
import torch import numpy as np from torch.distributions.distribution import Distribution def est_lambda(mu, p): return mu ** (2 - p) / (2 - p) def est_alpha(p): return (2 - p) / (p - 1) def est_beta(mu, p): return mu ** (1 - p) / (p - 1) class Tweedie(Distribution): r""" Creates a Tweedie ...
1,660
24.166667
79
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/modules/distribution/__init__.py
from .constant import ConstantDistribution from .tweedie import Tweedie
72
23.333333
42
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/evaluation/evaluator.py
from itertools import chain, tee from typing import ( Any, Dict, Iterable, Iterator, List, Optional, Tuple, Union, Callable, ) # Third-party imports import numpy as np import pandas as pd from tqdm import tqdm from pts.feature import get_seasonality from pts.model import Quantile, ...
20,928
33.708126
119
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/evaluation/__init__.py
from .backtest import make_evaluation_predictions, backtest_metrics from .evaluator import Evaluator, MultivariateEvaluator
124
40.666667
67
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/evaluation/backtest.py
# Standard library imports import logging from typing import Dict, Iterator, NamedTuple, Optional, Tuple, Union # Third-party imports import pandas as pd from pts.dataset import ( DataEntry, Dataset, DatasetStatistics, calculate_dataset_statistics, ) from pts.model import Estimator, Predictor, Forecas...
8,129
33.449153
112
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/core/serde.py
import itertools import json import math import textwrap from functools import singledispatch from pydoc import locate from typing import Any, Optional, cast, NamedTuple import numpy as np import torch from pts.core import fqname_for bad_type_msg = textwrap.dedent( """ Cannot serialize type {}. See the docum...
10,036
26.49863
78
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/core/logging.py
import os import socket from datetime import datetime import logging from pathlib import Path def get_log_path(log_dir, log_comment='temp', trial='t0', mkdir=True): if log_comment=='': log_comment='temp' base_path = os.path.join('logs', log_dir, log_comment) trial_path = trial full_lo...
1,140
27.525
86
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/core/component.py
import functools import inspect from collections import OrderedDict from typing import Any import torch from pydantic import BaseConfig, BaseModel, create_model from pts.core.serde import dump_code class BaseValidatedInitializerModel(BaseModel): """ Base Pydantic model for components with :func:`validated` ...
5,487
32.668712
86
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/core/_base.py
def fqname_for(cls: type) -> str: """ Returns the fully qualified name of ``cls``. Parameters ---------- cls The class we are interested in. Returns ------- str The fully qualified name of ``cls``. """ return f"{cls.__module__}.{cls.__qualname__}"
305
19.4
49
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/core/__init__.py
# Relative imports from ._base import fqname_for __all__ = ["fqname_for"] # fix Sphinx issues, see https://bit.ly/2K2eptM for item in __all__: if hasattr(item, "__module__"): setattr(item, "__module__", __name__)
226
24.222222
47
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/artificial.py
import math import os import random from typing import Callable, List, NamedTuple, Optional, Tuple, Union import numpy as np import pandas as pd import rapidjson as json from .common import ( MetaData, CategoricalFeatureInfo, BasicFeatureInfo, FieldName, Dataset, TrainDatasets, DataEntry, ...
30,342
35.958587
118
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/utils.py
import shutil from pathlib import Path import numpy as np import pandas as pd import rapidjson as json from .common import TrainDatasets, MetaData from .file_dataset import FileDataset def frequency_add(ts: pd.Timestamp, amount: int) -> pd.Timestamp: return ts + ts.freq * amount def forecast_start(entry): ...
3,603
26.097744
81
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/transformed_iterable_dataset.py
import itertools from typing import Dict, Iterable, Iterator, Optional import numpy as np import torch from pts.transform.transform import Transformation from .common import DataEntry, Dataset class TransformedIterableDataset(torch.utils.data.IterableDataset): def __init__( self, dataset: Dataset, is_tr...
2,707
30.488372
99
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/common.py
from typing import Any, Dict, Iterable, NamedTuple, List, Optional import pandas as pd from pydantic import BaseModel # Dictionary used for data flowing through the transformations. DataEntry = Dict[str, Any] # A Dataset is an iterable of DataEntry. Dataset = Iterable[DataEntry] class SourceContext(NamedTuple): ...
1,997
22.785714
76
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/stat.py
import math from collections import defaultdict from typing import Any, List, NamedTuple, Optional, Set import numpy as np from tqdm import tqdm from pts.exception import assert_pts from .common import FieldName class ScaleHistogram: """ Scale histogram of a timeseries dataset This counts the number of ...
12,942
36.625
88
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/file_dataset.py
import functools import glob import random from pathlib import Path from typing import Iterator, List from typing import NamedTuple import rapidjson as json from .common import Dataset, DataEntry, SourceContext from .process import ProcessDataEntry def load(file_obj): for line in file_obj: yield json.lo...
3,319
26.666667
87
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/__init__.py
from .artificial import ( ArtificialDataset, ConstantDataset, ComplexSeasonalTimeSeries, RecipeDataset, constant_dataset, default_synthetic, generate_sf2, ) from .common import ( DataEntry, FieldName, Dataset, MetaData, TrainDatasets, DateConstants, ) from .file_datas...
864
25.212121
92
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/process.py
from functools import lru_cache from typing import Callable, List, cast import numpy as np import pandas as pd from pandas.tseries.offsets import Tick from .common import DataEntry class ProcessStartField: def __init__(self, name: str, freq: str) -> None: self.name = name self.freq = freq d...
3,843
33.321429
100
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/loader.py
import itertools from collections import defaultdict from typing import Any, Dict, Iterable, Iterator, List, Optional # noqa: F401 import numpy as np # Third-party imports import torch from pts.transform.transform import Transformation # First-party imports from .common import DataEntry, Dataset DataBatch = Dict[st...
7,684
30.756198
87
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/recipe.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
18,316
29.276033
88
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/multivariate_grouper.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
8,108
37.25
95
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/list_dataset.py
import random import torch from typing import Iterable from .common import DataEntry, Dataset, SourceContext from .process import ProcessDataEntry class ListDataset(Dataset): def __init__( self, data_iter: Iterable[DataEntry], freq: str, one_dim_target: bool = True, shuffl...
945
26.028571
78
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/repository/_m4.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
2,966
33.5
104
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/repository/_gp_copula_2019.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
5,230
31.490683
138
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/repository/_lstnet.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
5,944
29.025253
115
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/repository/_util.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
2,063
25.126582
75
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/repository/datasets.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
5,882
32.617143
105
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/repository/_artificial.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
1,627
32.22449
88
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/dataset/repository/__init__.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
626
43.785714
75
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/transform/split.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
20,103
36.64794
106
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/transform/field.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
3,366
27.294118
79
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/transform/sampler.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
6,374
30.25
91
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/transform/transform.py
from abc import ABC, abstractmethod from functools import reduce from typing import Callable, Iterator, Iterable, List from pts.core.component import validated from pts.dataset import DataEntry MAX_IDLE_TRANSFORMS = 100 class Transformation(ABC): @abstractmethod def __call__( self, data_it: Iterable...
4,564
30.923077
91
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/transform/dataset.py
from typing import Iterator, List from pts.dataset import DataEntry, Dataset from .transform import Chain, Transformation class TransformedDataset(Dataset): """ A dataset that corresponds to applying a list of transformations to each element in the base_dataset. This only supports SimpleTransformatio...
918
26.029412
76
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/transform/convert.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
22,563
30.602241
86
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/transform/__init__.py
from .convert import ( AsNumpyArray, ExpandDimArray, VstackFeatures, ConcatFeatures, SwapAxes, ListFeatures, TargetDimIndicator, SampleTargetDim, CDFtoGaussianTransform, cdf_to_gaussian_forward_transform, ) from .dataset import TransformedDataset from .feature import ( target...
1,130
19.944444
39
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/transform/feature.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
8,489
31.906977
85
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/model/quantile.py
import re from typing import NamedTuple, Union class Quantile(NamedTuple): value: float name: str @property def loss_name(self): return f"QuantileLoss[{self.name}]" @property def weighted_loss_name(self): return f"wQuantileLoss[{self.name}]" @property def coverage_na...
2,496
28.376471
84
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/model/predictor.py
import json from abc import ABC, abstractmethod from pathlib import Path from pydoc import locate from typing import Iterator, Callable, Optional import numpy as np import torch import torch.nn as nn import pts from pts.core.serde import dump_json, fqname_for, load_json from pts.dataset import Dataset, DataEntry, Inf...
6,040
33.129944
81
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/model/forecast_generator.py
from abc import ABC, abstractmethod from typing import Any, Callable, Iterator, List, Optional import numpy as np import torch import torch.nn as nn from pts.core.component import validated from pts.dataset import InferenceDataLoader, DataEntry, FieldName from pts.modules import DistributionOutput from .forecast impo...
6,330
33.785714
125
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/model/utils.py
import inspect from typing import Optional import torch import torch.nn as nn def get_module_forward_input_names(module: nn.Module): params = inspect.signature(module.forward).parameters return list(params) def copy_parameters(net_source: nn.Module, net_dest: nn.Module) -> None: net_dest.load_state_dic...
1,032
26.918919
74
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/model/forecast.py
from abc import ABC, abstractmethod from enum import Enum from typing import Dict, List, Optional, Set, Union, Callable import numpy as np import pandas as pd import torch from pydantic import BaseModel, Field from torch.distributions import Distribution from .quantile import Quantile class OutputType(str, Enum): ...
16,436
29.495362
99
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/model/__init__.py
from .estimator import Estimator, PTSEstimator from .forecast import Forecast, SampleForecast, QuantileForecast, DistributionForecast from .predictor import Predictor, PTSPredictor from .quantile import Quantile from .utils import get_module_forward_input_names, copy_parameters, weighted_average
297
48.666667
86
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/model/estimator.py
from abc import ABC, abstractmethod from typing import NamedTuple, Optional import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader from pts.core.component import validated from pts import Trainer from pts.dataset import Dataset, TransformedIterableDataset, TransformedListDataset...
4,526
26.436364
83
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/model/deepar/deepar_network.py
from typing import List, Optional, Tuple, Union import numpy as np import torch import torch.nn as nn from torch.distributions import Distribution from pts.core.component import validated from pts.model import weighted_average from pts.modules import DistributionOutput, MeanScaler, NOPScaler, FeatureEmbedder def pr...
28,509
41.936747
179
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/model/deepar/deepar_estimator.py
from typing import List, Optional import numpy as np import torch import torch.nn as nn from pts.core.component import validated from pts import Trainer from pts.dataset import FieldName from pts.feature import ( TimeFeature, get_lags_for_frequency, time_features_from_frequency_str, ) from pts.model impor...
9,762
38.686992
144
py
M5_Accuracy_3rd
M5_Accuracy_3rd-master/pts/model/deepar/__init__.py
from .deepar_estimator import DeepAREstimator from .deepar_network import DeepARNetwork, RolledDeepARTrainingNetwork
117
38.333333
70
py
NM-sparsity
NM-sparsity-main/devkit/__init__.py
0
0
0
py
NM-sparsity
NM-sparsity-main/devkit/core/lr_scheduler.py
"""Learning Rate Schedulers""" from __future__ import division from math import pi, cos class LRScheduler(object): r"""Learning Rate Scheduler For mode='step', we multiply lr with `decay_factor` at each epoch in `step`. For mode='poly':: lr = targetlr + (baselr - targetlr) * (1 - iter / maxiter) ^ ...
3,992
41.478723
102
py
NM-sparsity
NM-sparsity-main/devkit/core/dist_utils.py
import os import torch import torch.multiprocessing as mp import torch.distributed as dist __all__ = [ 'init_dist', 'broadcast_params','average_gradients'] def init_dist(backend='nccl', master_ip='127.0.0.1', port=29500): if mp.get_start_method(allow_none=True) is None: mp....
945
28.5625
60
py
NM-sparsity
NM-sparsity-main/devkit/core/utils.py
import torch import os import shutil def save_checkpoint(model_dir, state, is_best): epoch = state['epoch'] path = os.path.join(model_dir, 'model.pth-' + str(epoch)) torch.save(state, path) checkpoint_file = os.path.join(model_dir, 'checkpoint') checkpoint = open(checkpoint_file, 'w+') checkpo...
2,861
40.478261
102
py
NM-sparsity
NM-sparsity-main/devkit/core/__init__.py
from .lr_scheduler import * from .dist_utils import * from .utils import *
75
18
27
py
NM-sparsity
NM-sparsity-main/devkit/dataset/imagenet_dataset.py
from torch.utils.data import Dataset from PIL import Image import torch def pil_loader(filename): with Image.open(filename) as img: img = img.convert('RGB') return img class ImagenetDataset(Dataset): def __init__(self, root_dir, meta_file, transform=None): self.root_dir = root_dir ...
1,758
29.327586
71
py
NM-sparsity
NM-sparsity-main/devkit/dataset/__init__.py
0
0
0
py
NM-sparsity
NM-sparsity-main/devkit/sparse_ops/sparse_ops.py
import torch from torch import autograd, nn import torch.nn.functional as F from itertools import repeat from torch._six import container_abcs class Sparse(autograd.Function): """" Prune the unimprotant weight for the forwards phase but pass the gradient to dense weight using SR-STE in the backwards phase""" ...
3,245
26.982759
159
py
NM-sparsity
NM-sparsity-main/devkit/sparse_ops/__init__.py
from .syncbn_layer import SyncBatchNorm2d from .sparse_ops import SparseConv
77
25
41
py
NM-sparsity
NM-sparsity-main/devkit/sparse_ops/syncbn_layer.py
import torch from torch.autograd import Function from torch.nn.parameter import Parameter from torch.nn.modules.module import Module import torch.distributed as dist import torch.nn as nn class SyncBNFunc(Function): @staticmethod def forward(ctx, in_data, scale_data, shift_data, running_mean, running_var, eps...
3,824
37.25
159
py
NM-sparsity
NM-sparsity-main/classification/train_imagenet.py
from __future__ import division import argparse import os import time import torch.distributed as dist import torch import torch.nn as nn import torch.backends.cudnn as cudnn from torch.utils.data.distributed import DistributedSampler import torchvision.transforms as transforms from torch.utils.data import DataLoader i...
10,642
33.003195
131
py
NM-sparsity
NM-sparsity-main/classification/models/resnet.py
import torch.nn as nn import math import sys import os.path as osp sys.path.append(osp.abspath(osp.join(__file__, '../../../'))) #from devkit.ops import SyncBatchNorm2d import torch import torch.nn.functional as F from torch import autograd from torch.nn.modules.utils import _pair as pair from torch.nn import init from...
5,446
28.603261
95
py
NM-sparsity
NM-sparsity-main/classification/models/__init__.py
from .resnet import *
22
10.5
21
py
NM-sparsity
NM-sparsity-main/RAFT/evaluate.py
import sys sys.path.append('core') from PIL import Image import argparse import os import time import numpy as np import torch import torch.nn.functional as F import matplotlib.pyplot as plt import datasets from utils import flow_viz from utils import frame_utils from raft import RAFT from utils.utils import InputPa...
6,618
32.429293
112
py
NM-sparsity
NM-sparsity-main/RAFT/demo.py
import sys sys.path.append('core') import argparse import os import cv2 import glob import numpy as np import torch from PIL import Image from raft import RAFT from utils import flow_viz from utils.utils import InputPadder DEVICE = 'cuda' def load_image(imfile): img = np.array(Image.open(imfile)).astype(np.ui...
2,073
26.289474
112
py
NM-sparsity
NM-sparsity-main/RAFT/train.py
from __future__ import print_function, division import sys sys.path.append('core') import argparse import os import cv2 import time import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.utils.data import DataLoader...
8,244
31.333333
103
py
NM-sparsity
NM-sparsity-main/RAFT/core/lr_scheduler.py
import types import math from torch._six import inf from functools import wraps import warnings import weakref from collections import Counter from bisect import bisect_right #from torch.optim.optimizer import Optimizer class _LRScheduler(object): def __init__(self, optimizer, last_epoch=-1, verbose=False): ...
19,353
43.800926
128
py
NM-sparsity
NM-sparsity-main/RAFT/core/sparse_update.py
import torch import torch.nn as nn import torch.nn.functional as F import sys import os.path as osp sys.path.append(osp.abspath(osp.join(__file__, '../../../'))) from devkit.sparse_ops import SparseConv class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__i...
5,385
36.402778
88
py
NM-sparsity
NM-sparsity-main/RAFT/core/sparse_raft.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from sparse_update import BasicUpdateBlock, SmallUpdateBlock from sparse_extractor import BasicEncoder, SmallEncoder from corr import CorrBlock, AlternateCorrBlock from utils.utils import bilinear_sampler, coords_grid, upflow8 try: ...
4,950
33.144828
102
py
NM-sparsity
NM-sparsity-main/RAFT/core/corr.py
import torch import torch.nn.functional as F from utils.utils import bilinear_sampler, coords_grid try: import alt_cuda_corr except: # alt_cuda_corr is not compiled pass class CorrBlock: def __init__(self, fmap1, fmap2, num_levels=4, radius=4): self.num_levels = num_levels self.radius...
3,085
32.543478
74
py
NM-sparsity
NM-sparsity-main/RAFT/core/update.py
import torch import torch.nn as nn import torch.nn.functional as F class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) ...
5,227
36.342857
87
py
NM-sparsity
NM-sparsity-main/RAFT/core/extractor.py
import torch import torch.nn as nn import torch.nn.functional as F class ResidualBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(ResidualBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) s...
8,847
32.014925
93
py
NM-sparsity
NM-sparsity-main/RAFT/core/datasets.py
# Data loading based on https://github.com/NVIDIA/flownet2-pytorch import numpy as np import torch import torch.utils.data as data import torch.nn.functional as F import os import math import random from glob import glob import os.path as osp from utils import frame_utils from utils.augmentor import FlowAugmentor, S...
9,242
38.165254
111
py
NM-sparsity
NM-sparsity-main/RAFT/core/raft.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from update import BasicUpdateBlock, SmallUpdateBlock from extractor import BasicEncoder, SmallEncoder from corr import CorrBlock, AlternateCorrBlock from utils.utils import bilinear_sampler, coords_grid, upflow8 try: autocast =...
4,924
32.965517
102
py
NM-sparsity
NM-sparsity-main/RAFT/core/__init__.py
0
0
0
py
NM-sparsity
NM-sparsity-main/RAFT/core/sparse_extractor.py
import torch import torch.nn as nn import torch.nn.functional as F import sys import os.path as osp sys.path.append(osp.abspath(osp.join(__file__, '../../../'))) from devkit.sparse_ops import SparseConv class ResidualBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): supe...
8,997
31.959707
94
py
NM-sparsity
NM-sparsity-main/RAFT/core/utils/utils.py
import torch import torch.nn.functional as F import numpy as np from scipy import interpolate class InputPadder: """ Pads images such that dimensions are divisible by 8 """ def __init__(self, dims, mode='sintel'): self.ht, self.wd = dims[-2:] pad_ht = (((self.ht // 8) + 1) * 8 - self.ht) % 8 ...
2,489
29
93
py
NM-sparsity
NM-sparsity-main/RAFT/core/utils/augmentor.py
import numpy as np import random import math from PIL import Image import cv2 cv2.setNumThreads(0) cv2.ocl.setUseOpenCL(False) import torch from torchvision.transforms import ColorJitter import torch.nn.functional as F class FlowAugmentor: def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=Tru...
9,108
35.878543
97
py
NM-sparsity
NM-sparsity-main/RAFT/core/utils/__init__.py
0
0
0
py
NM-sparsity
NM-sparsity-main/RAFT/core/utils/flow_viz.py
# Flow visualization code used from https://github.com/tomrunia/OpticalFlow_Visualization # MIT License # # Copyright (c) 2018 Tom Runia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software wi...
4,318
31.719697
90
py
NM-sparsity
NM-sparsity-main/RAFT/core/utils/frame_utils.py
import numpy as np from PIL import Image from os.path import * import re import cv2 cv2.setNumThreads(0) cv2.ocl.setUseOpenCL(False) TAG_CHAR = np.array([202021.25], np.float32) def readFlow(fn): """ Read .flo file in Middlebury format""" # Code adapted from: # http://stackoverflow.com/questions/28013200...
4,024
28.379562
109
py
NM-sparsity
NM-sparsity-main/RAFT/alt_cuda_corr/setup.py
from setuptools import setup from torch.utils.cpp_extension import BuildExtension, CUDAExtension setup( name='correlation', ext_modules=[ CUDAExtension('alt_cuda_corr', sources=['correlation.cpp', 'correlation_kernel.cu'], extra_compile_args={'cxx': [], 'nvcc': ['-O3']}), ]...
381
22.875
67
py
partitioning-with-cliffords
partitioning-with-cliffords-main/code/my_mpo.py
import numpy as np import tensornetwork as tn from tensornetwork.backends.abstract_backend import AbstractBackend tn.set_default_backend("pytorch") #tn.set_default_backend("numpy") from typing import List, Union, Text, Optional, Any, Type Tensor = Any import tequila as tq import torch EPS = 1e-12 class SubOperator...
14,354
36.480418
99
py
partitioning-with-cliffords
partitioning-with-cliffords-main/code/do_annealing.py
import tequila as tq import numpy as np import pickle from pathos.multiprocessing import ProcessingPool as Pool from parallel_annealing import * #from dummy_par import * from mutation_options import * from single_thread_annealing import * def find_best_instructions(instructions_dict): """ This function finds...
13,258
46.185053
187
py
partitioning-with-cliffords
partitioning-with-cliffords-main/code/scipy_optimizer.py
import numpy, copy, scipy, typing, numbers from tequila import BitString, BitNumbering, BitStringLSB from tequila.utils.keymap import KeyMapRegisterToSubregister from tequila.circuit.compiler import change_basis from tequila.utils import to_float import tequila as tq from tequila.objective import Objective from tequi...
24,489
42.732143
144
py
partitioning-with-cliffords
partitioning-with-cliffords-main/code/generate_orbital_optimization_data.py
import tequila as tq import numpy def opt_mol(mol, U, guess=None, threshold=1.e-5): delta=1.0 energy=1.0 while(delta>threshold): opt = tq.chemistry.optimize_orbitals(molecule=mol, circuit=U, initial_guess=guess, silent=True) guess = opt.mo_coeff delta = abs(opt.energy-energy) ...
1,383
29.086957
103
py
partitioning-with-cliffords
partitioning-with-cliffords-main/code/energy_optimization.py
import tequila as tq import numpy as np from tequila.objective.objective import Variable import openfermion from hacked_openfermion_qubit_operator import ParamQubitHamiltonian from typing import Union from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian ...
12,442
42.968198
225
py
partitioning-with-cliffords
partitioning-with-cliffords-main/code/parallel_annealing.py
import tequila as tq import multiprocessing import copy from time import sleep from mutation_options import * from pathos.multiprocessing import ProcessingPool as Pool def evolve_population(hamiltonian, type_energy_eval, cluster_circuit, process_id, ...
6,456
38.371951
146
py
partitioning-with-cliffords
partitioning-with-cliffords-main/code/single_thread_annealing.py
import tequila as tq import copy from mutation_options import * def st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, tasks): """ This function carrie...
4,005
40.298969
138
py
partitioning-with-cliffords
partitioning-with-cliffords-main/code/mutation_options.py
import argparse import numpy as np import random import copy import tequila as tq from typing import Union from collections import Counter from time import time from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from energy_optimization import minimi...
26,784
33.967363
191
py
partitioning-with-cliffords
partitioning-with-cliffords-main/code/plot_term_increase.py
import numpy as np import matplotlib.pyplot as plt # For now, this is all when varying _one_ Clifford gate only def find_envelope(in_list): upper, lower = [], [] for li in in_list: lower += [np.min(li)] upper += [np.max(li)] return upper, lower # >>>>>>>>>>>>>>>>>> BEGIN DATA >>>>...
29,307
286.333333
4,705
py
partitioning-with-cliffords
partitioning-with-cliffords-main/code/hacked_openfermion_qubit_operator.py
import tequila as tq import sympy import copy #from param_hamiltonian import get_geometry, generate_ucc_ansatz from hacked_openfermion_symbolic_operator import SymbolicOperator # Define products of all Pauli operators for symbolic multiplication. _PAULI_OPERATOR_PRODUCTS = { ('I', 'I'): (1., 'I'), ('I', 'X')...
9,918
29.614198
85
py