python_code stringlengths 0 187k | repo_name stringlengths 8 46 | file_path stringlengths 6 135 |
|---|---|---|
from typing import Optional, Any, cast
import gym
import gym_minigrid.minigrid
import numpy as np
import torch
from babyai.utils.format import InstructionsPreprocessor
from gym_minigrid.minigrid import MiniGridEnv
from allenact.base_abstractions.sensor import Sensor, prepare_locals_for_super
from allenact.base_abstra... | ask4help-main | allenact_plugins/minigrid_plugin/minigrid_sensors.py |
import abc
from typing import Callable, Dict, Optional, Tuple, cast
import gym
import numpy as np
import torch
from gym.spaces.dict import Dict as SpaceDict
import torch.nn as nn
from allenact.algorithms.onpolicy_sync.policy import (
ActorCriticModel,
Memory,
DistributionType,
ActorCriticOutput,
O... | ask4help-main | allenact_plugins/minigrid_plugin/minigrid_models.py |
ask4help-main | allenact_plugins/minigrid_plugin/configs/__init__.py | |
"""Experiment Config for MiniGrid tutorial."""
import gym
import torch.nn as nn
from allenact.base_abstractions.sensor import SensorSuite
from allenact_plugins.minigrid_plugin.minigrid_models import MiniGridSimpleConv
from allenact_plugins.minigrid_plugin.minigrid_tasks import MiniGridTask
from projects.tutorials.min... | ask4help-main | allenact_plugins/minigrid_plugin/configs/minigrid_nomemory.py |
ask4help-main | allenact_plugins/minigrid_plugin/scripts/__init__.py | |
ask4help-main | allenact_plugins/minigrid_plugin/data/__init__.py | |
"""Utility functions and classes for visualization and logging."""
import os
from datetime import datetime
import cv2
import imageio
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib
from allenact_plugins.manipulathor_plugin.manipulathor_utils import initialize_arm
from a... | ask4help-main | allenact_plugins/manipulathor_plugin/manipulathor_viz.py |
"""Task Definions for the task of ArmPointNav."""
from typing import Dict, Tuple, List, Any, Optional
import copy
import gym
import numpy as np
from allenact.base_abstractions.misc import RLStepResult
from allenact.base_abstractions.sensor import Sensor
from allenact.base_abstractions.task import Task
from allenact_p... | ask4help-main | allenact_plugins/manipulathor_plugin/manipulathor_tasks.py |
"""Task Samplers for the task of ArmPointNav."""
import json
import random
from typing import List, Dict, Optional, Any, Union
import gym
from allenact.base_abstractions.sensor import Sensor
from allenact.base_abstractions.task import Task
from allenact.base_abstractions.task import TaskSampler
from allenact.utils.exp... | ask4help-main | allenact_plugins/manipulathor_plugin/manipulathor_task_samplers.py |
ask4help-main | allenact_plugins/manipulathor_plugin/__init__.py | |
"""Constant values and hyperparameters that are used by the environment."""
import ai2thor.fifo_server
ARM_MIN_HEIGHT = 0.450998873
ARM_MAX_HEIGHT = 1.8009994
ADDITIONAL_ARM_ARGS = {
"disableRendering": True,
"returnToStart": True,
"speed": 1,
}
MOVE_AHEAD = "MoveAheadContinuous"
ROTATE_LEFT = "RotateL... | ask4help-main | allenact_plugins/manipulathor_plugin/manipulathor_constants.py |
import json
import os
from constants import ABS_PATH_OF_TOP_LEVEL_DIR
TRAIN_OBJECTS = ["Apple", "Bread", "Tomato", "Lettuce", "Pot", "Mug"]
TEST_OBJECTS = ["Potato", "SoapBottle", "Pan", "Egg", "Spatula", "Cup"]
MOVE_ARM_CONSTANT = 0.05
MOVE_ARM_HEIGHT_CONSTANT = MOVE_ARM_CONSTANT
UNWANTED_MOVE_THR = 0.01
DISTANCE_EP... | ask4help-main | allenact_plugins/manipulathor_plugin/armpointnav_constants.py |
"""Utility classes and functions for sensory inputs used by the models."""
from typing import Any, Union, Optional
import gym
import numpy as np
from allenact.base_abstractions.sensor import Sensor
from allenact.embodiedai.sensors.vision_sensors import DepthSensor, RGBSensor
from allenact.base_abstractions.task import... | ask4help-main | allenact_plugins/manipulathor_plugin/manipulathor_sensors.py |
"""Utility classes and functions for calculating the arm relative and absolute
position."""
from typing import Dict
import numpy as np
import torch
from allenact.utils.system import get_logger
from scipy.spatial.transform import Rotation as R
def state_dict_to_tensor(state: Dict):
result = []
if "position" i... | ask4help-main | allenact_plugins/manipulathor_plugin/arm_calculation_utils.py |
import ai2thor
from allenact_plugins.ithor_plugin.ithor_environment import IThorEnvironment
from allenact_plugins.manipulathor_plugin.armpointnav_constants import (
ARM_START_POSITIONS,
)
from allenact_plugins.manipulathor_plugin.manipulathor_constants import (
ADDITIONAL_ARM_ARGS,
)
def make_all_objects_unb... | ask4help-main | allenact_plugins/manipulathor_plugin/manipulathor_utils.py |
"""A wrapper for engaging with the ManipulaTHOR environment."""
import copy
import math
import warnings
from typing import Dict, Union, Any, Optional, cast
import ai2thor.server
import numpy as np
import math
from ai2thor.controller import Controller
from allenact.utils.misc_utils import prepare_locals_for_super
fr... | ask4help-main | allenact_plugins/manipulathor_plugin/manipulathor_environment.py |
from typing import Optional
import gym
import numpy as np
class GymEnvironment(gym.Wrapper):
"""gym.Wrapper with minimal bookkeeping (initial observation)."""
def __init__(self, gym_env_name: str):
super().__init__(gym.make(gym_env_name))
self._initial_observation: Optional[np.ndarray] = Non... | ask4help-main | allenact_plugins/gym_plugin/gym_environment.py |
ask4help-main | allenact_plugins/gym_plugin/__init__.py | |
from typing import Optional, Any
import gym
import numpy as np
from allenact.base_abstractions.sensor import Sensor, prepare_locals_for_super
from allenact.base_abstractions.task import Task, SubTaskType
from allenact_plugins.gym_plugin.gym_environment import GymEnvironment
class GymBox2DSensor(Sensor[gym.Env, Task... | ask4help-main | allenact_plugins/gym_plugin/gym_sensors.py |
import torch
from allenact.base_abstractions.distributions import Distr
class GaussianDistr(torch.distributions.Normal, Distr):
"""PyTorch's Normal distribution with a `mode` method."""
def mode(self) -> torch.FloatTensor:
return super().mean
| ask4help-main | allenact_plugins/gym_plugin/gym_distributions.py |
from typing import Dict, Union, Optional, Tuple, Any, Sequence, cast
import gym
import torch
import torch.nn as nn
from allenact.algorithms.onpolicy_sync.policy import (
ActorCriticModel,
DistributionType,
)
from allenact.base_abstractions.misc import ActorCriticOutput, Memory
from allenact_plugins.gym_plugin... | ask4help-main | allenact_plugins/gym_plugin/gym_models.py |
import random
from typing import Any, List, Dict, Optional, Union, Callable, Sequence, Tuple
import gym
import numpy as np
from gym.utils import seeding
from allenact.base_abstractions.misc import RLStepResult
from allenact.base_abstractions.sensor import Sensor, SensorSuite
from allenact.base_abstractions.task impor... | ask4help-main | allenact_plugins/gym_plugin/gym_tasks.py |
from typing import List, Callable, Optional, Any, cast, Dict
import gym
import numpy as np
import torch
import torch.nn as nn
from torchvision import models
import clip
from allenact.base_abstractions.preprocessor import Preprocessor
from allenact.utils.misc_utils import prepare_locals_for_super
'''
class ClipResNet... | ask4help-main | allenact_plugins/clip_plugin/clip_preprocessors.py |
"""Baseline models for use in the object navigation task.
Object navigation is currently available as a Task in AI2-THOR and
Facebook's Habitat.
"""
from typing import Tuple, Dict, Optional, cast
import gym
import torch
import torch.nn as nn
from gym.spaces.dict import Dict as SpaceDict
from allenact.algorithms.onpo... | ask4help-main | allenact_plugins/clip_plugin/objectnav_models.py |
ask4help-main | allenact_plugins/clip_plugin/__init__.py | |
ask4help-main | allenact_plugins/clip_plugin/configs/__init__.py | |
ask4help-main | allenact_plugins/clip_plugin/scripts/__init__.py | |
#!/usr/bin/python
import setuptools
setuptools.setup(
name='citeomatic',
version='0.01',
url='http://github.com/allenai/s2-research',
packages=setuptools.find_packages(),
install_requires=[
],
tests_require=[
],
zip_safe=False,
test_suite='py.test',
entry_points='',
pyro... | citeomatic-master | setup.py |
import random
import unittest
import os
import h5py
from sklearn.preprocessing import normalize
from citeomatic.models.options import ModelOptions
from citeomatic.models.text_embeddings import TextEmbeddingSum
import numpy as np
FIXTURES = os.path.join('tests', 'fixtures')
EMBEDDINGS_FILE = os.path.join(FIXTURES, 'w... | citeomatic-master | tests/test_pre_trained_embedding.py |
import re
from citeomatic.common import Document, global_tokenizer
from citeomatic import display
TEST_ABSTRACT = """
'— This paper investigates into the colorization problem which converts a grayscale image to a colorful version. This is a very difficult problem and normally requires manual adjustment to achieve art... | citeomatic-master | tests/test_display.py |
#!/usr/bin/env python
import json
import logging
import os
import random
import time
import numpy as np
from citeomatic import features
from citeomatic.common import FieldNames
from citeomatic.corpus import Corpus
def _time(op):
st = time.time()
r = op()
ed = time.time()
print(op, ed - st)
retur... | citeomatic-master | tests/test_corpus.py |
import glob
from citeomatic.grobid_parser import GrobidParser, parse_full_text
from citeomatic import file_util
def test_grobid_reed():
parser = parse_full_text(
file_util.slurp(file_util.test_file(__file__, 'reed.xml'))
)
assert parser.title == 'Optimizing Cauchy Reed-Solomon Codes for Fault-Tol... | citeomatic-master | tests/test_extract.py |
import unittest
import numpy as np
from citeomatic.corpus import Corpus
from citeomatic.features import Featurizer, DataGenerator
from citeomatic.models.layers import triplet_loss
from citeomatic.models.options import ModelOptions
from citeomatic.utils import import_from
from tests.test_corpus import build_test_corpu... | citeomatic-master | tests/test_model_build.py |
import unittest
from citeomatic.eval_metrics import precision_recall_f1_at_ks, average_results
class TestEvalMetrics(unittest.TestCase):
def test_precision_recall_f1_at_ks(self):
gold_y = ['1', '2', '3']
pred_y = ['1', '4', '3']
scores_y = [1.0, 0.1, 0.5]
k = [1, 2, 3]
resu... | citeomatic-master | tests/test_eval_metrics.py |
#!/usr/bin/env python3
import collections
import logging
from typing import List
import flask
import numpy as np
from flask import Flask, request
from citeomatic import display
from citeomatic.common import Document, FieldNames
from citeomatic.corpus import Corpus
from citeomatic.features import Featurizer
from cite... | citeomatic-master | citeomatic/service.py |
import numpy as np
def precision_recall_f1_at_ks(gold_y, predictions, scores=None, k_list=None):
def _mrr(ranked_list):
try:
idx = ranked_list.index(True)
return 1. / (idx + 1)
except ValueError:
return 0.0
if k_list is None:
k_list = [1, 5, 10]
... | citeomatic-master | citeomatic/eval_metrics.py |
#!/usr/bin/env python
"""
Luigi pipeline for Citeomatic.
This includes tasks for fetching the dataset, building a vocabulary and
training features and training/evaluating the model.
"""
import logging
import os
import zipfile
from os import path
import luigi
from citeomatic import file_util, features, training, corpu... | citeomatic-master | citeomatic/tasks.py |
import argparse
import logging
import os
import pickle
import sys
import time
import typing
from ast import literal_eval
import numpy
import pandas
import traitlets
from traitlets.config import Configurable
from citeomatic import traits, file_util
from .file_util import read_json, read_pickle, write_file, write_json,... | citeomatic-master | citeomatic/config.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: citeomatic/schema.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection... | citeomatic-master | citeomatic/schema_pb2.py |
from typing import Iterator
import arrow
import numpy as np
import tqdm
from annoy import AnnoyIndex
from citeomatic import file_util
from citeomatic.utils import batch_apply, flatten
from citeomatic.schema_pb2 import Document
from citeomatic.common import load_pickle
import keras.backend as K
class ANN(object):
... | citeomatic-master | citeomatic/neighbors.py |
import json
STRING_ENCODING = 'utf-8'
class Cache(object):
def lookup(self, namespace: str, key: str):
raise NotImplementedError("Please use subclass")
def put(self, namespace: str, key: str, json_str: str):
raise NotImplementedError("Please use subclass")
class LocalCache(Cache):
def ... | citeomatic-master | citeomatic/cache.py |
ROOT = '/net/nfs.corp/s2-research/citeomatic/data/'
DEFAULT_BASE_DIR = 'models/'
| citeomatic-master | citeomatic/__init__.py |
import errno
import io
import json
import logging
import os
import pickle
import tarfile
import typing
import tempfile
import hashlib
import subprocess
from os.path import abspath, dirname, join
from gzip import GzipFile
import arrow
ROOT = abspath(dirname(dirname(dirname(__file__))))
class S3FileNotFoundError(File... | citeomatic-master | citeomatic/file_util.py |
import collections
import logging
import mmh3
import re
import resource
import numpy as np
import pandas as pd
import six
import tqdm
from keras.preprocessing.sequence import pad_sequences
from sklearn.feature_extraction.text import CountVectorizer
from citeomatic.candidate_selectors import CandidateSelector
from cit... | citeomatic-master | citeomatic/features.py |
from citeomatic.common import Document
def document_to_bibtex(doc: Document):
"""
Return a BibTeX string for the given document.
:param doc:
:return: str:
"""
authors = doc.authors
if authors:
author_prefix = authors[0].split(' ')[-1].lower()
else:
author_prefix = ''
... | citeomatic-master | citeomatic/display.py |
import logging
import os
import keras.backend as K
import tensorflow as tf
from citeomatic import service
from citeomatic.serialization import model_from_directory
from citeomatic.features import Corpus
from citeomatic.grobid_parser import GrobidParser
from citeomatic.neighbors import ANN, EmbeddingModel
from citeomat... | citeomatic-master | citeomatic/gunicorn.py |
import importlib
import os
import pickle
from citeomatic import file_util
from citeomatic.schema_pb2 import Document as ProtoDoc
import spacy
from whoosh.fields import *
PAPER_EMBEDDING_MODEL = 'paper_embedder'
CITATION_RANKER_MODEL = 'citation_ranker'
nlp = spacy.load("en")
RESTRICTED_POS_TAGS = {'PUNCT', 'SYM', '... | citeomatic-master | citeomatic/common.py |
import functools
import sys
import importlib
from typing import TypeVar, Iterator, Callable, List
PY3 = sys.version_info[0] == 3
if PY3:
reload = importlib.reload
T = TypeVar('T')
U = TypeVar('U')
def import_from(module, name, reload_flag=False):
'''
usage example:
grid = import_from('sklearn.model_s... | citeomatic-master | citeomatic/utils.py |
import logging
from abc import ABC
from whoosh import scoring, qparser
from whoosh.filedb.filestore import FileStorage, copy_to_ram
from whoosh.index import FileIndex
from whoosh.qparser import MultifieldParser
from citeomatic.common import schema, FieldNames
from citeomatic.corpus import Corpus
from citeomatic.neigh... | citeomatic-master | citeomatic/candidate_selectors.py |
import numpy as np
from citeomatic.corpus import Corpus
from citeomatic.features import Featurizer
class Ranker:
def __init__(self, corpus: Corpus, featurizer: Featurizer, citation_ranker,
num_candidates_to_rank):
self.corpus = corpus
self.featurizer = featurizer
self.cit... | citeomatic-master | citeomatic/ranker.py |
import collections
import logging
import re
import arrow
import requests
import untangle
from citeomatic.utils import flatten
date_parser = re.compile(r'[^\d](?:19|20)\d\d[^\d]')
CURRENT_YEAR = arrow.now().year
EARLIEST_YEAR = 1970
def _all_text(doc):
child_text = [_all_text(c) for c in doc.children]
cdata_... | citeomatic-master | citeomatic/grobid_parser.py |
import typing
import traitlets
T1 = typing.TypeVar('T1')
T2 = typing.TypeVar('T2')
T3 = typing.TypeVar('T3')
T4 = typing.TypeVar('T4')
T = typing.TypeVar('T')
K = typing.TypeVar('K')
V = typing.TypeVar('V')
# Define wrappers for traitlets classes. These simply provide Python type hints
# that correspond to actual... | citeomatic-master | citeomatic/traits.py |
#!/usr/bin/env python
"""
Helpers for pickle compatibility across module renames.
"""
import json
import os
from typing import Tuple, Any
import tensorflow as tf
from citeomatic import file_util
from citeomatic.common import DatasetPaths
from citeomatic.features import Featurizer
from citeomatic.models.options import... | citeomatic-master | citeomatic/serialization.py |
import collections
import logging
import os
import resource
import h5py
import keras
import numpy as np
import tensorflow as tf
import tqdm
from keras.callbacks import ReduceLROnPlateau, TensorBoard
from keras.optimizers import TFOptimizer
from citeomatic import file_util
from citeomatic.candidate_selectors import Ca... | citeomatic-master | citeomatic/training.py |
import json
import logging
import sqlite3
import pickle
import tqdm
from citeomatic import file_util
from citeomatic.common import FieldNames, Document, DatasetPaths
from citeomatic.utils import batchify
from citeomatic.schema_pb2 import Document as ProtoDoc
def stream_papers(data_path):
for line_json in tqdm.t... | citeomatic-master | citeomatic/corpus.py |
import json
from citeomatic import file_util
from citeomatic.common import PAPER_EMBEDDING_MODEL, CITATION_RANKER_MODEL
from traitlets import Bool, HasTraits, Int, Unicode, Enum, Float
class ModelOptions(HasTraits):
# The type of candidate selector to use. Okapi BM25 (https://en.wikipedia.org/wiki/Okapi_BM25)
... | citeomatic-master | citeomatic/models/options.py |
from abc import ABC
import numpy as np
from citeomatic.models.layers import L2Normalize, ScalarMul, Sum, EmbeddingZero
from citeomatic.models.options import ModelOptions
from keras.layers import Bidirectional, Input, LSTM, Concatenate, SpatialDropout1D
from keras.layers import Conv1D, Lambda, Dense, GlobalMaxPooling1D... | citeomatic-master | citeomatic/models/text_embeddings.py |
import logging
import tensorflow as tf
from citeomatic.models.layers import Sum, custom_dot, EmbeddingZero
from citeomatic.models.options import ModelOptions
from citeomatic.models.text_embeddings import TextEmbeddingSum, _prefix, make_embedder
from keras.engine import Model
from keras.regularizers import l1, l2
from ... | citeomatic-master | citeomatic/models/citation_ranker.py |
import logging
from keras.engine import Model
from keras.layers import Add
from citeomatic.models.layers import L2Normalize, ScalarMultiply, custom_dot
from citeomatic.models.options import ModelOptions
from citeomatic.models.text_embeddings import _prefix, make_embedder
FIELDS = ['title', 'abstract']
SOURCE_NAMES =... | citeomatic-master | citeomatic/models/paper_embedder.py |
citeomatic-master | citeomatic/models/__init__.py | |
import tensorflow as tf
from keras import backend as K
from keras.engine.topology import Layer
from keras.layers import Lambda, Embedding
from keras.layers import Concatenate, Dot, Reshape, Flatten
class EmbeddingZero(Embedding):
def call(self, inputs):
if K.dtype(inputs) != 'int32':
inputs = ... | citeomatic-master | citeomatic/models/layers.py |
from collections import Counter
from citeomatic.common import DatasetPaths
from citeomatic.config import App
from citeomatic.corpus import Corpus
from citeomatic.traits import Enum
import numpy as np
class CorpusStat(App):
dataset_type = Enum(('dblp', 'pubmed', 'oc'), default_value='pubmed')
def main(self,... | citeomatic-master | citeomatic/scripts/corpus_stats.py |
import logging
from citeomatic.common import DatasetPaths
from citeomatic.config import App
from citeomatic.corpus import Corpus
class VerifyCorpus(App):
def main(self, args):
def _verify(db_filename, corpus_json):
try:
Corpus.build(db_filename=db_filename, source_json=corpus... | citeomatic-master | citeomatic/scripts/verify_corpus.py |
import json
import os
from citeomatic.config import App
from citeomatic.models.options import ModelOptions
from citeomatic.traits import Unicode, Enum
import copy
class GenerateOcConfigs(App):
dataset_type = Enum(('dblp', 'pubmed', 'oc'), default_value='pubmed')
input_config_file = Unicode(default_value=No... | citeomatic-master | citeomatic/scripts/generate_oc_configs.py |
#!/usr/bin/env python3
import atexit
import collections
import logging
import os
import random
import base.config
import numpy as np
import tqdm
from citeomatic import DEFAULT_BASE_DIR, ROOT, model_from_directory
from citeomatic.elastic import fetch_citations, fetch_level2_citations
from citeomatic.features import Cor... | citeomatic-master | citeomatic/scripts/evaluate_citeomatic_model.py |
import datetime
import logging
import os
from pprint import pprint
import numpy as np
from hyperopt import hp, fmin, tpe, Trials, STATUS_OK, STATUS_FAIL
from hyperopt.pyll.base import scope
from traitlets import Int, Unicode, Enum
from citeomatic import file_util
from citeomatic.common import PAPER_EMBEDDING_MODEL, C... | citeomatic-master | citeomatic/scripts/train.py |
import json
import pickle
from citeomatic.candidate_selectors import BM25CandidateSelector, ANNCandidateSelector, \
OracleCandidateSelector
from citeomatic.common import DatasetPaths
from citeomatic.config import App
from traitlets import Int, Unicode, Enum
from citeomatic.corpus import Corpus
from citeomatic.ne... | citeomatic-master | citeomatic/scripts/evaluate.py |
import logging
import os
import tqdm
from citeomatic import file_util
from citeomatic.common import DatasetPaths, FieldNames, global_tokenizer
from citeomatic.config import App
from citeomatic.corpus import Corpus
from citeomatic.service import document_from_dict, dict_from_document
from citeomatic.traits import Enum... | citeomatic-master | citeomatic/scripts/convert_kdd_to_citeomatic.py |
import logging
import tqdm
from citeomatic.common import DatasetPaths, FieldNames, global_tokenizer
from citeomatic.config import App
from citeomatic.corpus import Corpus
from citeomatic.traits import Unicode
import os
import json
from citeomatic import file_util
import pickle
class ConvertOpenCorpusToCiteomatic(Ap... | citeomatic-master | citeomatic/scripts/convert_open_corpus_to_citeomatic.py |
import os
import tqdm
from whoosh.index import create_in
from citeomatic import file_util
from citeomatic.common import DatasetPaths
from citeomatic.common import schema
from citeomatic.config import App
from citeomatic.traits import Enum
class CreateBM25Index(App):
#
# Caveat: It is unclear how to really s... | citeomatic-master | citeomatic/scripts/create_bm25_index.py |
"""Augment the CSV-Columns file to generate length measurement."""
# Copyright (c) 2021 The Allen Institute for Artificial Intelligence.
#
# 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
... | AMPT-main | measurement-tool-config/augmentcsv.py |
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
import argparse, json, os
"... | clevr-dataset-gen-master | image_generation/collect_scenes.py |
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
# The 2D bounding box genera... | clevr-dataset-gen-master | image_generation/render_images.py |
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
import sys, random, os
impor... | clevr-dataset-gen-master | image_generation/utils.py |
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
import json, os, math
from c... | clevr-dataset-gen-master | question_generation/question_engine.py |
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from __future__ import print... | clevr-dataset-gen-master | question_generation/generate_questions.py |
# A file which enables command line arguments to be added dynamically when using a yaml file.
# Mostly, this is just a wrapper which runs train.main() with --gpus and --data_dir argument.
import os
import yaml
import sys
def parse_as_type(n):
if type(n) is list:
return [parse_as_type(x) for x in n]
t... | dnw-master | runner.py |
""" General structure of train.py borrowed from https://github.com/JiahuiYu/slimmable_networks """
import importlib
import os
import time
import random
import sys
import torch
import torch.nn as nn
import torch.utils.data
import torch.utils.data.distributed
import torchvision.utils as vutils
import numpy as np
impor... | dnw-master | train.py |
import argparse
import os
import shutil
import time
import random
import numpy as np
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.d... | dnw-master | imagenet_sparsity_experiments/main.py |
import sys
import subprocess
import os
import socket
import time
from argparse import ArgumentParser, REMAINDER
import torch
def parse_args():
"""
Helper function parsing the command line options
@retval ArgumentParser
"""
parser = ArgumentParser(description="PyTorch distributed training launch "
... | dnw-master | imagenet_sparsity_experiments/multiproc.py |
import torch
import torch.nn as nn
import numpy as np
def mixup(alpha, num_classes, data, target):
with torch.no_grad():
bs = data.size(0)
c = np.random.beta(alpha, alpha)
perm = torch.randperm(bs).cuda()
md = c * data + (1-c) * data[perm, :]
mt = c * target + (1-c) * tar... | dnw-master | imagenet_sparsity_experiments/image_classification/mixup.py |
import os
import torch
import numpy as np
import torchvision.datasets as datasets
import torchvision.transforms as transforms
DATA_BACKEND_CHOICES = ['pytorch']
try:
from nvidia.dali.plugin.pytorch import DALIClassificationIterator
from nvidia.dali.pipeline import Pipeline
import nvidia.dali.ops as ops
... | dnw-master | imagenet_sparsity_experiments/image_classification/dataloaders.py |
from . import logger
from . import dataloaders
from . import training
from . import utils
from . import mixup
from . import resnet
from . import smoothing
| dnw-master | imagenet_sparsity_experiments/image_classification/__init__.py |
import random
import json
from collections import OrderedDict
class IterationMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.last = 0
def record(self, val, n = 1):
self.last = val
def get_val(self):
return None
def get_last(self):
r... | dnw-master | imagenet_sparsity_experiments/image_classification/logger.py |
import math
import torch
import torch.nn as nn
import numpy as np
from .sparse_util import SparseConv, TDConv
__all__ = ['ResNet', 'build_resnet', 'resnet_versions', 'resnet_configs']
# ResNetBuilder {{{
class ResNetBuilder(object):
def __init__(self, version, config):
self.config = config
self... | dnw-master | imagenet_sparsity_experiments/image_classification/resnet.py |
import os
import numpy as np
import torch
import shutil
import torch.distributed as dist
def should_backup_checkpoint(args):
def _sbc(epoch):
return args.gather_checkpoints and (epoch < 10 or epoch % 10 == 0)
return _sbc
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar', checkpoint_d... | dnw-master | imagenet_sparsity_experiments/image_classification/utils.py |
import torch
import torch.nn as nn
class LabelSmoothing(nn.Module):
"""
NLL loss with label smoothing.
"""
def __init__(self, smoothing=0.0):
"""
Constructor for the LabelSmoothing module.
:param smoothing: label smoothing factor
"""
super(LabelSmoothing, self).... | dnw-master | imagenet_sparsity_experiments/image_classification/smoothing.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import autograd
class ChooseTopEdges(autograd.Function):
""" Chooses the top edges for the forwards pass but allows gradient flow to all edges in the backwards pass"""
@staticmethod
def forward(ctx, weight, prune_rate):
... | dnw-master | imagenet_sparsity_experiments/image_classification/sparse_util.py |
import os
import time
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from . import logger as log
from . import resnet as models
from . import utils
try:
from apex.parallel import DistributedDataParallel as DDP
from apex.fp16_utils import *
from apex import amp
exc... | dnw-master | imagenet_sparsity_experiments/image_classification/training.py |
dnw-master | models/__init__.py | |
"""
MobileNet in PyTorch.
Borrowed from https://github.com/kuangliu/pytorch-cifar/blob/master/models/mobilenet.py
"""
import torch.nn as nn
import torch.nn.functional as F
from genutil.config import FLAGS
class Block(nn.Module):
"""Depthwise conv + Pointwise conv"""
def __init__(self, in_planes, out_plane... | dnw-master | models/basic/mobilenetv1cifar.py |
dnw-master | models/basic/__init__.py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import autograd
from genutil.config import FLAGS
def get_conv(inp, oup):
return nn.Conv2d(
inp, oup, kernel_size=3, stride=1, padding=1, bias=False, groups=inp
)
###########################################################... | dnw-master | models/graphs/util.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .util import get_graph, get_conv
from genutil.config import FLAGS
if getattr(FLAGS, 'use_dgl', False):
import dgl
import dgl.function as fn
from scipy.sparse import coo_matrix
class Block(nn.Module):
def __init__(self, inp, oup... | dnw-master | models/graphs/mobilenetv1like.py |
dnw-master | models/graphs/__init__.py | |
""" Tiny classifiers tested in Table 1.
The models have less than 42k parameters. At each node we perform Instance Normalization, ReLU,
and a 3 x 3 single channel convolution (order of operations may vary based on the implementation).
Each model follows downsample -> graph -> pool & fc. For pool we pool only the midd... | dnw-master | models/graphs/neuralgraph.py |
""" Borrowed from https://github.com/JiahuiYu/slimmable_networks
config utilities for yml file."""
import os
import sys
import yaml
# singletone
FLAGS = None
class LoaderMeta(type):
"""Constructor for supporting `!include`.
"""
def __new__(mcs, __name__, __bases__, __dict__):
"""Add include c... | dnw-master | genutil/config.py |
dnw-master | genutil/__init__.py | |
from genutil.config import FLAGS
def model_profiling(model):
n_macs = 0
n_params = 0
if FLAGS.skip_profiling:
return n_macs, n_params
# using n_macs for conv2d as
# (ins[1] * outs[1] *
# self.kernel_size[0] * self.kernel_size[1] *
# outs[2] * outs[3] // self.groups) * outs[0]
... | dnw-master | genutil/model_profiling.py |
import os
import torch
from torchvision import datasets, transforms
import torch.multiprocessing
torch.multiprocessing.set_sharing_strategy("file_system")
from genutil.config import FLAGS
class ImageNet:
def __init__(self):
super(ImageNet, self).__init__()
data_root = os.path.join(FLAGS.data_... | dnw-master | data/imagenet.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.