python_code
stringlengths
0
4.04M
repo_name
stringlengths
8
58
file_path
stringlengths
5
147
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch def calc_mean_invstddev(feature): if len(feature.size()) != 2: raise ValueError("We expect the input feature to be ...
data2vec_vision-main
deltalm/src/examples/speech_recognition/data/data_utils.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import numpy as np from fairseq.data import FairseqDataset from . import data_utils from .collaters import Seq2SeqCollater class...
data2vec_vision-main
deltalm/src/examples/speech_recognition/data/asr_dataset.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import absolute_import, division, print_function, unicode_literals import logging import math import torch import torch.nn.f...
data2vec_vision-main
deltalm/src/examples/speech_recognition/criterions/cross_entropy_acc.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from examples.speech_recognition.data.replabels import pack_replabels from fairseq import utils from fair...
data2vec_vision-main
deltalm/src/examples/speech_recognition/criterions/ASG_loss.py
import importlib import os # ASG loss requires wav2letter files_to_skip = set() try: import wav2letter except ImportError: files_to_skip.add("ASG_loss.py") for file in os.listdir(os.path.dirname(__file__)): if file.endswith(".py") and not file.startswith("_") and file not in files_to_skip: criter...
data2vec_vision-main
deltalm/src/examples/speech_recognition/criterions/__init__.py
#!/usr/bin/env python3 # # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import sys from sacremoses.normalize import MosesPunctNormalizer def main(args): normalizer = MosesPunctNormal...
data2vec_vision-main
deltalm/src/examples/constrained_decoding/normalize.py
#!/usr/bin/env python3 # # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import sys import sacremoses def main(args): """Tokenizes, preserving tabs""" mt = sacremoses.MosesTokeniz...
data2vec_vision-main
deltalm/src/examples/constrained_decoding/tok.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from . import rxf_src # noqa
data2vec_vision-main
deltalm/src/examples/rxf/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from . import label_smoothed_cross_entropy_r3f, sentence_prediction_r3f # noqa
data2vec_vision-main
deltalm/src/examples/rxf/rxf_src/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math import torch import torch.nn.functional as F from fairseq import utils from fairseq.criterions import FairseqCriterion, register_...
data2vec_vision-main
deltalm/src/examples/rxf/rxf_src/sentence_prediction_r3f.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math import torch import torch.nn.functional as F from fairseq import metrics, utils from fairseq.criterions import FairseqCriterion, ...
data2vec_vision-main
deltalm/src/examples/rxf/rxf_src/label_smoothed_cross_entropy_r3f.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from . import transformer_xl_model, truncated_bptt_lm_task # noqa
data2vec_vision-main
deltalm/src/examples/truncated_bptt/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os from dataclasses import dataclass, field from typing import List, Optional, Tuple import torch from fairseq import d...
data2vec_vision-main
deltalm/src/examples/truncated_bptt/truncated_bptt_lm_task.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from dataclasses import dataclass, field from typing import Dict, List, Optional import torch from fairseq.dataclass import Fa...
data2vec_vision-main
deltalm/src/examples/truncated_bptt/transformer_xl_model.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Helper script to pre-compute embeddings for a wav2letter++ dataset """ import argparse import glob import os from ...
data2vec_vision-main
deltalm/src/examples/wav2vec/wav2vec_featurize.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Data pre-processing: build vocabularies and binarize training data. """ import argparse import glob import os impor...
data2vec_vision-main
deltalm/src/examples/wav2vec/wav2vec_manifest.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Helper script to pre-compute embeddings for a wav2letter++ dataset """ import argparse import os def main(): ...
data2vec_vision-main
deltalm/src/examples/wav2vec/libri_labels.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Helper script to pre-compute embeddings for a wav2letter++ dataset """ import argparse import glob import os impor...
data2vec_vision-main
deltalm/src/examples/wav2vec/vq-wav2vec_featurize.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import argparse import contextlib import sys from collections import Counter from multiprocessing imp...
data2vec_vision-main
deltalm/src/examples/roberta/multiprocessing_bpe_encoder.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import argparse import json import os import re class InputExample: def __init__(self, paragrap...
data2vec_vision-main
deltalm/src/examples/roberta/preprocess_RACE.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json from functools import lru_cache def convert_sentence_to_json(sentence): if "_" in sentence: prefix, rest = sentence....
data2vec_vision-main
deltalm/src/examples/roberta/wsc/wsc_utils.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math import torch import torch.nn.functional as F from fairseq import utils from fairseq.criterions import LegacyFairseqCriterion, reg...
data2vec_vision-main
deltalm/src/examples/roberta/wsc/wsc_criterion.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from . import wsc_criterion # noqa from . import wsc_task # noqa
data2vec_vision-main
deltalm/src/examples/roberta/wsc/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import os import tempfile import numpy as np import torch import torch.nn.functional as F from fairseq import utils from fairseq....
data2vec_vision-main
deltalm/src/examples/roberta/wsc/wsc_task.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from . import commonsense_qa_task # noqa
data2vec_vision-main
deltalm/src/examples/roberta/commonsense_qa/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import os import numpy as np import torch from fairseq.data import ( Dictionary, IdDataset, ListDataset, NestedDi...
data2vec_vision-main
deltalm/src/examples/roberta/commonsense_qa/commonsense_qa_task.py
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import fileinput import sacremoses def main(): parser = argparse.ArgumentParser(description="...
data2vec_vision-main
deltalm/src/examples/megatron_11b/detok.py
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Translate pre-processed data with a trained model. """ import numpy as np import torch from fairseq import check...
data2vec_vision-main
deltalm/src/examples/criss/save_encoder.py
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import glob from subprocess import check_call try: import faiss has_faiss = True except Imp...
data2vec_vision-main
deltalm/src/examples/criss/mining/mine.py
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import glob import numpy as np DIM = 1024 def compute_dist(source_embs, target_embs, k=5, return...
data2vec_vision-main
deltalm/src/examples/criss/sentence_retrieval/encoder_analysis.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from fairseq.search import Search class NoisyChannelBeamSearch(Search): def __init__(self, tgt_dict): super().__in...
data2vec_vision-main
deltalm/src/examples/fast_noisy_channel/noisy_channel_beam_search.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from . import noisy_channel_translation # noqa from . import noisy_channel_sequence_generator # noqa from . import noisy_channel_beam_search...
data2vec_vision-main
deltalm/src/examples/fast_noisy_channel/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Dict, List, Optional import math import numpy as np import torch import torch.nn.functional as F from torch import Tensor...
data2vec_vision-main
deltalm/src/examples/fast_noisy_channel/noisy_channel_sequence_generator.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from fairseq.tasks.translation import TranslationTask from fairseq.tasks.language_modeling import LanguageModelingTask from fairseq import che...
data2vec_vision-main
deltalm/src/examples/fast_noisy_channel/noisy_channel_translation.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import os import os.path as op from collections import namedtuple from multiprocessing import cpu_count from typing import Li...
data2vec_vision-main
deltalm/src/examples/byte_level_bpe/get_bitext.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the r...
data2vec_vision-main
deltalm/src/examples/byte_level_bpe/gru_transformer.py
#!/usr/bin/env python3 from setuptools import find_packages, setup setup( name="layoutlmft", version="0.1", author="LayoutLM Team", url="https://github.com/microsoft/unilm/tree/master/layoutlmft", packages=find_packages(), python_requires=">=3.7", extras_require={"dev": ["flake8", "isort", "...
data2vec_vision-main
layoutlmft/setup.py
import os import re import numpy as np from transformers.utils import logging logger = logging.get_logger(__name__) PREFIX_CHECKPOINT_DIR = "checkpoint" _re_checkpoint = re.compile(r"^" + PREFIX_CHECKPOINT_DIR + r"\-(\d+)$") def get_last_checkpoint(folder): content = os.listdir(folder) checkpoints = [ ...
data2vec_vision-main
layoutlmft/layoutlmft/evaluation.py
from collections import OrderedDict from transformers import CONFIG_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, MODEL_NAMES_MAPPING, TOKENIZER_MAPPING from transformers.convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS, BertConverter, XLMRobertaConverter from transformers.models.auto.modeling_auto import auto...
data2vec_vision-main
layoutlmft/layoutlmft/__init__.py
from dataclasses import dataclass from typing import Dict, Optional, Tuple import torch from transformers.file_utils import ModelOutput @dataclass class ReOutput(ModelOutput): loss: Optional[torch.FloatTensor] = None logits: torch.FloatTensor = None hidden_states: Optional[Tuple[torch.FloatTensor]] = No...
data2vec_vision-main
layoutlmft/layoutlmft/utils.py
data2vec_vision-main
layoutlmft/layoutlmft/models/__init__.py
from dataclasses import dataclass, field from typing import Optional @dataclass class ModelArguments: """ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. """ model_name_or_path: str = field( metadata={"help": "Path to pretrained model or model identifier f...
data2vec_vision-main
layoutlmft/layoutlmft/models/model_args.py
# coding=utf-8 from transformers.models.layoutlm.tokenization_layoutlm import LayoutLMTokenizer from transformers.utils import logging logger = logging.get_logger(__name__) VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"} PRETRAINED_VOCAB_FILES_MAP = { "vocab_file": { "microsoft/layoutlmv2-base-uncased":...
data2vec_vision-main
layoutlmft/layoutlmft/models/layoutlmv2/tokenization_layoutlmv2.py
from .configuration_layoutlmv2 import LayoutLMv2Config from .modeling_layoutlmv2 import LayoutLMv2ForRelationExtraction, LayoutLMv2ForTokenClassification, LayoutLMv2Model from .tokenization_layoutlmv2 import LayoutLMv2Tokenizer from .tokenization_layoutlmv2_fast import LayoutLMv2TokenizerFast
data2vec_vision-main
layoutlmft/layoutlmft/models/layoutlmv2/__init__.py
# -*- coding: utf-8 -*- def add_layoutlmv2_config(cfg): _C = cfg # ----------------------------------------------------------------------------- # Config definition # ----------------------------------------------------------------------------- _C.MODEL.MASK_ON = True # When using pre-trained m...
data2vec_vision-main
layoutlmft/layoutlmft/models/layoutlmv2/detectron2_config.py
# coding=utf-8 import math import torch import torch.nn.functional as F import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss import detectron2 from detectron2.modeling import META_ARCH_REGISTRY from transformers import PreTrainedModel from transformers.modeling_outputs import ( ...
data2vec_vision-main
layoutlmft/layoutlmft/models/layoutlmv2/modeling_layoutlmv2.py
# coding=utf-8 from transformers.models.layoutlm.tokenization_layoutlm_fast import LayoutLMTokenizerFast from transformers.utils import logging from .tokenization_layoutlmv2 import LayoutLMv2Tokenizer logger = logging.get_logger(__name__) VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer....
data2vec_vision-main
layoutlmft/layoutlmft/models/layoutlmv2/tokenization_layoutlmv2_fast.py
# coding=utf-8 from transformers.models.layoutlm.configuration_layoutlm import LayoutLMConfig from transformers.utils import logging logger = logging.get_logger(__name__) LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP = { "layoutlmv2-base-uncased": "https://huggingface.co/microsoft/layoutlmv2-base-uncased/resolve/main...
data2vec_vision-main
layoutlmft/layoutlmft/models/layoutlmv2/configuration_layoutlmv2.py
# coding=utf-8 from transformers.utils import logging from ..layoutlmv2 import LayoutLMv2Config logger = logging.get_logger(__name__) LAYOUTXLM_PRETRAINED_CONFIG_ARCHIVE_MAP = { "layoutxlm-base": "https://huggingface.co/layoutxlm-base/resolve/main/config.json", "layoutxlm-large": "https://huggingface.co/lay...
data2vec_vision-main
layoutlmft/layoutlmft/models/layoutxlm/configuration_layoutxlm.py
# coding=utf-8 from transformers import XLMRobertaTokenizerFast from transformers.file_utils import is_sentencepiece_available from transformers.utils import logging if is_sentencepiece_available(): from .tokenization_layoutxlm import LayoutXLMTokenizer else: LayoutXLMTokenizer = None logger = logging.get_l...
data2vec_vision-main
layoutlmft/layoutlmft/models/layoutxlm/tokenization_layoutxlm_fast.py
# coding=utf-8 from transformers import XLMRobertaTokenizer from transformers.utils import logging logger = logging.get_logger(__name__) SPIECE_UNDERLINE = "▁" VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model"} PRETRAINED_VOCAB_FILES_MAP = { "vocab_file": { "layoutxlm-base": "https://huggin...
data2vec_vision-main
layoutlmft/layoutlmft/models/layoutxlm/tokenization_layoutxlm.py
from .configuration_layoutxlm import LayoutXLMConfig from .modeling_layoutxlm import LayoutXLMForRelationExtraction, LayoutXLMForTokenClassification, LayoutXLMModel from .tokenization_layoutxlm import LayoutXLMTokenizer from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast
data2vec_vision-main
layoutlmft/layoutlmft/models/layoutxlm/__init__.py
# coding=utf-8 from transformers.utils import logging from ..layoutlmv2 import LayoutLMv2ForRelationExtraction, LayoutLMv2ForTokenClassification, LayoutLMv2Model from .configuration_layoutxlm import LayoutXLMConfig logger = logging.get_logger(__name__) LAYOUTXLM_PRETRAINED_MODEL_ARCHIVE_LIST = [ "layoutxlm-base...
data2vec_vision-main
layoutlmft/layoutlmft/models/layoutxlm/modeling_layoutxlm.py
from transformers.models.layoutlm import *
data2vec_vision-main
layoutlmft/layoutlmft/models/layoutlm/__init__.py
import collections import time from typing import Any, Dict, List, Optional, Tuple, Union import torch from packaging import version from torch import nn from torch.utils.data import DataLoader, Dataset from transformers.trainer_utils import EvalPrediction, PredictionOutput, speed_metrics from transformers.utils impo...
data2vec_vision-main
layoutlmft/layoutlmft/trainers/xfun_trainer.py
from .funsd_trainer import FunsdTrainer from .xfun_trainer import XfunReTrainer, XfunSerTrainer
data2vec_vision-main
layoutlmft/layoutlmft/trainers/__init__.py
from typing import Any, Dict, Union import torch from transformers import Trainer class FunsdTrainer(Trainer): def _prepare_inputs(self, inputs: Dict[str, Union[torch.Tensor, Any]]) -> Dict[str, Union[torch.Tensor, Any]]: """ Prepare :obj:`inputs` before feeding them to the model, converting the...
data2vec_vision-main
layoutlmft/layoutlmft/trainers/funsd_trainer.py
data2vec_vision-main
layoutlmft/layoutlmft/modules/__init__.py
data2vec_vision-main
layoutlmft/layoutlmft/modules/decoders/__init__.py
import copy import torch from torch import nn from torch.nn import CrossEntropyLoss class BiaffineAttention(torch.nn.Module): """Implements a biaffine attention operator for binary relation classification. PyTorch implementation of the biaffine attention operator from "End-to-end neural relation extract...
data2vec_vision-main
layoutlmft/layoutlmft/modules/decoders/re.py
# flake8: noqa from .data_collator import DataCollatorForKeyValueExtraction from .datasets import *
data2vec_vision-main
layoutlmft/layoutlmft/data/__init__.py
import torch from detectron2.data.detection_utils import read_image from detectron2.data.transforms import ResizeTransform, TransformList def normalize_bbox(bbox, size): return [ int(1000 * bbox[0] / size[0]), int(1000 * bbox[1] / size[1]), int(1000 * bbox[2] / size[0]), int(1000 ...
data2vec_vision-main
layoutlmft/layoutlmft/data/utils.py
from dataclasses import dataclass, field from typing import Optional @dataclass class DataTrainingArguments: """ Arguments pertaining to what data we are going to input our model for training and eval. """ task_name: Optional[str] = field(default="ner", metadata={"help": "The name of the task (ner, p...
data2vec_vision-main
layoutlmft/layoutlmft/data/data_args.py
from dataclasses import dataclass from typing import Optional, Union import torch from detectron2.structures import ImageList from transformers import PreTrainedTokenizerBase from transformers.file_utils import PaddingStrategy @dataclass class DataCollatorForKeyValueExtraction: """ Data collator that will d...
data2vec_vision-main
layoutlmft/layoutlmft/data/data_collator.py
data2vec_vision-main
layoutlmft/layoutlmft/data/datasets/__init__.py
# Lint as: python3 import json import logging import os import datasets from layoutlmft.data.utils import load_image, merge_bbox, normalize_bbox, simplify_bbox from transformers import AutoTokenizer _URL = "https://github.com/doc-analysis/XFUN/releases/download/v1.0/" _LANG = ["zh", "de", "es", "fr", "en", "it", "...
data2vec_vision-main
layoutlmft/layoutlmft/data/datasets/xfun.py
# coding=utf-8 import json import os import datasets from layoutlmft.data.utils import load_image, normalize_bbox logger = datasets.logging.get_logger(__name__) _CITATION = """\ @article{Jaume2019FUNSDAD, title={FUNSD: A Dataset for Form Understanding in Noisy Scanned Documents}, author={Guillaume Jaume and ...
data2vec_vision-main
layoutlmft/layoutlmft/data/datasets/funsd.py
#!/usr/bin/env python # coding=utf-8 import logging import os import sys from dataclasses import dataclass, field from typing import Optional import numpy as np from datasets import ClassLabel, load_dataset, load_metric import layoutlmft.data.datasets.xfun import transformers from layoutlmft.data import DataCollator...
data2vec_vision-main
layoutlmft/examples/run_xfun_ser.py
#!/usr/bin/env python # coding=utf-8 import logging import os import sys from dataclasses import dataclass, field from typing import Optional import numpy as np from datasets import ClassLabel, load_dataset, load_metric import layoutlmft.data.datasets.funsd import transformers from layoutlmft.data import DataCollato...
data2vec_vision-main
layoutlmft/examples/run_funsd.py
#!/usr/bin/env python # coding=utf-8 import logging import os import sys import numpy as np from datasets import ClassLabel, load_dataset import layoutlmft.data.datasets.xfun import transformers from layoutlmft import AutoModelForRelationExtraction from layoutlmft.data.data_args import XFUNDataTrainingArguments from...
data2vec_vision-main
layoutlmft/examples/run_xfun_re.py
""" Simple check list from AllenNLP repo: https://github.com/allenai/allennlp/blob/master/setup.py To create the package for pypi. 1. Change the version in __init__.py and setup.py. 2. Commit these changes with the message: "Release: VERSION" 3. Add a tag in git to mark the release: "git tag VERSION -m'Adds tag VER...
data2vec_vision-main
unilm-v1/src/setup.py
import torch from torch.nn import DataParallel from torch.cuda._utils import _get_device_index from torch.nn.parallel._functions import Scatter from itertools import chain def scatter_imbalance(inputs, target_gpus, dim=0): r""" Slices tensors into approximately equal chunks and distributes them across giv...
data2vec_vision-main
unilm-v1/src/nn/data_parallel.py
data2vec_vision-main
unilm-v1/src/nn/__init__.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
data2vec_vision-main
unilm-v1/src/pytorch_pretrained_bert/optimization.py
__version__ = "0.4.0" from .tokenization import BertTokenizer, BasicTokenizer, WordpieceTokenizer from .modeling import (BertConfig, BertModel, BertForPreTraining, BertForMaskedLM, BertForNextSentencePrediction, BertForSequenceClassification, BertForMultipleChoice, BertForTokenClassification, Ber...
data2vec_vision-main
unilm-v1/src/pytorch_pretrained_bert/__init__.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
data2vec_vision-main
unilm-v1/src/pytorch_pretrained_bert/tokenization.py
# coding=utf-8 """PyTorch optimization for BERT model.""" from apex.optimizers import FP16_Optimizer class FP16_Optimizer_State(FP16_Optimizer): def __init__(self, init_optimizer, static_loss_scale=1.0, dynamic_loss_scale=False, dynamic_loss_arg...
data2vec_vision-main
unilm-v1/src/pytorch_pretrained_bert/optimization_fp16.py
# coding=utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.nn.functional as F from torch.nn.modules.loss import _Loss class LabelSmoothingLoss(_Loss): """ With label smoothing, KL-divergence between q_{smoothed gr...
data2vec_vision-main
unilm-v1/src/pytorch_pretrained_bert/loss.py
""" Utilities for working with the local dataset cache. This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp Copyright by the AllenNLP authors. """ import os import logging import shutil import tempfile import json from urllib.parse import urlparse from pathlib import Path from typing ...
data2vec_vision-main
unilm-v1/src/pytorch_pretrained_bert/file_utils.py
# coding=utf-8 """PyTorch BERT model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import copy import json import math import logging import tarfile import tempfile import shutil import numpy as np from scipy.stats import truncnorm import t...
data2vec_vision-main
unilm-v1/src/pytorch_pretrained_bert/modeling.py
# coding: utf8 def main(): import sys try: from .convert_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ModuleNotFoundError: print("pytorch_pretrained_bert can only be used from the commandline to convert TensorFlow models in PyTorch, " "In that case, i...
data2vec_vision-main
unilm-v1/src/pytorch_pretrained_bert/__main__.py
#!/usr/bin/env python from __future__ import print_function __author__ = 'xinya' from bleu.bleu import Bleu from meteor.meteor import Meteor from rouge.rouge import Rouge from cider.cider import Cider from collections import defaultdict from argparse import ArgumentParser import string import sys reload(sys) sys.setd...
data2vec_vision-main
unilm-v1/src/qg/eval_on_unilm_tokenized_ref.py
#!/usr/bin/env python from __future__ import print_function __author__ = 'xinya' from bleu.bleu import Bleu from meteor.meteor import Meteor from rouge.rouge import Rouge from cider.cider import Cider from collections import defaultdict from argparse import ArgumentParser import string import sys reload(sys) sys.setd...
data2vec_vision-main
unilm-v1/src/qg/eval.py
data2vec_vision-main
unilm-v1/src/gigaword/__init__.py
"""BERT finetuning runner.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import logging import glob import json import argparse import math import string from multiprocessing import Pool, cpu_count from tqdm import tqdm, trange from pathlib i...
data2vec_vision-main
unilm-v1/src/gigaword/eval.py
from __future__ import print_function, unicode_literals, division import os import re import codecs import platform from subprocess import check_output from tempfile import mkdtemp from functools import partial try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigPars...
data2vec_vision-main
unilm-v1/src/gigaword/bs_pyrouge.py
data2vec_vision-main
unilm-v1/src/cnndm/__init__.py
"""BERT finetuning runner.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import logging import glob import json import argparse import math import string from multiprocessing import Pool, cpu_count from tqdm import tqdm, trange from pathlib i...
data2vec_vision-main
unilm-v1/src/cnndm/eval.py
from __future__ import print_function, unicode_literals, division import os import re import codecs import platform from subprocess import check_output from tempfile import mkdtemp from functools import partial try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigPars...
data2vec_vision-main
unilm-v1/src/cnndm/bs_pyrouge.py
from random import randint, shuffle from random import random as rand import numpy as np import torch import torch.utils.data def get_random_word(vocab_words): i = randint(0, len(vocab_words)-1) return vocab_words[i] def batch_list_to_batch_tensors(batch): batch_tensors = [] for x in zip(*batch): ...
data2vec_vision-main
unilm-v1/src/biunilm/loader_utils.py
"""BERT finetuning runner.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import logging import glob import argparse import math from tqdm import tqdm, trange import numpy as np import torch from torch.utils.data import DataLoader, RandomSampl...
data2vec_vision-main
unilm-v1/src/biunilm/decode_seq2seq.py
data2vec_vision-main
unilm-v1/src/biunilm/__init__.py
from random import randint, shuffle, choice from random import random as rand import math import torch from biunilm.loader_utils import get_random_word, batch_list_to_batch_tensors, Pipeline # Input file format : # 1. One sentence per line. These should ideally be actual sentences, # not entire paragraphs or arbit...
data2vec_vision-main
unilm-v1/src/biunilm/seq2seq_loader.py
import pickle import math import argparse import glob from pathlib import Path from tqdm import tqdm import unicodedata from pytorch_pretrained_bert.tokenization import BertTokenizer def read_traces_from_file(file_name): with open(file_name, "rb") as fin: meta = pickle.load(fin) num_samples = met...
data2vec_vision-main
unilm-v1/src/biunilm/gen_seq_from_trace.py
"""BERT finetuning runner.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import logging import glob import math import json import argparse import random from pathlib import Path from tqdm import tqdm, trange import numpy as np import torch f...
data2vec_vision-main
unilm-v1/src/biunilm/run_seq2seq.py
"""BERT finetuning runner.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import json import logging import argparse import math from tqdm import tqdm, trange import numpy as np import torch import random import pickle from transformers impor...
data2vec_vision-main
s2s-ft/decode_seq2seq.py
from io import open from setuptools import find_packages, setup extras = { 'serving': ['pydantic', 'uvicorn', 'fastapi'], 'serving-tf': ['pydantic', 'uvicorn', 'fastapi'], 'serving-torch': ['pydantic', 'uvicorn', 'fastapi', 'torch'] } extras['all'] = [package for package in extras.values()] setup( na...
data2vec_vision-main
s2s-ft/setup.py
import pickle import math import argparse import glob import logging from pathlib import Path from tqdm import tqdm import unicodedata from transformers import BertTokenizer, RobertaTokenizer from s2s_ft.tokenization_unilm import UnilmTokenizer from s2s_ft.tokenization_minilm import MinilmTokenizer logging.basicConf...
data2vec_vision-main
s2s-ft/gen_seq_from_trace.py
from __future__ import absolute_import, division, print_function import argparse import logging import os import json import random import numpy as np import torch from torch.utils.data import (DataLoader, SequentialSampler) from torch.utils.data.distributed import DistributedSampler try: from torch.utils.tensor...
data2vec_vision-main
s2s-ft/run_seq2seq.py
"""BERT finetuning runner.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import logging import glob import json import argparse import math import string from multiprocessing import Pool, cpu_count from tqdm import tqdm, trange from pathlib i...
data2vec_vision-main
s2s-ft/evaluations/eval_for_xsum.py