python_code
stringlengths
0
679k
repo_name
stringlengths
9
41
file_path
stringlengths
6
149
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """GLUE dataset.""" from abc import ABC from abc import abstractmethod from torch.utils.data import Dataset from megatron import print_rank_0 from tasks.data_utils import build_sample from tasks.data_utils import build_tokens_types_paddings_from_text ...
Megatron-LM-master
tasks/glue/data.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """MNLI dataset.""" from megatron import print_rank_0 from tasks.data_utils import clean_text from .data import GLUEAbstractDataset LABELS = {'contradiction': 0, 'entailment': 1, 'neutral': 2} class MNLIDataset(GLUEAbstractDataset): def __init__(...
Megatron-LM-master
tasks/glue/mnli.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Detokenization.""" import re def ptb_detokenizer(string): string = string.replace(" '", "'") string = string.replace(" \n", "\n") string = string.replace("\n ", "\n") string = string.replace(" n't", "n't") string = string.replace(...
Megatron-LM-master
tasks/zeroshot_gpt/detokenizer.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Zero-shot datasets.""" import json import math import numpy as np import torch from megatron import get_args from megatron import print_rank_0 from megatron import get_tokenizer from .detokenizer import get_detokenizer def build_dataset(task): ...
Megatron-LM-master
tasks/zeroshot_gpt/datasets.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """GPT zero-shot evaluation.""" import math import torch from megatron import get_args from megatron import print_rank_0, is_last_rank from megatron import get_tokenizer from megatron.core import parallel_state, tensor_parallel from megatron.checkpointi...
Megatron-LM-master
tasks/zeroshot_gpt/evaluate.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Finetune utilities.""" import torch import torch.nn.functional as F from megatron import get_args from megatron import print_rank_0 from megatron import get_timers from megatron import utils from megatron.core import mpu from megatron.checkpointing imp...
Megatron-LM-master
tasks/vision/finetune_utils.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Main tasks functionality.""" import os import sys sys.path.append( os.path.abspath( os.path.join( os.path.join(os.path.dirname(__file__), os.path.pardir), os.path.pardir, ) ) ) from megatron import get_a...
Megatron-LM-master
tasks/vision/main.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Vision-classification finetuning/evaluation.""" import torch.nn.functional as F from functools import partial from megatron import get_args, get_timers from megatron import print_rank_0 from megatron.model.vision.classification import VitClassification...
Megatron-LM-master
tasks/vision/classification/classification.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Evaluation utilities.""" import os from functools import partial import torch from megatron import get_args from megatron import print_rank_0, print_rank_last from megatron.core import mpu from megatron.schedules import get_forward_backward_func from...
Megatron-LM-master
tasks/vision/classification/eval_utils.py
# BSD 3-Clause License # # Copyright (c) Soumith Chintala 2016, # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this #...
Megatron-LM-master
tasks/vision/segmentation/cityscapes.py
#!/usr/bin/env python # -*- coding: UTF-8 -*- #copyright (c) go-hiroaki & Chokurei #email: guangmingwu2010@gmail.com # guozhilingty@gmail.com # # # 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 as...
Megatron-LM-master
tasks/vision/segmentation/metrics.py
# Copyright (c) 2020 The MMSegmenation Authors. # # This source code is licensed under the Apache license found in the # LICENSE file in the root directory of this source tree. import random import os import math import mmcv import torch import numpy as np import torchvision.transforms as T from torchvision import dat...
Megatron-LM-master
tasks/vision/segmentation/transforms.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import math import einops import torch import apex import torch.nn.functional as F from megatron import get_args from megatron.model.module import MegatronModule from megatron.model.vision.vit_backbone import VitBackbone, VitMlpHead from megatron.model.visi...
Megatron-LM-master
tasks/vision/segmentation/seg_models.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Vision-classification finetuning/evaluation.""" import torch import torch.nn.functional as F from functools import partial from megatron import get_args, get_timers from megatron import print_rank_0, print_rank_last from megatron.core import mpu from t...
Megatron-LM-master
tasks/vision/segmentation/finetune_setr.py
import math import torch import numpy as np from megatron import get_args def slidingcrops(img, mask): # img: [b c h w] # mask: [b h w] args = get_args() assert args.img_h == args.img_w crop_size = args.img_h stride = args.seg_stride ignore_index = args.ignore_index n, c, h, w = img.sha...
Megatron-LM-master
tasks/vision/segmentation/utils.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Vision-classification finetuning/evaluation.""" import numpy as np import torch import torch.nn.functional as F from functools import partial from megatron import get_args, get_timers from megatron import print_rank_0, print_rank_last from megatron.cor...
Megatron-LM-master
tasks/vision/segmentation/finetune_segformer.py
import random import os import math import mmcv import torch import numpy as np import torchvision.transforms as T from torchvision import datasets from torch.utils.data import Dataset from megatron.data.autoaugment import ImageNetPolicy from tasks.vision.segmentation.cityscapes import Cityscapes import tasks.vision.se...
Megatron-LM-master
tasks/vision/segmentation/data.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import math import einops import torch import apex import torch.nn.functional as F from megatron import get_args from megatron.model import LayerNorm from megatron.model.module import MegatronModule from megatron.model.vision.utils import resize class Set...
Megatron-LM-master
tasks/vision/segmentation/seg_heads.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Race.""" from megatron import get_args from megatron import print_rank_0 from megatron import get_tokenizer from megatron.model.multiple_choice import MultipleChoice from tasks.eval_utils import accuracy_func_provider from tasks.finetune_utils import f...
Megatron-LM-master
tasks/race/finetune.py
import glob import json import os import time from torch.utils.data import Dataset from megatron import print_rank_0 from tasks.data_utils import build_sample from tasks.data_utils import build_tokens_types_paddings_from_ids from tasks.data_utils import clean_text NUM_CHOICES = 4 MAX_QA_LENGTH = 128 class RaceDa...
Megatron-LM-master
tasks/race/data.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import torch from megatron import get_args, print_rank_0 from megatron.checkpointing import load_biencoder_checkpoint from megatron.data.orqa_wiki_dataset import get_open_retrieval_wiki_dataset from megatron.data.realm_index import OpenRetreivalDataStore,...
Megatron-LM-master
tasks/orqa/evaluate_utils.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Main tasks functionality.""" from megatron import get_args, print_rank_0 from megatron.indexer import IndexBuilder from tasks.orqa.evaluate_utils import ORQAEvaluator def main(): """ Main program """ args = get_args() """ Cre...
Megatron-LM-master
tasks/orqa/evaluate_orqa.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # The following code has been taken from # https://github.com/facebookresearch/DPR, which is CC-BY-NC 4.0 # licensed as of now. More details on the license can be found # at https://github.com/facebookresearch/DPR/blob/m...
Megatron-LM-master
tasks/orqa/unsupervised/qa_utils.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """ Data Loader for Google NQ dataset """ from abc import ABC import csv from collections import OrderedDict import numpy as np import torch from torch.utils.data import DataLoader from torch.utils.data import Dataset, BatchSampler from megatron import...
Megatron-LM-master
tasks/orqa/unsupervised/nq.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # The following code has been taken from # https://github.com/facebookresearch/DPR, which is CC-BY-NC 4.0 # licensed as of now. More details on the license can be found # at https://github.com/facebookresearch/DPR/blob/m...
Megatron-LM-master
tasks/orqa/unsupervised/tokenizers.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Evaluation utilities.""" from collections import OrderedDict import math import numpy as np import time import torch import torch.nn.functional as F from torch.utils.data import DataLoader from megatron import get_args, print_rank_0 from megatron.core ...
Megatron-LM-master
tasks/orqa/supervised/eval_utils.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """ORQA finetuning/evaluation.""" from functools import partial import sys import math import torch import torch.nn.functional as F from megatron import get_args, get_timers, get_tokenizer, print_rank_0 from megatron.core import mpu from megatron.indexe...
Megatron-LM-master
tasks/orqa/supervised/finetune.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """ORQA dataset.""" import json import random from abc import ABC from abc import abstractmethod import numpy as np from torch.utils.data import Dataset from megatron import print_rank_0, get_args from megatron.data.biencoder_dataset_utils import make_a...
Megatron-LM-master
tasks/orqa/supervised/data.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Processing large data for pretraining.""" import argparse import math import json import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import time imp...
Megatron-LM-master
tools/preprocess_data.py
import os import sys import json import argparse sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) ) from megatron.data.indexed_dataset import ( MMapIndexedDataset, MMapIndexedDatasetBuilder, get_bin_path, get_idx_path, ) def get_args(): parser = argpa...
Megatron-LM-master
tools/merge_datasets.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Processing nmt data for finetuning.""" import argparse import json import multiprocessing import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import...
Megatron-LM-master
tools/preprocess_data_nmt.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import sys import json import requests if __name__ == "__main__": url = sys.argv[1] url = 'http://' + url + '/api' headers = {'Content-Type': 'application/json'} while True: sentence = input("Enter prompt: ") tokens_to_gen...
Megatron-LM-master
tools/text_generation_cli.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Sample Generate GPT""" import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import socket from megatron import get_args from megatron import print_ran...
Megatron-LM-master
tools/run_text_generation_server.py
import os import os.path as osp import pathlib import subprocess def recursively_lint_files(): """Recursively lint all python files in chosen subdirectories of megatron-lm""" try: import autopep8 except ModuleNotFoundError: print("Please first install autopep8 via `pip install autopep8`")...
Megatron-LM-master
tools/linter.py
# coding=utf-8 # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. """Processing text modality data for MultiModal pretraining.""" import argparse import json import multiprocessing import os import sys import numpy as np from torchvision.transforms import ToTensor sys.path.append(os.path.abspath(os.path....
Megatron-LM-master
tools/preprocess_mmdata.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import json import os import sys import types import torch def add_arguments(parser): group = parser.add_argument_group(title='Megatron loader') group.add_argument('--true-vocab-size', type=int, default=None, help='origina...
Megatron-LM-master
tools/checkpoint/loader_megatron.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import argparse import importlib import torch.multiprocessing as mp import os import sys # A loader is a python file with at least two functions # - add_arguments - takes in a parser and adds any arguments needed # - load_checkpoint - takes in the queue a...
Megatron-LM-master
tools/checkpoint/util.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import argparse from collections.abc import Mapping import concurrent.futures import os import sys import torch def add_arguments(parser): group = parser.add_argument_group(title='Megatron saver') group.add_argument('--megatron-path', type=str,...
Megatron-LM-master
tools/checkpoint/saver_megatron.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import json import os import sys import torch import transformers from tqdm import tqdm import types def add_arguments(parser): group = parser.add_argument_group(title='Llama-2 HF loader.') group.add_argument('--true-vocab-size', type=int, defau...
Megatron-LM-master
tools/checkpoint/loader_llama2_hf.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import json import time import sys if __name__ == '__main__': url_filename = sys.argv[1] data_filename = sys.argv[2] output_filename = sys.argv[3] urls = set() with open(url_filename, 'r') as f: for line in f: m...
Megatron-LM-master
tools/openwebtext/remove_group_duplicates.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import argparse import json import os import time """ This code adds id to each json object in a json file. User can add prefix to the ids. """ if __name__ == '__main__': print('parsing the arguments ...') parser = argparse.ArgumentParser() ...
Megatron-LM-master
tools/openwebtext/add_id.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import glob import sys import json import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--json_path", type=str, default=".", help="path where all the json files are located") parser.add_...
Megatron-LM-master
tools/openwebtext/merge_jsons.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # WARNING! This file contains a blacklist of known malicious sites and thus contains some NSFW language. import glob import re import time import tldextract import sys # List of the domains to blacklist. domain_blacklist = set([ '500px', 'aapks...
Megatron-LM-master
tools/openwebtext/blacklist_urls.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """ Filter and clean documents: Capable to clean docs with less than 512 characters, less than 256 characters and contains javascript, fix text and dataset specific cleaning like stories and realnews datasets. Program arguments have the details. """ impor...
Megatron-LM-master
tools/openwebtext/cleanup_fix_dataset.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import json import time import sys if __name__ == '__main__': print('grouping duplicate urls ...') input = sys.argv[1] output = sys.argv[2] if len(sys.argv) > 3: jaccard_similarity_threshold = float(sys.argv[3]) else: ...
Megatron-LM-master
tools/openwebtext/group_duplicate_url.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import argparse from functools import partial import itertools import json from lsh import cache, minhash import multiprocessing import numpy as np import time import pickle import sys import os # This function is adapted from: # https://github.com/matt...
Megatron-LM-master
tools/openwebtext/find_duplicates.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import ftfy import json from langdetect import detect import numpy as np import time import os import sys from tokenizer import Tokenizer MIN_DOCUMENT_LENGHT = 128 def print_progress(prefix, start_time, num_docs, num_fixed_text, num...
Megatron-LM-master
tools/openwebtext/cleanup_dataset.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """ Deduplicate downstream tasks from training dataset. 13-grams have been used. All split documents with less than 200 characters got filtered. Any document with more than 10 splits got filtered as well. """ import argparse from functools import partial ...
Megatron-LM-master
tools/openwebtext/filter_ngrams.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import importlib required_libs = [ "faiss", "h5py", "transformers", # for huggingface bert ] for lib in required_libs: try: globals()[lib] = importlib.import_module(lib) except ImportError as e: raise Exception(f"Miss...
Megatron-LM-master
tools/retro/external_libs.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import os import torch import types from megatron import get_retro_args from megatron.tokenizer.tokenizer import ( _BertWordPieceTokenizer, _GPT2BPETokenizer, _GPTSentencePieceTokenizer, ) def get_args_path(workdir): '''Argument copy st...
Megatron-LM-master
tools/retro/utils.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. """Preprocess data for Retro. Stages (see argument '--retro-tasks'): - Build chunk database (DB). - Build index (train, add). - Query pretraining neighbors. """ import json import os import torch from megatron import get_args, initialize_megatron, prin...
Megatron-LM-master
tools/retro/main.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. from .cli import retro
Megatron-LM-master
tools/retro/cli/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import json import numpy as np import os import torch import types from megatron.global_vars import set_global_variables, set_retro_args from megatron.initialize import ( initialize_megatron, _initialize_distributed, _set_random_seed, _co...
Megatron-LM-master
tools/retro/cli/cli.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import os from . import retro if __name__ == "__main__": retro.init(os.environ["RETRO_WORKDIR"])
Megatron-LM-master
tools/retro/cli/__main__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. from collections import defaultdict from concurrent.futures import as_completed, ProcessPoolExecutor from functools import reduce import glob import json import numpy as np import os from pathlib import Path import threading import torch from tqdm import ...
Megatron-LM-master
tools/retro/db/build.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. from .build import build_db
Megatron-LM-master
tools/retro/db/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import json import numpy as np import torch from tqdm import tqdm from megatron import get_args, print_rank_0 from tools.retro.external_libs import h5py from tools.retro.utils import get_gpt_tokenizer class DBDataset(torch.utils.data.Dataset): '''D...
Megatron-LM-master
tools/retro/db/dataset.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. from collections import defaultdict import glob import json import numpy as np import os from tqdm import tqdm from megatron import get_retro_args, print_rank_0 from megatron.data.indexed_dataset import MMapIndexedDataset from tools.retro.external_libs i...
Megatron-LM-master
tools/retro/db/utils.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import numpy as np import os import shutil import torch from tqdm import tqdm from megatron import get_retro_args, print_rank_0 from tools.bert_embedding import DiskDataParallelBertEmbedder from tools.retro.db.utils import ( get_indexed_dataset_infos...
Megatron-LM-master
tools/retro/index/build.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import abc import numpy as np import os import torch from megatron import get_retro_args from tools.retro.external_libs import faiss from .utils import get_index_dir class Index(abc.ABC): '''Abstract base class for indexes. *Note* : While cu...
Megatron-LM-master
tools/retro/index/index.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. from .build import add_to_index, build_index, train_index # from .index import Index
Megatron-LM-master
tools/retro/index/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. from .indexes import FaissBaseIndex, FaissParallelAddIndex class IndexFactory: '''Get index. Index type generally read from argument '--retro-index-ty'. ''' @classmethod def get_index_class(cls, index_type): return { ...
Megatron-LM-master
tools/retro/index/factory.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import concurrent import gc import glob import numpy as np import os import psutil import time import torch from tqdm import tqdm from megatron import get_retro_args, print_rank_0 from tools.retro.db.utils import get_indexed_dataset_infos from tools.retr...
Megatron-LM-master
tools/retro/index/utils.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. """Multi-process & multi-node version of Faiss's index.add(). This class inherits from FaissBaseIndex, and optimizes the 'add()' method by making it multi-node and multi-process, with bit-wise equivalence to FaissBaseIndex. This allows 'add()' to scale o...
Megatron-LM-master
tools/retro/index/indexes/faiss_par_add.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. """ This class implements a simple, un-optimized wrapper around a Faiss index, that implements the Index interface (see ..index.py). While this class is instantiable, it is meant to be extended with optimizations in classes that inherit from this class (s...
Megatron-LM-master
tools/retro/index/indexes/faiss_base.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. from .faiss_base import FaissBaseIndex from .faiss_par_add import FaissParallelAddIndex
Megatron-LM-master
tools/retro/index/indexes/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import os import torch from megatron import get_retro_args, print_rank_0 from megatron.data.gpt_dataset import build_train_valid_test_datasets \ as build_gpt_train_valid_test_datasets from megatron.training import ( build_train_valid_test_dataset...
Megatron-LM-master
tools/retro/query/chunk_dataset.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import numpy as np import os import torch from megatron import get_args, get_retro_args from tools.bert_embedding.utils import BlockPathMap from tools.retro.db.utils import get_merged_train_dataset as get_db_dataset from tools.retro.external_libs import ...
Megatron-LM-master
tools/retro/query/retro_dataset.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import numpy as np import os import psutil import time import torch from tqdm import tqdm from megatron import get_retro_args, print_rank_0 from tools.bert_embedding import BertEmbedder from tools.bert_embedding.utils import get_missing_blocks_by_rank fr...
Megatron-LM-master
tools/retro/query/query.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. from .query import query_pretraining_neighbors
Megatron-LM-master
tools/retro/query/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import hashlib import os from megatron import get_retro_args def get_query_workdir(): args = get_retro_args() return os.path.join(args.retro_workdir, "query") def get_neighbor_dirname(key, dataset): hashes = ",".join([ d.desc_hash for d i...
Megatron-LM-master
tools/retro/query/utils.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import importlib required_libs = [ "h5py", "transformers", # for huggingface bert ] for lib in required_libs: try: globals()[lib] = importlib.import_module(lib) except ImportError as e: raise Exception(f"Missing one or mo...
Megatron-LM-master
tools/bert_embedding/external_libs.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. from functools import partial import numpy as np import os import time import torch from torch.utils.data import BatchSampler, DataLoader, SequentialSampler, Subset from torch.utils.data._utils.collate import default_collate from tqdm import tqdm from me...
Megatron-LM-master
tools/bert_embedding/embed.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. from .embed import BertEmbedder, DiskDataParallelBertEmbedder
Megatron-LM-master
tools/bert_embedding/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import numpy as np import torch from megatron import get_args, get_tokenizer from megatron.data.bert_dataset import build_training_sample class BertEmbeddingDataset(torch.utils.data.Dataset): '''Dataset to convert a text dataset to Bert tokens.''' ...
Megatron-LM-master
tools/bert_embedding/dataset.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. from collections import defaultdict import glob import numpy as np import os import torch from tqdm import tqdm from megatron import print_rank_0 from megatron.core import parallel_state from .external_libs import h5py def save_data(data_map, *args): ...
Megatron-LM-master
tools/bert_embedding/utils.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import numpy as np import torch from tqdm import tqdm from .external_libs import transformers class IterableTextDataset(torch.utils.data.IterableDataset): '''Iterable over a text dataset.''' def __init__(self, text_dataset): self.text_...
Megatron-LM-master
tools/bert_embedding/huggingface.py
Megatron-LM-master
tests/__init__.py
def test_import(): import megatron
Megatron-LM-master
tests/unit_tests/test_basic.py
import pytest import torch import megatron.core.utils as util import numpy as np def test_divide_properly(): assert util.divide(4,2) == 2 def test_divide_improperly(): with pytest.raises(AssertionError): util.divide(4,5) def test_global_memory_buffer(): global_memory_buffer = util.GlobalMemoryBuf...
Megatron-LM-master
tests/unit_tests/test_utils.py
import os import torch import megatron.core.parallel_state as ps class Utils: world_size = torch.cuda.device_count() rank = int(os.environ['LOCAL_RANK']) @staticmethod def initialize_distributed(): print(f'Initializing torch.distributed with rank: {Utils.rank}, world_size: {Utils.world_size}'...
Megatron-LM-master
tests/unit_tests/test_utilities.py
Megatron-LM-master
tests/unit_tests/__init__.py
import torch import megatron.core.parallel_state as ps import pytest from tests.unit_tests.test_utilities import Utils import os rank = Utils.rank world_size = Utils.world_size def test_initialize__and_destroy_model_parallel(): with pytest.raises(AssertionError): assert(ps.initialize_model_parallel()) ...
Megatron-LM-master
tests/unit_tests/test_parallel_state.py
from megatron.core.tensor_parallel.cross_entropy import vocab_parallel_cross_entropy import torch from tests.unit_tests.test_utilities import Utils import numpy as np def test_vocab_parallel_cross_entropy(): Utils.initialize_model_parallel(4,2) vocab_parallel_logits = torch.range(0,7).repeat(16,4).cuda() t...
Megatron-LM-master
tests/unit_tests/tensor_parallel/test_cross_entropy.py
import torch import megatron.core.tensor_parallel.utils as util import megatron.core.parallel_state as ps from tests.unit_tests.test_utilities import Utils rank = Utils.rank def test_split_tensor_along_last_dim(): input_tensor = torch.rand((3,4)) torch.equal(input_tensor[0:2,0:2], util.split_tensor_along_last...
Megatron-LM-master
tests/unit_tests/tensor_parallel/test_tensor_parallel_utils.py
from megatron.core.tensor_parallel import mappings from tests.unit_tests.test_utilities import Utils import torch def test_CopyToModelParallelRegion(): Utils.initialize_model_parallel(4,2) input_data = torch.ones((1)).cuda()*Utils.rank output_data = mappings._CopyToModelParallelRegion.backward(None, input_...
Megatron-LM-master
tests/unit_tests/tensor_parallel/test_mappings.py
from megatron.core.tensor_parallel.data import broadcast_data import torch from tests.unit_tests.test_utilities import Utils def test_broadcast_data(): Utils.initialize_model_parallel(2,4) input_data = { 0 : torch.ones((8,8)).cuda() * 0.0, 1 : torch.ones((8,8)).cuda() * 1.0, 2 : torch.o...
Megatron-LM-master
tests/unit_tests/tensor_parallel/test_data.py
from megatron.core.tensor_parallel.random import CudaRNGStatesTracker from megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seed from megatron.core.tensor_parallel.random import _CUDA_RNG_STATE_TRACKER from megatron.core.tensor_parallel.random import checkpoint from tests.unit_tests.test_utilities...
Megatron-LM-master
tests/unit_tests/tensor_parallel/test_random.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import pytest import torch from megatron.core.transformer.mlp import MLP from tests.unit_tests.test_utilities import Utils from megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seed from megatron.core.transformer.transformer_config ...
Megatron-LM-master
tests/unit_tests/transformer/test_mlp.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import pytest import torch from megatron.core.transformer.module import Float16Module, MegatronModule from megatron.core.transformer.transformer_config import TransformerConfig from tests.unit_tests.test_utilities import Utils from megatron.core.tensor_p...
Megatron-LM-master
tests/unit_tests/transformer/test_module.py
Megatron-LM-master
tests/unit_tests/transformer/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import pytest import torch from megatron.core.transformer.attention import CrossAttention """ @pytest.fixture def core_attention(transformer_config): return CrossAttention(transformer_config) class TestCoreAttention: def test_constructor(sel...
Megatron-LM-master
tests/unit_tests/transformer/test_core_attention.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import os import pytest import torch from megatron.core import dist_checkpointing from megatron.core.transformer.transformer_config import TransformerConfig from megatron.core.transformer.transformer_layer import TransformerLayer from megatron.core.trans...
Megatron-LM-master
tests/unit_tests/transformer/test_transformer_block.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import pytest import torch from megatron.core.transformer.attention import SelfAttention from tests.unit_tests.test_utilities import Utils from megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seed from megatron.core.transformer.tra...
Megatron-LM-master
tests/unit_tests/transformer/test_attention.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import pytest import torch from megatron.core.transformer.transformer_config import TransformerConfig from megatron.core.transformer.transformer_layer import TransformerLayer from tests.unit_tests.test_utilities import Utils from megatron.core.tensor_pa...
Megatron-LM-master
tests/unit_tests/transformer/test_transformer_layer.py
import torch from tests.unit_tests.test_utilities import Utils from megatron.core import ModelParallelConfig import megatron.core.pipeline_parallel.schedules as schedule from pytest_mock import mocker import pytest rank = Utils.rank def test_get_forward_backward_func(): Utils.initialize_model_parallel(tensor_mo...
Megatron-LM-master
tests/unit_tests/pipeline_parallel/test_schedules.py
Megatron-LM-master
tests/unit_tests/pipeline_parallel/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import pytest import torch from megatron.core.transformer.transformer_config import TransformerConfig from megatron.core.models.gpt.gpt_model import GPTModel from tests.unit_tests.test_utilities import Utils from megatron.core.tensor_parallel.random impo...
Megatron-LM-master
tests/unit_tests/models/test_gpt_model.py
Megatron-LM-master
tests/unit_tests/models/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import pytest import torch from megatron.core.transformer.transformer_config import TransformerConfig from megatron.core.models.gpt.gpt_embedding import GPTEmbedding from tests.unit_tests.test_utilities import Utils class TestGPTEmbedding: def setu...
Megatron-LM-master
tests/unit_tests/models/test_gpt_embedding.py