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 |
|---|---|---|---|---|---|---|
lightning | lightning-master/tests/tests_fabric/plugins/environments/test_kubeflow.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 3,062 | 28.451923 | 109 | py |
lightning | lightning-master/tests/tests_fabric/utilities/test_data.py | import contextlib
import random
from unittest.mock import Mock
import numpy as np
import pytest
import torch
from torch import Tensor
from torch.utils.data import BatchSampler, DataLoader, RandomSampler, SequentialSampler
from lightning.fabric.utilities.data import (
_dataloader_init_kwargs_resolve_sampler,
_... | 20,108 | 35.628415 | 120 | py |
lightning | lightning-master/tests/tests_fabric/utilities/test_optimizer.py | import collections
import dataclasses
import torch
from torch import Tensor
from lightning.fabric.utilities.optimizer import _optimizer_to_device
def test_optimizer_to_device():
@dataclasses.dataclass(frozen=True)
class FooState:
bar: int
class TestOptimizer(torch.optim.SGD):
def __init... | 1,204 | 30.710526 | 69 | py |
lightning | lightning-master/tests/tests_fabric/utilities/test_device_dtype_mixin.py | import pytest
import torch
from torch import nn as nn
from lightning.fabric.utilities.device_dtype_mixin import _DeviceDtypeModuleMixin
from tests_fabric.helpers.runif import RunIf
class SubSubModule(_DeviceDtypeModuleMixin):
pass
class SubModule(nn.Module):
def __init__(self):
super().__init__()
... | 4,652 | 30.869863 | 115 | py |
lightning | lightning-master/tests/tests_fabric/utilities/test_apply_func.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 2,327 | 37.8 | 103 | py |
lightning | lightning-master/tests/tests_fabric/utilities/test_seed.py | import os
from unittest import mock
import pytest
import torch
import lightning.fabric.utilities
from lightning.fabric.utilities import seed as seed_utils
from lightning.fabric.utilities.seed import _collect_rng_states, _set_rng_states
@mock.patch.dict(os.environ, {}, clear=True)
def test_seed_stays_same_with_multi... | 3,284 | 37.647059 | 98 | py |
lightning | lightning-master/tests/tests_fabric/utilities/test_imports.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 1,912 | 30.883333 | 101 | py |
lightning | lightning-master/tests/tests_fabric/utilities/test_runif.py | import pytest
from tests_fabric.helpers.runif import RunIf
@RunIf(min_torch="99")
def test_always_skip():
exit(1)
@pytest.mark.parametrize("arg1", [0.5, 1.0, 2.0])
@RunIf(min_torch="0.0")
def test_wrapper(arg1: float):
assert arg1 > 0.0
| 250 | 15.733333 | 49 | py |
lightning | lightning-master/tests/tests_fabric/utilities/test_registry.py | import contextlib
from unittest import mock
from unittest.mock import Mock
from lightning.fabric.utilities.imports import _PYTHON_GREATER_EQUAL_3_8_0, _PYTHON_GREATER_EQUAL_3_10_0
from lightning.fabric.utilities.registry import _load_external_callbacks
class ExternalCallback:
"""A callback in another library tha... | 2,332 | 34.892308 | 109 | py |
lightning | lightning-master/tests/tests_fabric/utilities/test_logger.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 4,848 | 30.69281 | 110 | py |
lightning | lightning-master/tests/tests_fabric/utilities/test_init.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 2,117 | 33.16129 | 120 | py |
lightning | lightning-master/tests/tests_fabric/utilities/test_distributed.py | from functools import partial
import pytest
import torch
from lightning.fabric.accelerators import CPUAccelerator, CUDAAccelerator, MPSAccelerator
from lightning.fabric.plugins.environments import LightningEnvironment
from lightning.fabric.strategies import DDPStrategy
from lightning.fabric.strategies.launchers.multi... | 2,894 | 34.304878 | 119 | py |
lightning | lightning-master/tests/tests_fabric/utilities/test_spike.py | import contextlib
import sys
import pytest
import torch
from lightning.fabric import Fabric
from lightning.fabric.utilities.spike import _TORCHMETRICS_GREATER_EQUAL_1_0_0, SpikeDetection, TrainingSpikeException
def spike_detection_test(fabric, global_rank_spike, spike_value, should_raise):
loss_vals = [1 / i fo... | 6,383 | 29.692308 | 118 | py |
lightning | lightning-master/tests/tests_fabric/loggers/test_csv.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 4,431 | 35.933333 | 102 | py |
lightning | lightning-master/tests/tests_fabric/loggers/test_tensorboard.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 8,920 | 36.170833 | 115 | py |
lightning | lightning-master/tests/tests_fabric/graveyard/test_tpu.py | from importlib import import_module
import pytest
import torch
@pytest.mark.parametrize(
("import_path", "name"),
[
("lightning.fabric.strategies", "SingleTPUStrategy"),
("lightning.fabric.strategies.single_tpu", "SingleTPUStrategy"),
],
)
def test_graveyard_single_tpu(import_path, name):... | 1,390 | 33.775 | 110 | py |
lightning | lightning-master/tests/tests_fabric/accelerators/test_xla.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 1,840 | 38.170213 | 114 | py |
lightning | lightning-master/tests/tests_fabric/accelerators/test_mps.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 1,913 | 32.578947 | 109 | py |
lightning | lightning-master/tests/tests_fabric/accelerators/test_registry.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 2,423 | 31.756757 | 106 | py |
lightning | lightning-master/tests/tests_fabric/accelerators/test_cpu.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 1,565 | 32.319149 | 99 | py |
lightning | lightning-master/tests/tests_fabric/accelerators/test_cuda.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 6,094 | 36.857143 | 106 | py |
lightning | lightning-master/tests/integrations_app/public/test_multi_node.py | import os
from unittest import mock
import pytest
from lightning_utilities.core.imports import package_available
from integrations_app.public import _PATH_EXAMPLES
from lightning.app.testing.helpers import _RunIf
from lightning.app.testing.testing import application_testing, LightningTestApp
class LightningTestMult... | 1,896 | 38.520833 | 120 | py |
lightning | lightning-master/tests/tests_data/conftest.py | import pytest
import torch.distributed
@pytest.fixture(autouse=True)
def teardown_process_group():
"""Ensures that the distributed process group gets closed before the next test runs."""
yield
if torch.distributed.is_available() and torch.distributed.is_initialized():
torch.distributed.destroy_pro... | 333 | 29.363636 | 91 | py |
lightning | lightning-master/tests/tests_data/test_fileio.py | import os
from unittest import mock
import pytest
from lightning.data.fileio import is_path, is_url, open_single_file, OpenCloudFileObj, path_to_url
@pytest.mark.parametrize(
("input_str", "expected"),
[
("s3://my_bucket/a", True),
("s3:/my_bucket", False),
("my_bucket", False),
... | 3,230 | 25.483607 | 100 | py |
lightning | lightning-master/tests/tests_data/datasets/test_env.py | from functools import partial
import pytest
import torch
from torch.utils.data import get_worker_info
from lightning.data.datasets.env import _DistributedEnv, _WorkerEnv, Environment
from lightning.fabric import Fabric
@pytest.mark.parametrize(
(
"num_workers",
"current_worker_rank",
"di... | 4,187 | 34.794872 | 95 | py |
lightning | lightning-master/tests/tests_data/datasets/test_iterable.py | import math
import sys
from collections import Counter
from functools import partial
from typing import Any, Dict
import pytest
import torch
import lightning
from lightning.data.datasets.iterable import (
_Chunk,
_Stateful,
_StatefulIterableDataset,
DataLoader,
LightningIterableDataset,
)
class ... | 18,441 | 29.183306 | 120 | py |
lightning | lightning-master/tests/parity_pytorch/generate_comparison.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 2,200 | 39.018182 | 120 | py |
lightning | lightning-master/tests/parity_pytorch/test_basic_parity.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 5,295 | 36.034965 | 118 | py |
lightning | lightning-master/tests/parity_pytorch/test_sync_batchnorm_parity.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 4,395 | 37.226087 | 115 | py |
lightning | lightning-master/tests/parity_pytorch/measure.py | import gc
import time
from typing import Callable
import torch
from tqdm import tqdm
def measure_loops(cls_model, kind: str, loop: Callable, num_runs: int = 10, num_epochs: int = 10):
"""Returns an array with the last loss from each epoch for each run."""
hist_losses = []
hist_durations = []
hist_mem... | 1,147 | 30.888889 | 104 | py |
lightning | lightning-master/tests/parity_pytorch/models.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 2,349 | 36.301587 | 101 | py |
lightning | lightning-master/tests/parity_pytorch/__init__.py | import pytest
from lightning.pytorch.utilities.testing import _runif_reasons
def RunIf(**kwargs):
reasons, marker_kwargs = _runif_reasons(**kwargs)
return pytest.mark.skipif(condition=len(reasons) > 0, reason=f"Requires: [{' + '.join(reasons)}]", **marker_kwargs)
| 275 | 29.666667 | 119 | py |
lightning | lightning-master/tests/legacy/simple_classif_training.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 2,048 | 34.947368 | 118 | py |
lightning | lightning-master/docs/source-pytorch/conf.py | #
# 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 --------------------------------------------------------------
# If extensions (or ... | 15,954 | 34.455556 | 114 | py |
lightning | lightning-master/docs/source-app/conf.py | # 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 --------------------------------------------------------------
# If extensions (or mo... | 14,132 | 34.599496 | 144 | py |
lightning | lightning-master/docs/source-app/workflows/share_files_between_components/app.py | import os
import torch
import lightning as L
from lightning.app.storage import Path
class ModelTraining(L.LightningWork):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.checkpoints_path = Path("./checkpoints")
def run(self):
# make fake checkpoints
... | 1,458 | 28.77551 | 75 | py |
lightning | lightning-master/docs/source-app/examples/github_repo_runner/app.py | import io
import os
import subprocess
import sys
from copy import deepcopy
from functools import partial
from subprocess import Popen
from typing import Dict, List, Optional
from lightning import BuildConfig, CloudCompute, LightningApp, LightningFlow
from lightning.app import structures
from lightning.app.components i... | 11,140 | 35.055016 | 115 | py |
lightning | lightning-master/docs/source-app/code_samples/convert_pl_to_app/train.py | import os
import torch
import torch.nn.functional as F
from torch import nn
from torch.utils.data import DataLoader, random_split
from torchvision import transforms as T
from torchvision.datasets import MNIST
import pytorch_lightning as pl
class LitAutoEncoder(pl.LightningModule):
def __init__(self):
su... | 1,416 | 29.148936 | 91 | py |
lightning | lightning-master/docs/source-app/code_samples/quickstart/app/app_1.py | import flash
from flash.core.data.utils import download_data
from flash.image import ImageClassificationData, ImageClassifier
import lightning as L
from pytorch_lightning.callbacks import ModelCheckpoint
# Step 1: Create a training LightningWork component that gets a backbone as input
# and saves the best model and ... | 3,840 | 40.301075 | 90 | py |
lightning | lightning-master/docs/source-app/levels/basic/hello_components/xgboost.py | # app.py
# !pip install scikit-learn xgboost
import lightning as L
from sklearn import datasets
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
class XGBoostComponent(L.LightningWork):
def run(self):
iris = datasets.load_iris()
X, y = iris.data, iris.target
... | 588 | 25.772727 | 80 | py |
lightning | lightning-master/docs/source-app/levels/basic/hello_components/multi_node.py | # !pip install torch
import lightning as L
from lightning.app.components import MultiNode
class MultiNodeComponent(L.LightningWork):
def run(
self,
main_address: str,
main_port: int,
node_rank: int,
world_size: int,
):
print(f"ADD YOUR DISTRIBUTED CODE: {main_ad... | 622 | 19.766667 | 100 | py |
lightning | lightning-master/docs/source-app/levels/basic/hello_components/pl_multinode.py | # app.py
import lightning as L
from lightning.app.components import LightningTrainerMultiNode
from lightning.pytorch.demos.boring_classes import BoringModel
class LightningTrainerDistributed(L.LightningWork):
def run(self):
model = BoringModel()
trainer = L.Trainer(max_epochs=10, strategy="ddp")
... | 565 | 27.3 | 62 | py |
lightning | lightning-master/docs/source-app/levels/basic/hello_components/deploy_model.py | # !pip install torchvision
import lightning as L
from lightning.app.components.serve import PythonServer, Image, Number
import base64, io, torchvision, torch
from PIL import Image as PILImage
class PyTorchServer(PythonServer):
def setup(self):
self._model = torchvision.models.resnet18(pretrained=True)
... | 1,161 | 35.3125 | 90 | py |
lightning | lightning-master/docs/source-app/levels/basic/hello_components/xgboost_gpu.py | # app.py
# !pip install sklearn xgboost
# !conda install py-xgboost-gpu
import lightning as L
from sklearn import datasets
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
class XGBoostComponent(L.LightningWork):
def run(self):
iris = datasets.load_iris()
X, y ... | 701 | 29.521739 | 80 | py |
lightning | lightning-master/docs/source-app/levels/basic/hello_components/streamlit_demo.py | # app.py
# !pip install streamlit omegaconf scipy
# !pip install torch
import lightning as L
import torch
from io import BytesIO
from functools import partial
from scipy.io.wavfile import write
import streamlit as st
class StreamlitApp(L.app.components.ServeStreamlit):
def build_model(self):
sample_rate =... | 926 | 28.903226 | 95 | py |
lightning | lightning-master/docs/source-app/levels/basic/hello_components/pt_multinode.py | # app.py
# ! pip install torch
import lightning as L
from lightning.app.components import MultiNode
import torch
from torch.nn.parallel.distributed import DistributedDataParallel
def distributed_train(local_rank: int, main_address: str, main_port: int, num_nodes: int, node_rank: int, nprocs: int):
# 1. SET UP DIS... | 2,378 | 38 | 119 | py |
lightning | lightning-master/docs/source-app/levels/basic/hello_components/train_pytorch.py | # app.py
# ! pip install torch
import lightning as L
import torch
class PyTorchComponent(L.LightningWork):
def run(self):
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = torch.nn.Sequential(torch.nn.Linear(1, 1),
torch.nn.ReLU(),
... | 923 | 30.862069 | 77 | py |
lightning | lightning-master/docs/source-fabric/conf.py | # 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 --------------------------------------------------------------
# If extensions (or mo... | 13,584 | 34.377604 | 114 | py |
lightning | lightning-master/requirements/collect_env_details.py | # Copyright The Lightning AI team.
#
# 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 or agreed to in wri... | 2,759 | 30.363636 | 109 | py |
flynn | flynn-main/utils/evaluations.py | import logging
import os
import sys
import warnings
import numpy as np
from openml.datasets import list_datasets, get_dataset
from sklearn.base import clone
from sklearn.datasets import load_digits
from sklearn.metrics import balanced_accuracy_score, f1_score
from sklearn.model_selection import train_test_split
from ... | 6,182 | 34.331429 | 80 | py |
flynn | flynn-main/utils/get_data.py | import numpy as np
from sklearn.datasets import load_digits
from tensorflow.keras.datasets import mnist, cifar10, fashion_mnist, cifar100
def print_stats(X, y):
print('X:', X.shape)
print('y:', y.shape)
print('Labels:', np.unique(y).tolist())
def get_digits():
X, y = load_digits(return_X_y=True)
... | 1,918 | 23.922078 | 77 | py |
pyMeta | pyMeta-master/example_metatrain.py | # NOTE: the code is slightly different when RL environments are used as tasks, as there is no more difference between
# train and test datasets, and because the agents need to interact with the environment directly.
from pyMeta.tasks.dataset_from_files_tasks import create_omniglot_from_files_task_distribution
from pyM... | 16,208 | 52.672185 | 218 | py |
pyMeta | pyMeta-master/evaluate_model.py | from pyMeta.tasks.dataset_from_files_tasks import create_omniglot_from_files_task_distribution
from pyMeta.tasks.omniglot_tasks import create_omniglot_allcharacters_task_distribution
from pyMeta.tasks.cifar100_tasks import create_cifar100_task_distribution
from pyMeta.tasks.miniimagenet_tasks import create_miniimagenet... | 12,148 | 51.141631 | 218 | py |
pyMeta | pyMeta-master/pyMeta/networks.py | """
Pre-defined network models.
"""
import tensorflow as tf
from tensorflow.keras.layers import Conv2D, MaxPool2D, BatchNormalization, Flatten, Dense, Activation, \
GlobalAveragePooling2D
"""
# Old, working (before multiheaded options
def make_omniglot_cnn_model(num_output_classes... | 5,064 | 34.669014 | 109 | py |
pyMeta | pyMeta-master/pyMeta/core/meta_learner.py | """
Base interface for meta-learners based on gradients.
The interface is just a tentative suggestion, as different algorithms may have very different needs.
"""
import tensorflow as tf
from pyMeta.core.task import Task
class GradBasedMetaLearner:
"""
In general, meta-learners objects should be created bef... | 2,091 | 31.6875 | 114 | py |
pyMeta | pyMeta-master/pyMeta/contrib_tasks/permuted_mnist_tasks.py | """
Utility functions to create permuted-mnist Tasks, sampling a new permutation on each task reset.
The created tasks will be derived from ClassificationTask, and can be aggregated in a TaskDistribution object.
"""
import numpy as np
import tensorflow as tf
import pickle
from pyMeta.core.task import ClassificationT... | 4,070 | 38.911765 | 142 | py |
pyMeta | pyMeta-master/pyMeta/metalearners/reptile.py | """
Implementation of the Reptile algorithm for meta-learning
Nichol, Achiam and Schulman, (2018) - https://arxiv.org/abs/1803.02999
The meta-gradient is computed as g = (init_theta - avg_final_theta)
"""
import numpy as np
import tensorflow as tf
from pyMeta.core.meta_learner import GradBasedMetaLearner
class Rept... | 4,141 | 40.42 | 114 | py |
pyMeta | pyMeta-master/pyMeta/metalearners/fomaml.py | """
Implementation of the First-Order MAML (FOMAML) algorithm for meta-learning.
Finn, Abbeel and Levine, (2017) - https://arxiv.org/abs/1703.03400
The meta-gradient is computed as g = \frac{\partial}{\partial \theta} L_{test}(\theta),
evaluated at \theta=\theta_{final} (i.e., gradient wrt to the final parameters afte... | 4,919 | 40 | 114 | py |
pyMeta | pyMeta-master/pyMeta/metalearners/implicit_maml.py | """
Implementation of the iMAML (implicit-MAML) algorithm for meta-learning.
Rajeswaran*, Finn*, Kakade, and Levine (2019) - https://arxiv.org/pdf/1909.04630
WARNING: this code is super ugly and hacky, and can be simplified greatly.
WARNING2: l-BFGS was preferred to CG (contrary to the original iMAML paper) because (1... | 11,975 | 38.137255 | 150 | py |
pyMeta | pyMeta-master/pyMeta/metalearners/seq_fomaml.py | """
Implementation of the First-Order MAML (FOMAML) algorithm for meta-learning.
For details, see https://arxiv.org/abs/1909.04170 .
"""
import numpy as np
import tensorflow as tf
from pyMeta.core.task import TaskAsSequenceOfTasks
from pyMeta.metalearners.fomaml import FOMAMLMetaLearner
class SeqFOMAMLMetaLearner(F... | 5,613 | 46.176471 | 117 | py |
pyMeta | pyMeta-master/pyMeta/tasks/cifar100_tasks.py | """
Utility functions to create permuted-mnist Tasks, sampling a new permutation on each task reset.
The created tasks will be derived from ClassificationTask, and can be aggregated in a TaskDistribution object.
"""
import numpy as np
import tensorflow as tf
import pickle
from pyMeta.core.task import ClassificationT... | 5,678 | 44.432 | 116 | py |
COOL-MC | COOL-MC-main/common/preprocessors/single_agent_deepfool_attack.py | """
This script makes use of code from the following GitHub repository: https://github.com/aminul-huq/DeepFool by aminul-huq in the preprocess method.
The code has been modified to fit the specific needs of this script.
Thank you aminul-huq for making this code available and open-source.
"""
from common.preprocessors.p... | 3,600 | 34.653465 | 146 | py |
COOL-MC | COOL-MC-main/common/preprocessors/single_agent_ffgsm.py | from common.preprocessors.preprocessor import Preprocessor
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import torch
import os
class FFGSM(Preprocessor):
def __init__(self, state_mapper, attack_config_str: str, task) -> None:
super... | 1,878 | 40.755556 | 120 | py |
COOL-MC | COOL-MC-main/common/preprocessors/single_agent_fgsm.py | from common.preprocessors.preprocessor import Preprocessor
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import torch
import os
class FGSM(Preprocessor):
def __init__(self, state_mapper, attack_config_str: str, task) -> None:
super(... | 1,631 | 37.857143 | 120 | py |
COOL-MC | COOL-MC-main/common/utilities/training.py | from common.utilities.project import Project
import sys
from common.safe_gym.safe_gym import SafeGym
from common.utilities.helper import *
import gym
import random
import math
import numpy as np
import torch
from collections import deque
import gc
def train(project, env, prop_type=''):
all_episode_rewards = dequ... | 5,546 | 55.602041 | 415 | py |
COOL-MC | COOL-MC-main/common/utilities/helper.py | """This module provides helper functions for COOL-MC."""
import argparse
import sys
import random
from typing import Any, Dict
import numpy as np
import torch
DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
SAFE_TRAINING_TASK = "safe_training"
RL_MODEL_CHECKING_TASK = "rl_model_checking"
DEFAUL... | 7,238 | 45.10828 | 171 | py |
COOL-MC | COOL-MC-main/common/rl_agents/reinforce_agent.py | import gym
import numpy as np
from collections import deque
import matplotlib.pyplot as plt
import mlflow
import os
import shutil
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical
from common.rl_agents.agent import Agent
from commo... | 3,400 | 28.068376 | 124 | py |
COOL-MC | COOL-MC-main/common/rl_agents/turnbased_n_agents.py | import mlflow
import os
import shutil
from typing import List
import torch as T
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from collections import OrderedDict
from collections import deque
import math
import torch
import numpy as np
from common.rl_agents.agent import Agent
from co... | 4,312 | 32.434109 | 535 | py |
COOL-MC | COOL-MC-main/common/rl_agents/cooperative_poagents_wrapper.py | import mlflow
import os
import shutil
from typing import List
import torch as T
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from common.rl_agents.agent import Agent
from collections import OrderedDict
import torch
import numpy as np
from common.rl_agents.dqn_agent import DQNAgent
f... | 8,449 | 37.584475 | 531 | py |
COOL-MC | COOL-MC-main/common/rl_agents/dqn_agent.py | import mlflow
import os
import shutil
from typing import List
import torch as T
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from common.rl_agents.agent import Agent
from common.utilities.helper import *
from collections import OrderedDict
import torch
import numpy as np
class Re... | 10,182 | 36.300366 | 301 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/models/CNN.py | import torch
import torch.nn as nn
from torchvision.models import resnet
use_cuda = torch.cuda.is_available()
class ResNet(nn.Module):
"""
This is a placeholder till the features are stored. Also, this exists to get final mile improvements by fine-tuning the ResNet.
"""
def __init__(self):
sup... | 1,254 | 28.186047 | 131 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/models/Ensemble.py | import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from models.Decider import Decider
from models.Guesser import Guesser
from models.QGen import QGenSeq2Seq
from models.QGenImgCap import QGenImgCap
from models.Encoder import E... | 3,335 | 34.870968 | 126 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/models/QGenImgCap.py | import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence
from utils.wrap_var import to_var
use_cuda = torch.cuda.is_available()
#This is not used in the NAACL'19 work
class QGenImgCap(nn.Module):
"""docstring for QGenImgCap."""
def __init__(se... | 5,862 | 38.086667 | 228 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/models/Guesser.py | import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.functional import log_softmax
from utils.wrap_var import to_var
"""
Guesser
"""
use_cuda = torch.cuda.is_available()
class Guesser(nn.Module):
"""
Assumption that encoder hidden is given which is then used for dot product wit... | 3,205 | 34.230769 | 187 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/models/Encoder.py | import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from utils.wrap_var import to_var
use_cuda = torch.cuda.is_available()
class Encoder(nn.Module):
"""docstring for EncoderBasic."""
def __init__(self, **kwargs):
... | 5,210 | 42.066116 | 166 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/models/QGen.py | import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence
from utils.wrap_var import to_var
use_cuda = torch.cuda.is_available()
class QGenSeq2Seq(nn.Module):
"""
QGen hidden state is initialised by the scaled encoder output.
The input at e... | 7,276 | 33.985577 | 118 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/models/Decider.py | import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
"""
For different types of Deciders.
"""
class Decider(nn.Module):
def __init__(self, **kwargs):
super(Decider, self).__init__()
"""
Parameters
----------
**kwargs : ... | 1,306 | 24.134615 | 114 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/models/Oracle.py | import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
use_cuda = torch.cuda.is_available()
class Oracle(nn.Module):
"""docstring for Oracle"""
def __init__(self, no_words, no_words_feat, ... | 5,844 | 42.296296 | 123 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/train/Oracle/train.py | import numpy as np
import datetime
import json
import argparse
import os
import multiprocessing
from collections import OrderedDict
from tensorboardX import SummaryWriter
from time import time
import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn import DataParallel
from torch.utils.data import ... | 10,227 | 41.264463 | 162 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/train/SL/parser.py | import os
import json
import datetime
from time import time
import torch
from torch.autograd import Variable
import torch.nn as nn
from utils.config import load_config
from utils.vocab import create_vocab
use_cuda = torch.cuda.is_available()
#TODO: It will be good to have similar preprocssing as for the CL.
def pre... | 3,770 | 35.61165 | 125 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/train/SL/train_it.py | import numpy as np
import datetime
import json
# import progressbar
import argparse
import os
import multiprocessing
from time import time
from shutil import copy2
import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn import DataParallel
from torch.utils.data import DataLoader
from torch.autogra... | 14,875 | 45.633229 | 184 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/train/SL/train.py | import numpy as np
import datetime
import json
# import progressbar
import argparse
import os
import multiprocessing
from time import time
from shutil import copy2
import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn import DataParallel
from torch.utils.data import DataLoader
from torch.autogra... | 16,916 | 47.196581 | 187 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/train/CL/parser.py | import os
import json
import datetime
from time import time
import torch
from torch.autograd import Variable
import torch.nn as nn
from utils.config import load_config
from utils.vocab import create_vocab
use_cuda = torch.cuda.is_available()
def preprocess_config(args, visAttn=False):
"""Function to process the a... | 5,343 | 38.294118 | 125 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/train/CL/qgen.py | import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.functional import dropout
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
use_cuda = torch.cuda.is_available()
def qgen_fwpass(q_model, inputs, use_dataparallel):
"""Short summary.
Parameters
---... | 1,300 | 33.236842 | 132 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/train/CL/gameplay.py | import torch
import torch.nn as nn
from utils.wrap_var import to_var
from utils.gameplayutils import *
use_cuda = torch.cuda.is_available()
def gameplay_fwpass(q_model, o_model, inputs, exp_config, word2i, train= True):
"""Assumption: Takes in models and batch level input to give the guesser logits.
Paramet... | 4,821 | 40.568966 | 201 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/train/CL/train.py | import numpy as np
import datetime
import json
import argparse
import os
import multiprocessing
from time import time
from shutil import copy2
import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn import DataParallel
from torch.utils.data import DataLoader
from torch.autograd import Variable
fro... | 11,486 | 42.511364 | 230 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/train/GamePlay/inference.py | import numpy as np
import json
import argparse
import os
import multiprocessing
from time import time
from shutil import copy2
import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn import DataParallel
from torch.utils.data import DataLoader
from utils.vocab import create_vocab
from utils.eval i... | 18,167 | 51.206897 | 202 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/train/GamePlay/parser.py | import os
import json
import datetime
from time import time
import torch
from torch.autograd import Variable
import torch.nn as nn
from utils.config import load_config
from utils.vocab import create_vocab
use_cuda = torch.cuda.is_available()
def preprocess_config(args):
"""Function to process the arguments and re... | 4,373 | 37.368421 | 125 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/utils/model_loading.py | import warnings
from collections import OrderedDict
import torch
from torch.nn import DataParallel
use_cuda = torch.cuda.is_available()
def load_model(model, bin_file, use_dataparallel):
"""
Given a model instance, loads the weights from bin_file. Handles cuda & DataParallel stuff.
"""
print(bin_file... | 1,271 | 30.02439 | 95 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/utils/gameplayutils.py | import torch
from torch.autograd import Variable
from utils.wrap_var import to_var
use_cuda = torch.cuda.is_available()
def get_newq_lengths(new_questions, EOS,max_num=30):
new_question_lengths = list()
for q_idx in range(new_questions.size(0)):
if EOS not in list(new_questions[q_idx].data):
... | 3,369 | 32.7 | 121 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/utils/ExtractImgfeatures.py | import h5py
from PIL import Image
import json
import torch
import numpy as np
from time import time
from models.CNN import ResNet
from torchvision import transforms
from train.N2N.utils import to_var
from os import listdir
def extract_features(split, img_dir, model, my_cpu = False):
img_list = listdir(img_dir+sp... | 2,156 | 28.148649 | 103 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/utils/extractConvfeatures.py | import h5py
from PIL import Image
import json
import torch
import torch.nn as nn
import numpy as np
from time import time
import gzip
from torchvision.models import resnet
from torchvision import transforms
from train.N2N.utils import preprocess_config, to_var
from os import listdir
def extract_features(split, img_di... | 3,044 | 30.071429 | 104 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/utils/eval.py | import torch
from torch.autograd import Variable
import json
def calculate_accuracy(predictions, targets):
"""
:param prediction: NxC
:param targets: N
"""
if isinstance(predictions, Variable):
predictions = predictions.data
if isinstance(targets, Variable):
targets = targets.da... | 476 | 25.5 | 84 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/utils/wrap_var.py | import torch
from torch.autograd import Variable
use_cuda = torch.cuda.is_available()
def to_var(x, volatile=False):
"""Short summary.
Parameters
----------
x : type
Input tensor.
volatile : type
Flag for the variable has to be volatile or not.
Returns
-------
Variabl... | 454 | 17.2 | 56 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/utils/datasets/Oracle/OracleDataset.py | import os
import json
import h5py
import gzip
import io
import copy
import numpy as np
import torch
from nltk.tokenize import TweetTokenizer
from utils.image_utils import get_spatial_feat
from torch.utils.data import Dataset
class OracleDataset(Dataset):
def __init__(self, data_dir, data_file, split, visual_feat_... | 7,069 | 39.632184 | 141 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/utils/datasets/SL/prepro.py | import json
import torch
import collections
import os
import gzip
import io
import h5py
import numpy as np
from torch.utils.data import Dataset
from nltk.tokenize import TweetTokenizer
from utils.image_utils import get_spatial_feat
def create_data_file(data_dir, data_file, data_args, vocab_file_name, split='train'):
... | 9,749 | 43.117647 | 139 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/utils/datasets/SL/N2NDataset.py | import os
import json
import numpy as np
import h5py
from PIL import Image
from utils.datasets.SL.prepro import create_data_file
from torch.utils.data import Dataset
from torchvision import transforms
from utils.create_subset import create_subset
class N2NDataset(Dataset):
def __init__(self, split='train', **kwar... | 3,600 | 44.0125 | 211 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/utils/datasets/SL/N2NResNetDataset.py | import os
import json
import numpy as np
import h5py
from PIL import Image
from utils.datasets.SL.prepro import create_data_file
from torch.utils.data import Dataset
from torchvision import transforms
from utils.create_subset import create_subset
class N2NResNetDataset(Dataset):
def __init__(self, split='train', ... | 4,384 | 45.157895 | 211 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/utils/datasets/CL/RndObjSampDataset.py | import os
import json
import random
import numpy as np
import h5py
from PIL import Image
from utils.datasets.GamePlay.prepro import create_data_file
from torch.utils.data import Dataset
from utils.datasets.CL.prepro import create_data_file
from utils.create_subset import create_subset
class RndObjSampDataset(Dataset)... | 3,569 | 44.769231 | 211 | py |
Beyond-Task-Success-NAACL2019 | Beyond-Task-Success-NAACL2019-master/utils/datasets/CL/QGenDataset.py | import os
import json
import random
import numpy as np
import h5py
from PIL import Image
# from utils.datasets.N2N.gameplay.prepro import create_data_file
from torch.utils.data import Dataset
from utils.datasets.CL.prepro import create_data_file, create_qgen_data_file
from utils.create_subset import create_subset
cl... | 2,850 | 41.552239 | 216 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.