python_code
stringlengths
0
187k
repo_name
stringlengths
8
46
file_path
stringlengths
6
135
aristo-leaderboard-master
eqasc/code/allennlp_reasoning_explainqa/common/__init__.py
#!/usr/bin/env python3 # % cat testfiles-5/predictions.tsv | sort | python3 explainer.py # In paragraph 4, sentence 2, the participant "plants" is moved from an unknown location to sediment # In paragraph 4, sentence 3, the participant "bacteria" is moved from an unknown location to sediment # In paragraph 4, sentence...
aristo-leaderboard-master
propara/evaluator/explainer.py
aristo-leaderboard-master
propara/evaluator/__init__.py
#!/usr/bin/env python3 import argparse import json from typing import Dict from evaluation import Evaluation from process import sentences_from_sentences_file, ActionFile from scoring import QuestionScores from errors import corrupted_action_file, corrupted_sentences_file def main(answers_file: str, predictions_fil...
aristo-leaderboard-master
propara/evaluator/evaluator.py
from typing import List, NamedTuple, Callable, TypeVar, Optional from evaluation.metric import Metric from text import terms from process import ProcessSummary, Conversion, Move, Input, Output # Question types used in functions here QType = TypeVar("QType", Input, Output, Conversion, Move) class QuestionScores(Name...
aristo-leaderboard-master
propara/evaluator/scoring/question.py
from scoring.question import QuestionScores
aristo-leaderboard-master
propara/evaluator/scoring/__init__.py
import unittest from process import ProcessSummary, Conversion, Move, Input, Output from scoring import question, QuestionScores class TestScoring(unittest.TestCase): def test_compare_locations(self): self.assertEquals(question._compare_locations('', ''), 1.0) self.assertEquals(question._compare...
aristo-leaderboard-master
propara/evaluator/scoring/test_scoring.py
from typing import Dict, NamedTuple, Iterable from evaluation.metric import Metric class EvaluationAverages(NamedTuple): inputs: float outputs: float conversions: float moves: float overall: float class Evaluation: def __init__(self, scores: Dict[int, "QuestionScores"]) -> None: # type: ig...
aristo-leaderboard-master
propara/evaluator/evaluation/evaluation.py
from evaluation.metric import Metric from evaluation.evaluation import Evaluation
aristo-leaderboard-master
propara/evaluator/evaluation/__init__.py
from typing import Dict, NamedTuple class Metric(NamedTuple): precision: float recall: float def F1(self): if self.precision + self.recall == 0: return 0.0 return 2 * self.precision * self.recall / (self.precision + self.recall) def diagnostics(self) -> Dict[str, float]:...
aristo-leaderboard-master
propara/evaluator/evaluation/metric.py
from typing import List, Set from text.stemmer import PorterStemmer # Extract term sets from a phrase containing " AND " and " OR " tokens. A phrase like "foo OR bar AND fnord OR gnarf" # is turned into a list of term sets like [{"foo", "bar"}, {"fnord", "gnarf"}] to match to another phrase's term sets. def extract_...
aristo-leaderboard-master
propara/evaluator/text/terms.py
aristo-leaderboard-master
propara/evaluator/text/__init__.py
import unittest from text import terms class TestTerms(unittest.TestCase): def test_extract_termsets(self): # one term self.assertEqual(terms.extract_termsets("dew"), [{'dew'}]) # one term with a word that should not be stemmed self.assertEqual(terms.extract_termsets("raining"),...
aristo-leaderboard-master
propara/evaluator/text/test_terms.py
""" This was copied from the NLTK source: https://github.com/nltk/nltk/blob/7e06fcb2be41a7dbc23bf0b4f666aef7b915d402/nltk/stem/porter.py It was modified slightly to run outside NLTK. """ """ Porter Stemmer This is the Porter stemming algorithm. It follows the algorithm presented in Porter, M. "An algorithm for...
aristo-leaderboard-master
propara/evaluator/text/stemmer.py
from errors.errors import corrupted_action_file, corrupted_sentences_file
aristo-leaderboard-master
propara/evaluator/errors/__init__.py
import sys def corrupted_action_file(filename: str, details: str, line_num: int = None): if line_num is None: print(f"Corrupted or empty action file {filename} ({details})") else: print(f"Corrupted action file {filename} on line {line_num} ({details})") sys.exit(2) def corrupted_sentence...
aristo-leaderboard-master
propara/evaluator/errors/errors.py
# Locations NO_LOCATION = 'null' # This location is used of a participant that doesn't exist (was destroyed, or not yet created) LOCATION_UNKNOWN = 'unk' # Actions NO_ACTION = 'NONE' MOVE = 'MOVE' CREATE = 'CREATE' DESTROY = 'DESTROY'
aristo-leaderboard-master
propara/evaluator/process/constants.py
from process.process import Process, Conversion, Move, Input, Output from process.summary import ProcessSummary from process.action_file import ActionFile from process.sentence_file import sentences_from_sentences_file
aristo-leaderboard-master
propara/evaluator/process/__init__.py
from collections import defaultdict from typing import Dict, List, Tuple def sentences_from_sentences_file(sentences_filename: str) -> Dict[int, List[str]]: all_sentences = dict() # type: Dict[Tuple[int, int], str] with open(sentences_filename) as f: for line in f: process_id_str, sentenc...
aristo-leaderboard-master
propara/evaluator/process/sentence_file.py
from typing import Dict, List, NamedTuple from process.process import Conversion, Move, Input, Output class ProcessSummary(NamedTuple): process_id: int inputs: List[Input] outputs: List[Output] conversions: List[Conversion] moves: List[Move] def __repr__(self): return f"Process {self...
aristo-leaderboard-master
propara/evaluator/process/summary.py
import unittest from collections import OrderedDict from process import process, Process, Conversion, Move, Input, Output from process.constants import NO_ACTION as NO_ACT, NO_LOCATION as NO_LOC, CREATE, DESTROY, MOVE class TestProcess(unittest.TestCase): def test_qa(self): p = Process( proc...
aristo-leaderboard-master
propara/evaluator/process/test_process.py
from collections import OrderedDict, defaultdict from typing import NamedTuple, Dict, List from errors import corrupted_action_file from process.constants import LOCATION_UNKNOWN, NO_LOCATION, NO_ACTION, CREATE, MOVE, DESTROY from process import ProcessSummary, Process def _accumulate_action(locations, actions, num_...
aristo-leaderboard-master
propara/evaluator/process/action_file.py
from typing import List, NamedTuple, Dict from process.constants import NO_LOCATION, CREATE, DESTROY, MOVE class Input(NamedTuple): participants: str class Output(NamedTuple): participants: str class Conversion(NamedTuple): created: str destroyed: str locations: str step_id: str class M...
aristo-leaderboard-master
propara/evaluator/process/process.py
import unittest from collections import OrderedDict from process.action_file import ActionFile from process.constants import NO_ACTION as NO_ACT from process.constants import NO_LOCATION as NO_LOC, CREATE, DESTROY, MOVE class TestSummarize(unittest.TestCase): def test_load(self): # Spot-check values load...
aristo-leaderboard-master
propara/evaluator/process/test_action_file.py
import os import evaluator import unittest import tempfile import typing class TestAccuracy(unittest.TestCase): def test_EverythingCorrect(self): qa = {"Q1": "A", "Q2": "A", "Q3": "A"} p = {"Q1": ["A"], "Q2": ["A"], "Q3": ["A"]} self.assertEqual(3.0 / 3.0, evaluator.calculate_accuracy(qa...
aristo-leaderboard-master
openbookqa/evaluator/test_evaluator.py
#!/usr/bin/env python3 import csv from typing import * import logging import sys import json EXIT_STATUS_ANSWERS_MALFORMED = 1 EXIT_STATUS_PREDICTIONS_MALFORMED = 2 EXIT_STATUS_PREDICTIONS_EXTRA = 3 EXIT_STATUS_PREDICTION_MISSING = 4 def calculate_accuracy(question_answers: Dict[str, str], predictions: Dict[str, Li...
aristo-leaderboard-master
openbookqa/evaluator/evaluator.py
import os import evaluator import unittest import tempfile import typing class TestAccuracy(unittest.TestCase): def test_EverythingCorrect(self): qa = {"Q1": "A", "Q2": "A", "Q3": "A"} p = {"Q1": ["A"], "Q2": ["A"], "Q3": ["A"]} self.assertEqual(3.0 / 3.0, evaluator.calculate_accuracy(qa...
aristo-leaderboard-master
qasc/evaluator/test_evaluator.py
#!/usr/bin/env python3 import csv from typing import * import logging import sys import json EXIT_STATUS_ANSWERS_MALFORMED = 1 EXIT_STATUS_PREDICTIONS_MALFORMED = 2 EXIT_STATUS_PREDICTIONS_EXTRA = 3 EXIT_STATUS_PREDICTION_MISSING = 4 def calculate_accuracy(question_answers: Dict[str, str], predictions: Dict[str, Li...
aristo-leaderboard-master
qasc/evaluator/evaluator.py
import os import evaluator import unittest import tempfile import typing class TestAccuracy(unittest.TestCase): def test_EverythingCorrect(self): qa = {"Q1": "A", "Q2": "A", "Q3": "A"} p = {"Q1": ["A"], "Q2": ["A"], "Q3": ["A"]} self.assertEqual(3.0 / 3.0, evaluator.calculate_accuracy(qa...
aristo-leaderboard-master
arc/evaluator/test_evaluator.py
#!/usr/bin/env python3 import csv from typing import * import logging import sys import json EXIT_STATUS_ANSWERS_MALFORMED = 1 EXIT_STATUS_PREDICTIONS_MALFORMED = 2 EXIT_STATUS_PREDICTIONS_EXTRA = 3 EXIT_STATUS_PREDICTION_MISSING = 4 def calculate_accuracy(question_answers: Dict[str, str], predictions: Dict[str, Li...
aristo-leaderboard-master
arc/evaluator/evaluator.py
import ast import hashlib import json import os from collections import defaultdict from typing import Tuple, Sequence, Dict, Optional, Union, Any, Set import compress_pickle import matplotlib.pyplot as plt import numpy as np import pandas import pandas as pd from filelock import FileLock from allenact.utils.misc_uti...
advisor-main
summarization_utils.py
"""Defining the PPO loss for actor critic type models.""" import abc import math from typing import Dict, Union, Optional, Tuple, cast, Callable import numpy as np import torch import torch.nn.functional as F from stable_baselines3.common.running_mean_std import RunningMeanStd from allenact.algorithms.offpolicy_sync....
advisor-main
advisor_losses.py
import os from pathlib import Path MINIGRID_EXPERT_TRAJECTORIES_DIR = os.path.abspath( os.path.join(os.path.dirname(Path(__file__)), "minigrid_data", "minigrid_demos") ) MINIGRID_ENV_NAMES_SUPPORTED = ( "CrossingS25N10", # LavaCrossing (S25, N10) "WallCrossingS25N10", # WallCrossing (S25, N10) "AskFo...
advisor-main
minigrid_constants.py
import os from pathlib import Path import matplotlib.pyplot as plt from allenact.utils.misc_utils import TABLEAU10_RGB ADVISOR_TOP_LEVEL_DIR = os.path.abspath(os.path.dirname(Path(__file__))) NICE_COLORS12_RGB = TABLEAU10_RGB + ( (31, 119, 180), (255, 127, 14), (44, 160, 44), (214, 39, 40), (148...
advisor-main
advisor_constants.py
from typing import Callable, Dict, Optional, Any, cast import gym import numpy as np import torch from gym.spaces.dict import Dict as SpaceDict from torch import nn, autograd from allenact.algorithms.onpolicy_sync.policy import ActorCriticModel from allenact.base_abstractions.distributions import CategoricalDistr fro...
advisor-main
gail_models.py
import glob import json import math import os import shutil import time from typing import Optional import torch import torch.multiprocessing as mp from allenact.algorithms.onpolicy_sync.runner import OnPolicyRunner from allenact.main import get_args, init_logging, load_config from allenact_plugins.lighthouse_plugin....
advisor-main
lighthouse_scripts/save_pairwise_imitation_data.py
import copy import glob import os import sys from collections import defaultdict from typing import Dict, Optional, Tuple, Union, Sequence import matplotlib.pyplot as plt import numpy as np import pandas as pd from statsmodels.stats.proportion import proportion_confint from advisor_constants import ADVISOR_TOP_LEVEL_...
advisor-main
lighthouse_scripts/summarize_pairwise_imitation_data.py
advisor-main
lighthouse_scripts/__init__.py
import glob import json import os import traceback import warnings from collections import defaultdict from typing import Dict, Tuple, List import matplotlib.pyplot as plt import pandas as pd from tensorflow.python.framework.errors_impl import DataLossError from tensorflow.python.summary.summary_iterator import summar...
advisor-main
lighthouse_scripts/summarize_pairwise_imitation_train_curves.py
from allenact.utils.experiment_utils import PipelineStage from projects.advisor.lighthouse_experiments.base import BaseLightHouseExperimentConfig class LightHouseBC(BaseLightHouseExperimentConfig): """Find goal in lighthouse env using imitation learning. Training with Imitation. """ def tag(self): ...
advisor-main
lighthouse_experiments/bc.py
from allenact.utils.experiment_utils import PipelineStage from projects.advisor.lighthouse_experiments.base import BaseLightHouseExperimentConfig class LightHouseBCThenPPO(BaseLightHouseExperimentConfig): """Dagger then ppo.""" def tag(self): return "LightHouseBCThenPPO" def training_pipeline(se...
advisor-main
lighthouse_experiments/bc_then_ppo.py
from allenact.utils.experiment_utils import PipelineStage, LinearDecay from projects.advisor.lighthouse_experiments.base import BaseLightHouseExperimentConfig class LightHouseDagger(BaseLightHouseExperimentConfig): """Find goal in lighthouse env using imitation learning. Training with Dagger. """ de...
advisor-main
lighthouse_experiments/dagger.py
advisor-main
lighthouse_experiments/__init__.py
from allenact.utils.experiment_utils import PipelineStage, LinearDecay from projects.advisor.lighthouse_experiments.base import BaseLightHouseExperimentConfig class LightHouseBCTeacherForcing(BaseLightHouseExperimentConfig): """Find goal in lighthouse env using imitation learning. Training with Imitation. ...
advisor-main
lighthouse_experiments/bc_teacher_forcing.py
from allenact.utils.experiment_utils import PipelineStage, LinearDecay from projects.advisor.lighthouse_experiments.base import BaseLightHouseExperimentConfig class LightHouseImitationAndPPO(BaseLightHouseExperimentConfig): """Dagger then ppo.""" def tag(self): return "LightHouseImitationAndPPO" ...
advisor-main
lighthouse_experiments/dagger_then_ppo.py
from allenact.utils.experiment_utils import PipelineStage, LinearDecay from projects.advisor.lighthouse_experiments.base import BaseLightHouseExperimentConfig class LightHouseBCTeacherForcingThenPPO(BaseLightHouseExperimentConfig): """Find goal in lighthouse env using imitation learning. Training with Imitat...
advisor-main
lighthouse_experiments/bc_teacher_forcing_then_ppo.py
from allenact.utils.experiment_utils import PipelineStage from projects.advisor.lighthouse_experiments.base import BaseLightHouseExperimentConfig class LightHousePPO(BaseLightHouseExperimentConfig): """PPO only.""" def tag(self): return "LightHousePPO" def training_pipeline(self, **kwargs): ...
advisor-main
lighthouse_experiments/ppo.py
from torch import nn from advisor_losses import AdvisorWeightedStage from allenact.base_abstractions.sensor import SensorSuite from allenact.embodiedai.models.basic_models import RNNActorCritic from allenact.utils.experiment_utils import PipelineStage from allenact_plugins.lighthouse_plugin.lighthouse_models import ( ...
advisor-main
lighthouse_experiments/advisor_ppo.py
from allenact.utils.experiment_utils import PipelineStage from projects.advisor.lighthouse_experiments.base import BaseLightHouseExperimentConfig class LightHouseA2C(BaseLightHouseExperimentConfig): """A2C only.""" def tag(self): return "LightHouseA2C" def training_pipeline(self, **kwargs): ...
advisor-main
lighthouse_experiments/a2c.py
from advisor_losses import AdvisorWeightedStage from allenact.utils.experiment_utils import PipelineStage from projects.advisor.lighthouse_experiments.advisor_ppo import LightHouseAdvisorPPO class LightHouseAdvisorA2C(LightHouseAdvisorPPO): """A2C and Imitation with adaptive reweighting.""" def tag(self): ...
advisor-main
lighthouse_experiments/advisor_a2c.py
import math from abc import ABC from typing import Dict, Any, List, Optional, Tuple, Union, NamedTuple import gym import torch import torch.nn as nn from torch import optim from torch.optim.lr_scheduler import LambdaLR from allenact.algorithms.onpolicy_sync.losses import PPO, A2C from allenact.algorithms.onpolicy_syn...
advisor-main
lighthouse_experiments/base.py
from allenact.utils.experiment_utils import PipelineStage from projects.advisor.lighthouse_experiments.base import BaseLightHouseExperimentConfig class LightHouseBCAndPPO(BaseLightHouseExperimentConfig): """PPO and Imitation jointly.""" def tag(self): return "LightHouseBCAndPPO" def training_pip...
advisor-main
lighthouse_experiments/bc_and_ppo.py
from allenact.utils.experiment_utils import PipelineStage from projects.advisor.minigrid_and_pd_experiments.base import BaseExperimentConfig class MgPdBC(BaseExperimentConfig): """Training with behavior cloning.""" def __init__(self, task_name: str, **kwargs): super().__init__(task_name=task_name, US...
advisor-main
minigrid_and_pd_experiments/bc.py
from allenact.utils.experiment_utils import PipelineStage from projects.advisor.minigrid_and_pd_experiments.base import BaseExperimentConfig class MgPdBCThenPPO(BaseExperimentConfig): """Training with behavior cloning and then PPO.""" def __init__(self, task_name: str, **kwargs): super().__init__(tas...
advisor-main
minigrid_and_pd_experiments/bc_then_ppo.py
from advisor_losses import ( AdvisorImitationStage, AdvisorWeightedStage, ) from allenact.utils.experiment_utils import PipelineStage, LinearDecay from projects.advisor.minigrid_and_pd_experiments.base import BaseExperimentConfig class MgPdBCTeacherForcingThenAdvisor(BaseExperimentConfig): """Training wit...
advisor-main
minigrid_and_pd_experiments/bc_teacher_forcing_then_advisor.py
from allenact.utils.experiment_utils import PipelineStage, OffPolicyPipelineComponent from allenact_plugins.minigrid_plugin.minigrid_offpolicy import ( MiniGridOffPolicyExpertCELoss, ) from poisoneddoors_plugin.poisoneddoors_offpolicy import ( PoisonedDoorsOffPolicyExpertCELoss, ) from projects.advisor.minigrid...
advisor-main
minigrid_and_pd_experiments/pure_offpolicy.py
from advisor_losses import AdvisorWeightedStage from allenact.utils.experiment_utils import PipelineStage from projects.advisor.minigrid_and_pd_experiments.base import BaseExperimentConfig class MgPdAdvisor(BaseExperimentConfig): """Training with adaptive reweighing.""" def __init__(self, task_name: str, **k...
advisor-main
minigrid_and_pd_experiments/advisor.py
from allenact.utils.experiment_utils import PipelineStage from projects.advisor.minigrid_and_pd_experiments.base import BaseExperimentConfig class MgPdBCThenPPO(BaseExperimentConfig): """Training with behavior cloning and then PPO.""" def __init__(self, task_name: str, **kwargs): super().__init__(tas...
advisor-main
minigrid_and_pd_experiments/bc_with_ppo.py
from allenact.utils.experiment_utils import PipelineStage, LinearDecay from projects.advisor.minigrid_and_pd_experiments.base import BaseExperimentConfig class MgPdDagger(BaseExperimentConfig): """Training with DAgger.""" def __init__(self, task_name: str, **kwargs): super().__init__(task_name=task_n...
advisor-main
minigrid_and_pd_experiments/dagger.py
advisor-main
minigrid_and_pd_experiments/__init__.py
from advisor_losses import ( AdvisorImitationStage, AdvisorWeightedStage, ) from allenact.utils.experiment_utils import PipelineStage, LinearDecay from projects.advisor.minigrid_and_pd_experiments.base import BaseExperimentConfig class MgPdDaggerThenAdvisor(BaseExperimentConfig): """Training with DAgger f...
advisor-main
minigrid_and_pd_experiments/dagger_then_advisor.py
from advisor_losses import MiniGridOffPolicyAdvisorLoss from allenact.utils.experiment_utils import PipelineStage, OffPolicyPipelineComponent from poisoneddoors_plugin.poisoneddoors_offpolicy import ( PoisonedDoorsOffPolicyAdvisorLoss, ) from projects.advisor.minigrid_and_pd_experiments.base import BaseExperimentCo...
advisor-main
minigrid_and_pd_experiments/ppo_with_offpolicy_advisor.py
from allenact.utils.experiment_utils import PipelineStage, LinearDecay from projects.advisor.minigrid_and_pd_experiments.base import BaseExperimentConfig class MgPdBCTeacherForcing(BaseExperimentConfig): """Training with behavior cloning with teacher forcing of 1.""" def __init__(self, task_name: str, **kwar...
advisor-main
minigrid_and_pd_experiments/bc_teacher_forcing.py
from allenact.utils.experiment_utils import PipelineStage, OffPolicyPipelineComponent from allenact_plugins.minigrid_plugin.minigrid_offpolicy import ( MiniGridOffPolicyExpertCELoss, ) from poisoneddoors_plugin.poisoneddoors_offpolicy import ( PoisonedDoorsOffPolicyExpertCELoss, ) from projects.advisor.minigrid...
advisor-main
minigrid_and_pd_experiments/ppo_with_offpolicy.py
from allenact.utils.experiment_utils import PipelineStage, LinearDecay from projects.advisor.minigrid_and_pd_experiments.base import BaseExperimentConfig class MgPdDaggerThenPPO(BaseExperimentConfig): """Training with DAgger and then PPO.""" def __init__(self, task_name: str, **kwargs): super().__ini...
advisor-main
minigrid_and_pd_experiments/dagger_then_ppo.py
from allenact.utils.experiment_utils import PipelineStage, LinearDecay from projects.advisor.minigrid_and_pd_experiments.base import BaseExperimentConfig class MgPdBCThenPPO(BaseExperimentConfig): """Training with behavior cloning (teacher forcing of 1) and then PPO.""" def __init__(self, task_name: str, **k...
advisor-main
minigrid_and_pd_experiments/bc_teacher_forcing_then_ppo.py
from allenact.utils.experiment_utils import PipelineStage from projects.advisor.minigrid_and_pd_experiments.base import BaseExperimentConfig class MgPdPPO(BaseExperimentConfig): """Training with PPO.""" def __init__(self, task_name: str, **kwargs): super().__init__(task_name=task_name, USE_EXPERT=Fal...
advisor-main
minigrid_and_pd_experiments/ppo.py
from typing import cast import gym from torch import nn from advisor_losses import GAILDiscriminatorLoss, GAILPPO from allenact.algorithms.onpolicy_sync.losses.ppo import PPOConfig from allenact.base_abstractions.sensor import SensorSuite from allenact.embodiedai.models.basic_models import LinearActorCritic from alle...
advisor-main
minigrid_and_pd_experiments/gail.py
import abc import math import os from typing import ( Optional, List, Any, Dict, cast, Sequence, Callable, Union, NamedTuple, ) import gym import torch from gym_minigrid.minigrid import Lava, WorldObj, Wall from torch import nn, optim from torch.optim.lr_scheduler import LambdaLR f...
advisor-main
minigrid_and_pd_experiments/base.py
import typing from typing import Dict, Union, Tuple, Iterator, Any from typing import Optional import numpy as np import torch from gym.utils import seeding from advisor_losses import AlphaScheduler, AdvisorWeightedStage from allenact.algorithms.offpolicy_sync.losses.abstract_offpolicy_loss import ( AbstractOffPo...
advisor-main
poisoneddoors_plugin/poisoneddoors_offpolicy.py
import typing from typing import Dict, Tuple, Any, Union import gym import torch import torch.nn as nn from gym.spaces.dict import Dict as SpaceDict from allenact.base_abstractions.misc import ActorCriticOutput, DistributionType, Memory from allenact.embodiedai.models.basic_models import RNNActorCritic, LinearActorCr...
advisor-main
poisoneddoors_plugin/poisoneddoors_models.py
from typing import Optional, Any import gym import numpy as np from allenact.base_abstractions.sensor import Sensor from allenact.utils.misc_utils import prepare_locals_for_super from poisoneddoors_plugin.poisoneddoors_tasks import ( PoisonedDoorsEnvironment, PoisonedDoorsTask, PoisonedEnvStates, ) clas...
advisor-main
poisoneddoors_plugin/poisoneddoors_sensors.py
advisor-main
poisoneddoors_plugin/__init__.py
import random from enum import Enum from typing import Any, Tuple, Union, List, Optional, Dict import gym import numpy as np from gym.utils import seeding from allenact.base_abstractions.misc import RLStepResult from allenact.base_abstractions.sensor import SensorSuite, Sensor from allenact.base_abstractions.task imp...
advisor-main
poisoneddoors_plugin/poisoneddoors_tasks.py
import argparse import glob import multiprocessing as mp import os mp = mp.get_context("forkserver") from projects.advisor.summarization_utils import create_comparison_hp_plots_from_tsv def get_argument_parser(): """Creates the argument parser.""" # noinspection PyTypeChecker parser = argparse.Argument...
advisor-main
minigrid_and_pd_scripts/summarize_random_hp_search.py
import json import os import time import typing import babyai import blosc import torch import torch.multiprocessing as mp from tqdm import tqdm from allenact.main import load_config, get_argument_parser from allenact.utils.misc_utils import partition_sequence from allenact.utils.system import get_logger from allenac...
advisor-main
minigrid_and_pd_scripts/save_expert_demos.py
advisor-main
minigrid_and_pd_scripts/__init__.py
import json import os from typing import cast, Dict import tqdm from advisor_constants import ADVISOR_TOP_LEVEL_DIR from allenact.main import get_argument_parser, load_config from allenact.utils.experiment_utils import set_seed, ScalarMeanTracker from minigrid_and_pd_experiments.base import BaseExperimentConfig TASK...
advisor-main
minigrid_and_pd_scripts/compute_random_performance_for_task.py
import itertools import json import math import os import queue import time import warnings from typing import Dict, List, Optional, Any import canonicaljson import torch import torch.multiprocessing as mp from allenact.algorithms.onpolicy_sync.runner import OnPolicyRunner from allenact.main import init_logging, load...
advisor-main
minigrid_and_pd_scripts/random_hp_search.py
from allenact_plugins.babyai_plugin.scripts.truncate_expert_demos import ( make_small_demos, ) from projects.advisor.minigrid_constants import MINIGRID_EXPERT_TRAJECTORIES_DIR if __name__ == "__main__": make_small_demos(MINIGRID_EXPERT_TRAJECTORIES_DIR)
advisor-main
minigrid_and_pd_scripts/make_small_demos.py
import abc import torch import torch.optim as optim from torch.optim.lr_scheduler import LambdaLR from advisor_losses import AdvisorWeightedStage from allenact.algorithms.onpolicy_sync.losses import PPO from allenact.algorithms.onpolicy_sync.losses.ppo import PPOConfig from allenact.utils.experiment_utils import ( ...
advisor-main
objectnav_experiments/objectnav_mixin_advisor.py
advisor-main
objectnav_experiments/__init__.py
from abc import ABC import torch import torch.optim as optim from torch.optim.lr_scheduler import LambdaLR from allenact.algorithms.onpolicy_sync.losses import PPO from allenact.algorithms.onpolicy_sync.losses.imitation import Imitation from allenact.algorithms.onpolicy_sync.losses.ppo import PPOConfig from allenact....
advisor-main
objectnav_experiments/objectnav_mixin_bcwithppo.py
from abc import ABC from typing import Sequence, Union import gym import torch.nn as nn from torchvision import models from allenact.base_abstractions.preprocessor import Preprocessor from allenact.embodiedai.preprocessors.resnet import ResNetPreprocessor from allenact.embodiedai.sensors.vision_sensors import RGBSens...
advisor-main
objectnav_experiments/objectnav_mixin_resnetgru_with_aux_head.py
advisor-main
objectnav_experiments/robothor/__init__.py
from typing import Optional from allenact.base_abstractions.sensor import ExpertActionSensor from allenact_plugins.ithor_plugin.ithor_sensors import ( RGBSensorThor, GoalObjectTypeThorSensor, ) from allenact_plugins.robothor_plugin.robothor_tasks import ObjectNavTask from objectnav_experiments.objectnav_mixin_...
advisor-main
objectnav_experiments/robothor/objectnav_robothor_rgb_resnetgru_advisor.py
from allenact.base_abstractions.sensor import ExpertActionSensor from allenact_plugins.ithor_plugin.ithor_sensors import ( RGBSensorThor, GoalObjectTypeThorSensor, ) from allenact_plugins.robothor_plugin.robothor_tasks import ObjectNavTask from objectnav_experiments.objectnav_mixin_bcwithppo import ( Object...
advisor-main
objectnav_experiments/robothor/objectnav_robothor_rgb_resnetgru_bcwithppo.py
from setuptools import setup, find_packages setup(name='comet', version='1.0', description='Codebase for releasing comet model code', # url='http://github.com/storborg/funniest', author='Antoine Bosselut', author_email='antoineb@allenai.org', license='MIT', packages=find_packa...
comet-public-master
setup.py
comet-public-master
comet/__init__.py
import json import copy import torch import numpy as np import contextlib from distutils.dir_util import mkpath from tqdm import tqdm def make_new_tensor_from_list(items, device_num, dtype=torch.float32): if device_num is not None: device = torch.device("cuda:{}".format(device_num)) else: ...
comet-public-master
comet/utils.py
from comet.models.gpt import (LMModel, DEFAULT_CONFIG, load_openai_pretrained_model) import torch.nn as nn def make_model(opt, n_vocab, n_ctx, n_special, load=True, return_acts=True, return_probs=False, clf_token="<CLASS>", answer_size=None): print(n_ctx) if opt.exp == "generatio...
comet-public-master
comet/models/models.py
comet-public-master
comet/models/__init__.py
import torch def prepare_position_embeddings(opt, encoder_vocab, sequences): vocab_size = len(encoder_vocab) num_positions = sequences.size(-2) position_embeddings = torch.LongTensor( range(vocab_size, vocab_size + num_positions)).to(sequences.device) sequences = sequences.repeat(1, 1, 2) ...
comet-public-master
comet/models/utils.py
import copy import json import math import re import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.parameter import Parameter ''' Much of this code is taken from HuggingFace's OpenAI LM Implementation here: https://github.com/huggingface/pytorch-openai-transformer-lm '...
comet-public-master
comet/models/gpt.py
import comet.train.batch as batch import comet.evaluate.evaluate as base_evaluate import numpy as np def make_evaluator(opt, *args): if opt.exp == "generation": return AtomicGenerationEvaluator(opt, *args) else: return AtomicClassificationEvaluator(opt, *args) class AtomicGenerationEvaluator(...
comet-public-master
comet/evaluate/atomic_evaluate.py
import comet.data.data as data import comet.data.config as cfg import comet.evaluate.sampler as sampling def do_gen_run(opt, generator, l, split="dev", scores={}): # Generate sequences for examples in evaluation set using # current trained model if opt.eval.gs == "full": sequences, avg_scores, in...
comet-public-master
comet/evaluate/generate.py
import time import torch import comet.evaluate.generate as base_generate import comet.evaluate.sampler as sampling import comet.utils as utils import comet.data.config as cfg def make_generator(opt, *args): return ConceptNetGenerator(opt, *args) class ConceptNetGenerator(base_generate.Generator): def __ini...
comet-public-master
comet/evaluate/conceptnet_generate.py
comet-public-master
comet/evaluate/__init__.py
def update_classification_losses(losses, nums, name, bs, loss): if not isinstance(loss, float): print(type(loss)) raise nums[name] += bs losses[name] += loss * bs def update_generation_losses(losses, nums, micro, macro, bs, length, loss): # Update Losses nums[macro] += bs i...
comet-public-master
comet/evaluate/utils.py
import time import numpy as np import comet.train.batch as batch_utils import comet.utils as utils import comet.evaluate.evaluate as base_evaluate def make_evaluator(opt, *args, **kwargs): return ConceptNetGenerationEvaluator(opt, *args, **kwargs) class ConceptNetGenerationEvaluator(base_evaluate.Evaluator): ...
comet-public-master
comet/evaluate/conceptnet_evaluate.py