python_code
stringlengths
0
187k
repo_name
stringlengths
8
46
file_path
stringlengths
6
135
print( 'ERROR: stitch_wrapper not yet compiled. Please run `cd /path/to/tensorbox/utils && make`' )
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/stitch_wrapper.py
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: AnnoList.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 go...
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/annolist/AnnoList_pb2.py
import os import sys import string import matplotlib matplotlib.use('Agg') from pylab import * import numpy as np class MatPlotter: fontsize = 15 color = 0 colors = ["r-", "b-", "k-", "c-", "m-", "y-"] colors += [x + "-" for x in colors] colors += ["g-", "g--"] curFigure = [] legendNames =...
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/annolist/MatPlotter.py
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/annolist/__init__.py
#!/usr/bin/env python import sys import os import random import re from AnnotationLib import * from MatPlotter import * from optparse import OptionParser from copy import deepcopy from math import sqrt def main(argv): parser = OptionParser(usage="usage: %prog [options] <datafile> [...]") parser.add_option( ...
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/annolist/plotSimple.py
import os from math import sqrt import gzip import json import bz2 import numpy as np from collections import MutableSequence #import AnnoList_pb2 from . import PalLib import xml.dom.minidom xml_dom_ext_available = False try: import xml.dom.ext xml_dom_ext_available = True except ImportError: pass ###...
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/annolist/AnnotationLib.py
#import AnnoList_pb2 from . import AnnotationLib def loadPal(filename): _annolist = AnnoList_pb2.AnnoList() f = open(filename, "rb") _annolist.ParseFromString(f.read()) f.close() return _annolist def savePal(filename, _annolist): f = open(filename, "wb") f.write(_annolist.SerializeToS...
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/annolist/PalLib.py
def is_number(s): try: float(s) return True except ValueError: return False
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/annolist/ma_utils.py
#!/usr/bin/env python import os, sys from AnnotationLib import * from optparse import OptionParser import copy import math # BASED ON WIKIPEDIA VERSION # n - number of nodes # C - capacity matrix # F - flow matrix # s - source # t - sink # sumC - sum over rows of C (too speed up computation) def edmonds_karp(n, C, ...
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/annolist/doRPC.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/slim_nets/resnet_v1.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/slim_nets/inception_v1.py
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/slim_nets/__init__.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/slim_nets/resnet_utils.py
from setuptools import setup, find_packages setup( name="allennlp_beaker", version="0.0.1", description=( "An interactive AllenNLP plugin for submitting training jobs to beaker" ), long_description=open("README.md").read(), long_description_content_type="text/markdown", classifiers=...
allennlp-beaker-master
setup.py
allennlp-beaker-master
allennlp_beaker/__init__.py
from collections import deque from datetime import date import os import shutil import subprocess from tempfile import TemporaryDirectory from typing import Any, Dict, List, Iterable, Optional, Tuple import uuid from allennlp.common.file_utils import cached_path from allennlp.common.params import Params import click i...
allennlp-beaker-master
allennlp_beaker/__main__.py
allennlp-beaker-master
tests/__init__.py
def test_hello(): print("Hello!")
allennlp-beaker-master
tests/test_hello.py
from setuptools import setup, find_packages def read_requirements(filename: str): with open(filename) as requirements_file: import re def fix_url_dependencies(req: str) -> str: """Pip and setuptools disagree about how URL dependencies should be handled.""" m = re.match( ...
better-promptability-main
setup.py
_MAJOR = "0" _MINOR = "1" # On main and in a nightly release the patch should be one ahead of the last # released build. _PATCH = "0" # This is mainly for nightly builds which have the suffix ".dev$DATE". See # https://semver.org/#is-v123-a-semantic-version for the semantics. _SUFFIX = "" VERSION_SHORT = "{0}.{1}".for...
better-promptability-main
better_promptability/version.py
from tango import Step @Step.register("check_install") class CheckInstall(Step): DETERMINISTIC = True CACHEABLE = False def run(self) -> None: import torch if torch.cuda.is_available(): print("All good! CUDA is available :)") else: print("All good! No CUDA...
better-promptability-main
better_promptability/check_install.py
better-promptability-main
better_promptability/__init__.py
""" Changing T5Attention's forward to support prefix tuning, along with subclassing other classes that use T5Attention. Changes in T5Attention's forward from are marked with "# <CHANGE>" and "# </CHANGE>". It's possible that the added logic can be separated as some code that entirely preceeds the original forward, s.t....
better-promptability-main
better_promptability/models/t5_with_prefix.py
from __future__ import annotations import logging from typing import Any, Dict from allennlp.training.metrics import Metric from learn2learn.utils import clone_module from tango.common.lazy import Lazy import torch import torch.distributed as dist from tango.common.params import logger as tango_logger from tango.integ...
better-promptability-main
better_promptability/models/meta_learner.py
better-promptability-main
better_promptability/models/__init__.py
from __future__ import annotations from collections import defaultdict from typing import Any, Dict, List, Optional, Tuple, Union from allennlp.training.metrics import Metric import torch import torch.nn.functional as F from tango.common.lazy import Lazy from tango.integrations.pytorch_lightning.model import Lightnin...
better-promptability-main
better_promptability/models/model.py
from __future__ import annotations import logging from typing import Any, Callable, IO, Optional, Union, Dict import torch from tango.common.lazy import Lazy from tango.integrations.torch.optim import Optimizer from transformers import T5ForConditionalGeneration from ..data.config import Config from ..data.prompt_dat...
better-promptability-main
better_promptability/models/prefix_transformer.py
better-promptability-main
better_promptability/common/__init__.py
from contextlib import contextmanager from copy import deepcopy import logging import os import shutil import tempfile from pathlib import Path from typing import List, Dict, Any, Optional, cast, Union from tango.common.registrable import Registrable from tango.common.util import PathOrStr class BetterPromptabilityT...
better-promptability-main
better_promptability/common/testing.py
from .process_dataset import ProcessDataset
better-promptability-main
better_promptability/steps/__init__.py
import logging import os from typing import Dict from datasets import Dataset, DatasetDict from tango.step import Step from allennlp.common import cached_transformers logger = logging.getLogger(__name__) @Step.register("process_story_cloze") class ProcessStoryCloze(Step): DETERMINISTIC: bool = True CACHEAB...
better-promptability-main
better_promptability/steps/process_story_cloze.py
import logging import os from typing import Dict from datasets import Dataset, DatasetDict from tango.step import Step logger = logging.getLogger(__name__) @Step.register("process_dataset") class ProcessDataset(Step): DETERMINISTIC: bool = True CACHEABLE = False # use datasets caching. def run( ...
better-promptability-main
better_promptability/steps/process_dataset.py
from collections import defaultdict from typing import Any, Dict, List, Tuple, Set, Optional import numpy as np from tango import Format, JsonFormat, Step from tango.common import Params import torch @Step.register("aggregate_results") class AggregateResults(Step): DETERMINISTIC = True CACHEABLE = True F...
better-promptability-main
better_promptability/train/aggregate_results.py
better-promptability-main
better_promptability/train/__init__.py
import logging import os import sys from pathlib import Path from typing import Dict, List, Tuple, Optional import dill import pytorch_lightning as pl import transformers from pytorch_lightning.plugins import DDPShardedPlugin from pytorch_lightning.utilities import rank_zero_only from tango.common.lazy import Lazy fro...
better-promptability-main
better_promptability/train/train.py
from typing import Dict, List, Optional, Tuple import pytorch_lightning as pl from tango.common.lazy import Lazy from tango.integrations.pytorch_lightning import LightningTrainer from tango.format import JsonFormat from tango.step import Step from ..data.config import Config from ..data.prompt_data_module import Prom...
better-promptability-main
better_promptability/train/eval.py
from __future__ import annotations from typing import Union from transformers.optimization import Adafactor as HFAdafactor from tango.integrations.torch.optim import Optimizer @Optimizer.register("adafactor") class Adafactor(HFAdafactor): """See https://github.com/huggingface/transformers/issues/14830 Never...
better-promptability-main
better_promptability/train/optim.py
import sys import dill from tango.common.logging import initialize_logging from tango.common.util import import_extra_module from better_promptability.train.train import _train_step def main(): initialize_logging() _, kwargs_file, results_file = sys.argv with open(kwargs_file, "rb") as f: train...
better-promptability-main
better_promptability/train/train_main.py
better-promptability-main
better_promptability/modules/__init__.py
import logging import torch from transformers import ( AutoConfig, AutoModel, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeq2SeqLM, AutoModelForSequenceClassification, AutoModelForTokenClassification, AutoModelForCausalLM, ) logger = logging.getLogger(__name__...
better-promptability-main
better_promptability/modules/transformer.py
import logging import numpy as np import torch from torch import nn import torch.nn.functional as F logger = logging.getLogger(__name__) class WithPrefixEmbedding(nn.Module): """ From https://github.com/shmsw25/Channel-LM-Prompting/blob/cbbb92cc97039c73475ddf0db46896e9efeff3c1/model_util.py#L113 ""...
better-promptability-main
better_promptability/modules/with_prefix_embedding.py
from __future__ import annotations from typing import Mapping, Optional from tango.common import PathOrStr, Params from .config import Config from .t0_module import T0Module class T0Mixture: """ This class is used to initialize a collection of T0Module. """ def __init__( self, mixtu...
better-promptability-main
better_promptability/data/t0_mixture.py
from __future__ import annotations import random from typing import Any, Optional, Union from datasets import Dataset as HFDataset from torch.utils.data import Dataset from tango.common import Tqdm class MixerDataset(Dataset): """ This dataset mixes multiple other datasets into a single :class:`Dataset`. ...
better-promptability-main
better_promptability/data/mixer_dataset.py
from typing import Optional, Union from tango.common.aliases import PathOrStr from tango.common.registrable import Registrable class Config(Registrable): def __init__( self, seed: int = 42, gpus: int = 1, precision: Union[int, str] = 32, output_dir: Optional[PathOrStr] = N...
better-promptability-main
better_promptability/data/config.py
from __future__ import annotations from typing import Any, Mapping from urllib.error import HTTPError from tango.common.aliases import PathOrStr from transformers import T5Tokenizer, PreTrainedTokenizerBase from .data_utils import PAD_TYPE from .data_module import DataModule from .config import Config class PromptD...
better-promptability-main
better_promptability/data/prompt_data_module.py
from __future__ import annotations import logging import os from abc import abstractmethod, abstractproperty from collections.abc import ItemsView from typing import Any, Mapping, Optional, Union from allennlp.training.metrics import Metric import datasets from datasets import Dataset as HFDataset, DatasetDict as HFDa...
better-promptability-main
better_promptability/data/data_module.py
from __future__ import annotations import random from typing import Optional, Mapping from datasets import Dataset as HFDataset from tango.common import PathOrStr, Tqdm import torch import torch.distributed as dist from torch.utils.data.dataloader import DataLoader from transformers.trainer_pt_utils import LengthGroup...
better-promptability-main
better_promptability/data/t0_meta_learning_data_module.py
from .t0_mixture import T0Mixture from .t0_module import T0Module
better-promptability-main
better_promptability/data/__init__.py
from __future__ import annotations from typing import Any, List, Mapping, Optional from pathlib import Path import pickle from allennlp.training.metrics import Metric import numpy as np from tango.common import Params, PathOrStr import datasets from .data_module import DatasetDictType from .data_utils import md5, PAD...
better-promptability-main
better_promptability/data/t0_module.py
from __future__ import annotations from typing import Optional, Mapping, Any from tango.common import Tqdm, DatasetDict, PathOrStr from .data_utils import PAD_TYPE from .config import Config from .mixer_dataset import MixerDataset, _UndersampledDataset from .prompt_data_module import PromptDataModule from .t0_mixture...
better-promptability-main
better_promptability/data/t0_multitask_data_module.py
from __future__ import annotations import hashlib from typing import Iterable, Mapping, Union import math import numpy as np import torch from torch.utils.data._utils.collate import default_collate PAD_TYPE = Union[int, float, bool] def _find_max_shapes( batch: list[dict[str, np.ndarray]], allow_keys: Iterable...
better-promptability-main
better_promptability/data/data_utils.py
from __future__ import annotations import math import random from typing import Callable import torch.distributed as dist from torch.utils.data.dataloader import DataLoader, _BaseDataLoaderIter class MixerDataLoader(DataLoader): """ A dataloader that encapsulates multiple dataloaders. At each iteration, yie...
better-promptability-main
better_promptability/data/mixer_dataloader.py
def test_hello(): print("Hello, World!")
better-promptability-main
tests/hello_test.py
better-promptability-main
tests/__init__.py
import os from tango.common import Params def test_few_shot_baseline_all(): os.environ["CKPT"] = "null" d = Params.from_file("configs/fewshot_eval_all_green.jsonnet").as_dict() del os.environ["CKPT"] assert "result_anli_GPT_3_style_r1_score_eval" in d["steps"] assert "aggregated_results" in d["st...
better-promptability-main
tests/configs_test.py
better-promptability-main
tests/models/__init__.py
better-promptability-main
tests/steps/__init__.py
from better_promptability.steps.process_story_cloze import ProcessStoryCloze from better_promptability.common.testing import BetterPromptabilityTestCase class ProcessStoryClozeTest(BetterPromptabilityTestCase): def test_process_story_cloze(self): step = ProcessStoryCloze() result = step.run( ...
better-promptability-main
tests/steps/process_story_cloze_test.py
from better_promptability.steps.process_dataset import ProcessDataset from better_promptability.common.testing import BetterPromptabilityTestCase class ProcessDatasetTest(BetterPromptabilityTestCase): def test_process_dataset(self): step = ProcessDataset() result = step.run( old_data_p...
better-promptability-main
tests/steps/process_dataset_test.py
import pytest from transformers.models import t5 as hf_t5 from better_promptability.modules.transformer import Transformer @pytest.fixture(scope="module") def model_name(): return "google/t5-small-lm-adapt" @pytest.fixture(scope="module") def tokenizer(model_name): return hf_t5.T5Tokenizer.from_pretrained(m...
better-promptability-main
tests/modules/transformer_test.py
better-promptability-main
tests/modules/__init__.py
better-promptability-main
tests/data/__init__.py
from better_promptability.data.config import Config from better_promptability.data import T0Module from better_promptability.common.testing import BetterPromptabilityTestCase class T0ModuleTest(BetterPromptabilityTestCase): def test_t0_module_green(self): t0 = T0Module( config=Config(), ...
better-promptability-main
tests/data/t0_data_module_test.py
import pytest from better_promptability.data.mixer_dataset import MixerDataset @pytest.fixture def datasets(): return [["a1", "a2", "a3"], ["b1", "b2", "b3", "b4", "b5", "b6", "b7"]] def test_mixer_dataset(datasets): mixer = MixerDataset(datasets) assert len(mixer) == 10 assert [x for x in mixer] =...
better-promptability-main
tests/data/mixer_dataset_test.py
import random import sys from tqdm import tqdm random.seed(100) TASKS_METADATA = [ # task name, num templates, random performance ("ANLI", 45, 1/3), ("Hellaswag", 4, 1/4), ("StoryCloze", 5, 1/2), ("CB", 15, 1/3), ("COPA", 12, 1/2), ("RTE", 10, 1/2), ("WIC", 10, 1/2), ("WSC", 10, 1/...
better-promptability-main
scripts/bootstrap.py
import logging import os import sys from tango.common import Params from tqdm import tqdm from better_promptability.steps.process_dataset import ProcessDataset from better_promptability.steps.process_story_cloze import ProcessStoryCloze logging.basicConfig(level=logging.INFO) def process_green_datasets(old_base_p...
better-promptability-main
scripts/process_green_datasets.py
""" Download all of the data from the [bigscience/P3](https://huggingface.co/datasets/bigscience/P3) corresponding to a particular mixture. This script should only be run from the root of this repository. """ import importlib import json import os import sys from pathlib import Path import datasets from tango.common ...
better-promptability-main
scripts/download_t0_training_set.py
""" Subsamples the training set for each dataset (i.e., for all tepmlates). Ideally we want to sample the same examples across templates for a given dataset, but unfortunately this is impossible since the P3 dataset cache does not guarantee the same example order across templates. Check out, for example, hellaswag_comp...
better-promptability-main
scripts/subsample_t0_training_set.py
import sys import os sys.path.append(os.path.abspath(os.path.join("..", "nla_semparse"))) from nla_semparse.nla_metric import NlaMetric def test_metric_basic(): metric = NlaMetric() metric(["2"], ["2"]) assert metric.get_metric() == { "well_formedness": 1.0, "denotation_accuracy": 1.0, ...
allennlp-guide-master
nla_semparse/tests/nla_metric_test.py
allennlp-guide-master
nla_semparse/nla_semparse/__init__.py
from allennlp_semparse import DomainLanguage, predicate class NlaLanguage(DomainLanguage): def __init__(self): super().__init__( start_types={int}, allowed_constants={ "0": 0, "1": 1, "2": 2, "3": 3, "4...
allennlp-guide-master
nla_semparse/nla_semparse/nla_language.py
from typing import Dict, List, Optional from allennlp.training.metrics.metric import Metric from allennlp_semparse.domain_languages.domain_language import ExecutionError from .nla_language import NlaLanguage @Metric.register("nla_metric") class NlaMetric(Metric): """ Metric for evaluating prefix arithmetic ...
allennlp-guide-master
nla_semparse/nla_semparse/nla_metric.py
import sys import os import random import math import argparse from typing import List, Dict, Any sys.path.append(os.path.abspath(os.path.join("..", "nla_semparse"))) from nla_semparse.nla_language import NlaLanguage class DataGenerator: """ Generator for data points for natural language arithmetic. """...
allennlp-guide-master
nla_semparse/scripts/generate_data.py
# Inputs text: TextField title: TextField stars: LabelField # Outputs aspect: LabelField sentiment: LabelField
allennlp-guide-master
exercises/chapter05/input_output/add_list_source.py
# Inputs text: TextField title: TextField # Outputs sentiment: LabelField
allennlp-guide-master
exercises/chapter05/input_output/add_stars_source.py
# Inputs text: TextField title: TextField # Outputs sentiment: LabelField
allennlp-guide-master
exercises/chapter05/input_output/add_title_solution.py
# Inputs text: TextField # Outputs sentiment: LabelField
allennlp-guide-master
exercises/chapter05/input_output/add_title_source.py
# Inputs text: TextField title: TextField stars: LabelField aspect: LabelField # either here # Outputs sentiment: LabelField aspect: LabelField # or here
allennlp-guide-master
exercises/chapter05/input_output/add_aspect_solution.py
# Inputs text: TextField title: TextField stars: LabelField # Outputs aspect: List[LabelField] sentiment: List[LabelField] # or a SequenceLabelField that depends on `aspect`
allennlp-guide-master
exercises/chapter05/input_output/add_list_solution.py
# Inputs text: TextField title: TextField stars: LabelField # OR stars: ArrayField, if you want to model the numerical value # Outputs sentiment: LabelField
allennlp-guide-master
exercises/chapter05/input_output/add_stars_solution.py
# Inputs text: TextField title: TextField stars: LabelField # Outputs sentiment: LabelField
allennlp-guide-master
exercises/chapter05/input_output/add_aspect_source.py
from allennlp.common import Params from allennlp.data import DatasetReader, Instance, Vocabulary from allennlp.data.fields import LabelField, TextField from allennlp.data.iterators import BasicIterator from allennlp.data.token_indexers import SingleIdTokenIndexer from allennlp.data.tokenizers import WordTokenizer from ...
allennlp-guide-master
exercises/chapter05/putting_them_together/config_source.py
from allennlp.data import DatasetReader, Instance, Vocabulary from allennlp.data.fields import LabelField, TextField from allennlp.data.iterators import BasicIterator from allennlp.data.token_indexers import SingleIdTokenIndexer from allennlp.data.tokenizers import WordTokenizer from allennlp.models import Model from a...
allennlp-guide-master
exercises/chapter05/putting_them_together/code_source.py
from allennlp.data import DatasetReader, Instance from allennlp.data.fields import LabelField, TextField from allennlp.data.token_indexers import SingleIdTokenIndexer from allennlp.data.tokenizers import WordTokenizer # Data will be formatted as: # [title][tab][text][tab][stars][tab][aspect][tab][sentiment] @Dataset...
allennlp-guide-master
exercises/chapter05/input_output_reader/add_fields_source.py
from allennlp.data import DatasetReader, Instance from allennlp.data.fields import LabelField, TextField from allennlp.data.token_indexers import SingleIdTokenIndexer from allennlp.data.tokenizers import WordTokenizer # Data will be formatted as: # [title][tab][text][tab][stars][tab][aspect][tab][sentiment] @Dataset...
allennlp-guide-master
exercises/chapter05/input_output_reader/add_fields_solution.py
def test(): assert len(instances) == 2, "You didn't get two instances" expected_fields = {"text", "title", "stars", "aspect", "sentiment"} assert ( instances[0].fields.keys() == expected_fields ), "You don't have the right fields in your Instance" assert ( instances[0]["sentiment"] =...
allennlp-guide-master
exercises/chapter05/input_output_reader/add_fields_test.py
inputs = {"sentence": "a very well-made, funny and entertaining picture."} archive = ( "https://storage.googleapis.com/allennlp-public-models/" "basic_stanford_sentiment_treebank-2020.06.09.tar.gz" ) predictor = Predictor.from_path(archive) interpreter = SimpleGradient(predictor) interpretation = interpreter.sa...
allennlp-guide-master
exercises/part3/interpret/saliency_source.py
inputs = {"sentence": "a very well-made, funny and entertaining picture."} archive = ( "https://storage.googleapis.com/allennlp-public-models/" "basic_stanford_sentiment_treebank-2020.06.09.tar.gz" ) predictor = Predictor.from_path(archive) reducer = InputReduction(predictor) # or Hotflip(predictor) # if it is...
allennlp-guide-master
exercises/part3/interpret/attacker_source.py
from allennlp.interpret.saliency_interpreters import SimpleGradient from allennlp.predictors import Predictor
allennlp-guide-master
exercises/part3/interpret/saliency_setup.py
from allennlp.models.archival import load_archive from allennlp.predictors import Predictor from allennlp.interpret.attackers import InputReduction
allennlp-guide-master
exercises/part3/interpret/attacker_setup.py
inputs = ["one plus three minus four", "five minus six times seven over one"] for nla_input in inputs: output = translate_nla(nla_input) print(f"Input: {nla_input}") print(f"Prediction: {output}\n")
allennlp-guide-master
exercises/part3/semantic-parsing-seq2seq/predictor_source_medium.py
import csv from typing import Dict from allennlp.common.file_utils import cached_path from allennlp.common.util import START_SYMBOL, END_SYMBOL from allennlp.data import DatasetReader, Instance from allennlp.data.fields import TextField from allennlp.data.token_indexers import TokenIndexer, SingleIdTokenIndexer from a...
allennlp-guide-master
exercises/part3/semantic-parsing-seq2seq/dataset_reader_setup.py
class Seq2SeqDatasetReader(DatasetReader): def __init__( self, source_tokenizer: Tokenizer = None, target_tokenizer: Tokenizer = None, source_token_indexers: Dict[str, TokenIndexer] = None, target_token_indexers: Dict[str, TokenIndexer] = None, **kwargs, ) -> None...
allennlp-guide-master
exercises/part3/semantic-parsing-seq2seq/dataset_reader_source.py
from typing import List from allennlp.predictors import Predictor from allennlp.models.archival import load_archive from allennlp_models.generation import ( ComposedSeq2Seq, ) # Need this for loading model archive from nla_semparse.nla_semparse.nla_metric import ( NlaMetric, ) # Need this for loading model a...
allennlp-guide-master
exercises/part3/semantic-parsing-seq2seq/predictor_source_easy.py
from typing import Dict, List, Optional from allennlp.training.metrics.metric import Metric from allennlp_semparse.domain_languages.domain_language import ExecutionError from nla_semparse.nla_semparse.nla_language import NlaLanguage @Metric.register("nla_metric") class NlaMetric(Metric): """ Metric for eval...
allennlp-guide-master
exercises/part3/semantic-parsing-seq2seq/metric_setup.py
from typing import List from allennlp.predictors import Predictor from allennlp.models.archival import load_archive from allennlp_models.generation import ( ComposedSeq2Seq, ) # Need this for loading model archive from nla_semparse.nla_semparse.nla_metric import ( NlaMetric, ) # Need this for loading model a...
allennlp-guide-master
exercises/part3/semantic-parsing-seq2seq/predictor_setup.py
def evaluate(prediction: str, target: str) -> Dict[str, float]: metric = NlaMetric() metric([prediction], [target]) return metric.get_metric(reset=True) target = "(subtract (multiply 7 3) 2)" predictions = [ "(subtract (multiply 7 3) 2)", "(subtract (multiply 6 4) 5)", "subtract () add divide...
allennlp-guide-master
exercises/part3/semantic-parsing-seq2seq/metric_source.py
inputs = [ "eight over nine times six minus three plus seven over five minus one", "seven times eight plus five minus six plus one plus three plus two over seven", ] for nla_input in inputs: output = translate_nla(nla_input) print(f"Input: {nla_input}") print(f"Prediction: {output}\n")
allennlp-guide-master
exercises/part3/semantic-parsing-seq2seq/predictor_source_hard.py
from collections import Counter, defaultdict from typing import Dict from allennlp.data.instance import Instance from allennlp.data.fields import Field, TextField, LabelField, SequenceLabelField from allennlp.data.token_indexers import TokenIndexer, SingleIdTokenIndexer from allennlp.data.tokenizers import Token from ...
allennlp-guide-master
exercises/part2/reading-data/instances_setup.py
# You can implement your own dataset reader by subclassing DatasetReader. # At the very least, you need to implement the _read() method, preferably # text_to_instance() as well. @DatasetReader.register("classification-tsv") class ClassificationTsvReader(DatasetReader): def __init__( self, tokenizer:...
allennlp-guide-master
exercises/part2/reading-data/dataset_reader_basic_source.py