python_code
stringlengths
0
679k
repo_name
stringlengths
9
41
file_path
stringlengths
6
149
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import json import os import sys import tempfile import requests from megatron.data.indexed_dataset import MMapIndexedDataset from megatron.tokenizer.gpt2_tokenization import ( PRETRAINED_MERGES_ARCHIVE_MAP, PRETRAINED_VOCAB_ARCHIVE_MAP, ) from t...
Megatron-LM-master
tests/unit_tests/data/test_preprocess_data.py
Megatron-LM-master
tests/functional_tests/__init__.py
import os import json import pytest import sys import glob from tensorboard.backend.event_processing import event_accumulator LOGS_DIR = os.getenv('LOGS_DIR') EXPECTED_METRICS_FILE = os.getenv('EXPECTED_METRICS_FILE') import enum class TypeOfTest(enum.Enum): APPROX = 1 DETERMINISTIC = 2 def read_tb_logs_as...
Megatron-LM-master
tests/functional_tests/python_test_utils/test_ci_pipeline.py
"""Check if a given slurm job id completed successfully Usage: python3 check_slurm_job_completion.py <JOB_ID> """ import sys import subprocess cmd = f"sacct -j {sys.argv[1]}" result = subprocess.check_output(cmd, shell=True).decode().split() assert len(result) > 14, "JOB state not available." status = res...
Megatron-LM-master
tests/functional_tests/python_test_utils/check_slurm_job_completion.py
Megatron-LM-master
tests/functional_tests/python_test_utils/__init__.py
import os os.environ['OPENBLAS_NUM_THREADS'] = '1' import sys import json import shutil import glob from tensorboard.backend.event_processing import event_accumulator LOGS_DIR = os.getenv('LOGS_DIR') def read_tb_logs_as_list(path, summary_name, index): files = glob.glob(f"{path}/events*tfevents*") files += gl...
Megatron-LM-master
tests/functional_tests/python_test_utils/test_resume_checkpoint_pipeline.py
import os os.environ['OPENBLAS_NUM_THREADS'] = '1' import sys import glob from tensorboard.backend.event_processing import event_accumulator def read_tb_logs_as_list(path, summary_name): """Reads a TensorBoard Events file from the input path, and returns the summary specified as input as a list. Argument...
Megatron-LM-master
tests/functional_tests/python_test_utils/get_test_results_from_tensorboard_logs.py
# coding=utf-8 # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. """Sample Generate GPT""" import json import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir))) import torch from megatron im...
Megatron-LM-master
examples/detxoify_lm/generate_samples_gpt.py
# coding=utf-8 # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. """Fine-tune GPT""" import torch from functools import partial import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir))) fro...
Megatron-LM-master
examples/detxoify_lm/finetune_gpt.py
import json import time from typing import Dict, Optional, List import joblib from googleapiclient import discovery from googleapiclient.errors import HttpError import argparse from tqdm import tqdm parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--data-path', type=str, d...
Megatron-LM-master
examples/detxoify_lm/perspective_api.py
import json import time from typing import Dict, Optional, List import joblib from googleapiclient import discovery from googleapiclient.errors import HttpError import argparse from tqdm import tqdm parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--data-path', type=str, d...
Megatron-LM-master
examples/detxoify_lm/annotations/perspective_api_annotate.py
import json import time from typing import Dict, Optional, List import joblib from googleapiclient import discovery from googleapiclient.errors import HttpError import argparse from tqdm import tqdm parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--data-path', type=str, d...
Megatron-LM-master
examples/detxoify_lm/annotations/filter-selfgeneration.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import torch # A dictionary of all the memory buffers allocated. _MEM_BUFFS = dict() def allocate_mem_buff(name, numel, dtype, track_usage): """Allocate a memory buffer.""" assert name not in _MEM_BUFFS, \ 'memory buffer {} already all...
Megatron-LM-master
megatron/memory.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Megatron initialization.""" import random import os import time import numpy as np import torch from datetime import timedelta from megatron import fused_kernels from megatron import get_adlr_autoresume from megatron import get_args from megatron imp...
Megatron-LM-master
megatron/initialize.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. """Megatron arguments.""" import argparse import dataclasses import json import os import torch import types import torch.nn.functional as F from megatron.global_vars import set_retro_args, get_retro_args from tools.retro.utils import get_args_path as ge...
Megatron-LM-master
megatron/arguments.py
import signal import torch def get_world_size(): if torch.distributed.is_available() and torch.distributed.is_initialized(): world_size = torch.distributed.get_world_size() else: world_size = 1 return world_size def get_device(local_rank=None): backend = torch.distributed.get_backen...
Megatron-LM-master
megatron/dist_signal_handler.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import torch from .global_vars import get_args, get_retro_args from .global_vars import get_current_global_batch_size from .global_vars import get_num_microbatches from .global_vars import get_signal_handler from .global_vars import update_num_microbatche...
Megatron-LM-master
megatron/__init__.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import datetime import torch import json import threading from flask import Flask, request, jsonify, current_app from flask_restful import Resource, Api from megatron import get_args from megatron.text_generation import generate_and_post_process from megatr...
Megatron-LM-master
megatron/text_generation_server.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Learning rate decay and weight decay incr functions.""" import math from megatron import print_rank_0 class OptimizerParamScheduler(object): """Anneals learning rate and weight decay""" def __init__(self, optimizer, init_lr, max_lr, min_lr, ...
Megatron-LM-master
megatron/optimizer_param_scheduler.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """General utilities.""" import sys import torch try: from apex.multi_tensor_apply import multi_tensor_applier except ImportError: multi_tensor_applier = None try: import amp_C except ImportError: amp_C = None from megatron import ( ...
Megatron-LM-master
megatron/utils.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Megatron number of micro-batches calculators.""" from abc import ABC from abc import abstractmethod def build_num_microbatches_calculator(args): # Constant num micro-batches. if args.rampup_batch_size is None: num_microbatches_calcul...
Megatron-LM-master
megatron/microbatches.py
import sys import time import torch import torch.distributed as dist from megatron import get_args, print_rank_0 from megatron.core import mpu from megatron.checkpointing import load_biencoder_checkpoint from megatron.data.orqa_wiki_dataset import get_open_retrieval_wiki_dataset from megatron.data.orqa_wiki_dataset im...
Megatron-LM-master
megatron/indexer.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Megatron timers.""" from abc import ABC from abc import abstractmethod import time import torch class TimerBase(ABC): def __init__(self, name): self.name = name @abstractmethod def start(self, barrier=False): pass ...
Megatron-LM-master
megatron/timers.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. """Pretrain utilities.""" from datetime import datetime import math import sys import time # The earliest we can measure the start time. _TRAIN_START_TIME = time.time() import torch from megatron import get_args from megatron import get_signal_handler fr...
Megatron-LM-master
megatron/training.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Megatron global variables.""" import os import sys import torch from megatron import dist_signal_handler from megatron.tokenizer import build_tokenizer from .microbatches import build_num_microbatches_calculator from .timers import Timers _GLOBAL_ARG...
Megatron-LM-master
megatron/global_vars.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. """Input/output checkpointing.""" import os import random import sys import numpy as np import torch from megatron import update_num_microbatches from megatron.core import mpu, tensor_parallel from .global_vars import get_args from .utils import (unwrap...
Megatron-LM-master
megatron/checkpointing.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Generation utilities.""" import torch import torch.nn.functional as F from megatron import get_args, get_tokenizer from megatron.core import mpu from megatron.utils import get_ltor_masks_and_position_ids from .communication import ( copy_from_last...
Megatron-LM-master
megatron/text_generation/generation.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors, Facebook AI Research authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the L...
Megatron-LM-master
megatron/text_generation/beam_utils.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. from .api import ( generate, generate_and_post_process, beam_search_and_post_process)
Megatron-LM-master
megatron/text_generation/__init__.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Tokenization utilities.""" import torch from megatron import get_tokenizer, get_args from .communication import broadcast_int_list, broadcast_tensor def detokenize_generations(tokens_gpu_tensor, lengths_gpu_tensor, ...
Megatron-LM-master
megatron/text_generation/tokenization.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Forward step utilities.""" from collections.abc import Iterable import torch from megatron import get_args from megatron.core import mpu, InferenceParams from .communication import ( send_to_next_pipeline_rank, recv_from_prev_pipeline_rank_) ...
Megatron-LM-master
megatron/text_generation/forward_step.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Inference API.""" import torch from megatron.core import mpu from .communication import broadcast_float_list from .generation import ( generate_tokens_probs_and_return_on_first_stage, score_and_return_on_first_stage, beam_sear...
Megatron-LM-master
megatron/text_generation/api.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Communications utilities.""" import torch from megatron.core import mpu # TODO: use functions from megatron/p2p def recv_from_prev_pipeline_rank_(recv_buffer=None): """Receive from previous pipeline stage and update the input buffer inplac...
Megatron-LM-master
megatron/text_generation/communication.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Sampling utilities. Part of this code is inspired by: - https://github.com/ari-holtzman/degen/blob/master/gen.py - https://huggingface.co/transformers/_modules/transformers/generation_logits_process.html """ import torch def modify_logits_for_top...
Megatron-LM-master
megatron/text_generation/sampling.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. from commons import set_random_seed from commons import IdentityLayer from commons import print_separator from commons import initialize_distributed from mpu.cross_entropy import vocab_parallel_cross_entropy import mpu import torch.nn.functional as F impor...
Megatron-LM-master
megatron/mpu/tests/test_cross_entropy.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. from mpu import layers from commons import set_random_seed from commons import print_separator from commons import initialize_distributed import mpu from torch.nn.parameter import Parameter import torch.nn.init as init import torch import random import sys...
Megatron-LM-master
megatron/mpu/tests/test_layers.py
Megatron-LM-master
megatron/mpu/tests/__init__.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import argparse import os import random import numpy import torch import mpu class IdentityLayer(torch.nn.Module): def __init__(self, size, scale=1.0): super(IdentityLayer, self).__init__() self.weight = torch.nn.Parameter(scale * to...
Megatron-LM-master
megatron/mpu/tests/commons.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. from commons import print_separator from commons import initialize_distributed from mpu import data as data_utils import mpu import torch import functools import operator import sys sys.path.append("../..") def test_broadcast_data(tensor_model_parallel_s...
Megatron-LM-master
megatron/mpu/tests/test_data.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. from commons import print_separator from commons import initialize_distributed import mpu import torch import sys sys.path.append("../..") def test_initialize_model_parallel(tensor_model_parallel_size): if torch.distributed.get_rank() == 0: ...
Megatron-LM-master
megatron/mpu/tests/test_initialize.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. from commons import print_separator from commons import initialize_distributed import mpu import torch import sys sys.path.append("../..") def test_set_cuda_rng_state(tensor_model_parallel_size): if torch.distributed.get_rank() == 0: print('...
Megatron-LM-master
megatron/mpu/tests/test_random.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. from dataclasses import dataclass from typing import Callable, Optional import torch @dataclass class ModelParallelConfig: """Base configuration for Megatron Core Model Parallelism ----------------- tensor_model_parallel_size (int): In...
Megatron-LM-master
megatron/core/model_parallel_config.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. MAJOR = 0 MINOR = 4 PATCH = 0 PRE_RELEASE = 'rc0' # Use the following formatting: (major, minor, patch, pre-release) VERSION = (MAJOR, MINOR, PATCH, PRE_RELEASE) __shortversion__ = '.'.join(map(str, VERSION[:3])) __version__ = '.'.join(map(str, VERSION...
Megatron-LM-master
megatron/core/package_info.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import enum class ModelType(enum.Enum): encoder_or_decoder = 1 encoder_and_decoder = 2 retro_encoder = 3 retro_decoder = 4
Megatron-LM-master
megatron/core/enums.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Model and data parallel groups.""" import os from typing import Optional import torch from .utils import GlobalMemoryBuffer # Intra-layer model parallel group that the current rank belongs to. _TENSOR_MODEL_PARALLEL_GROUP = None # Inter-layer model ...
Megatron-LM-master
megatron/core/parallel_state.py
import megatron.core.parallel_state import megatron.core.tensor_parallel import megatron.core.utils from .inference_params import InferenceParams from .model_parallel_config import ModelParallelConfig # Alias parallel_state as mpu, its legacy name mpu = parallel_state __all__ = ["parallel_state", "tensor_parallel", ...
Megatron-LM-master
megatron/core/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. """Utility functions used throughout Megatron core""" import math import operator from functools import reduce import torch from megatron.core import parallel_state from megatron.core.dist_checkpointing.mapping import ShardedTensor def ensure_divisibil...
Megatron-LM-master
megatron/core/utils.py
class InferenceParams: """Inference parameters that are passed to the main model in order to efficienly calculate and store the context during inference.""" def __init__(self, max_batch_size, max_sequence_length): self.max_sequence_length = max_sequence_length self.max_batch_size = max_batc...
Megatron-LM-master
megatron/core/inference_params.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import importlib import numbers import torch from torch.nn import init from torch.nn.parameter import Parameter from megatron.core.utils import make_viewless_tensor try: from apex.contrib.layer_norm.layer_norm import FastLayerNormFN HAVE_PERSIS...
Megatron-LM-master
megatron/core/fusions/fused_layer_norm.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import torch import torch.nn as nn from megatron.core.transformer.enums import AttnMaskType class ScaledUpperTriangMaskedSoftmax(torch.autograd.Function): """ Fused operation which performs following three operations in sequence 1. Scale th...
Megatron-LM-master
megatron/core/fusions/fused_softmax.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. from typing import Optional, Tuple import torch def _bias_dropout_add_func(x, bias, residual, prob, training): # type: (Tensor, Optional[Tensor], Tensor, float, bool) -> Tensor # NOTE: Previously, the argument `bias` used to be passed as # `...
Megatron-LM-master
megatron/core/fusions/fused_bias_dropout.py
Megatron-LM-master
megatron/core/fusions/__init__.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import torch ###### BIAS GELU FUSION/ NO AUTOGRAD ################ # 1/sqrt(2*pi)-> 0.3989423 # 1/sqrt(2) -> 0.70710678 # sqrt(2/pi) -> 0.79788456 # this function is tanh approximation of gelu # actual gelu is: # x * 0.5 * (1.0 + torch.erf(x * 0.707106...
Megatron-LM-master
megatron/core/fusions/fused_bias_gelu.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import torch from megatron.core.parallel_state import ( get_tensor_model_parallel_group, get_tensor_model_parallel_rank, get_tensor_model_parallel_world_size, ) from .utils import VocabUtility class _VocabParallelCrossEntropy(torch.autograd...
Megatron-LM-master
megatron/core/tensor_parallel/cross_entropy.py
from .cross_entropy import vocab_parallel_cross_entropy from .data import broadcast_data from .layers import ( ColumnParallelLinear, RowParallelLinear, VocabParallelEmbedding, copy_tensor_model_parallel_attributes, linear_with_grad_accumulation_and_async_allreduce, param_is_not_tensor_parallel_d...
Megatron-LM-master
megatron/core/tensor_parallel/__init__.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # Parts of the code here are adapted from PyTorch # repo: https://github.com/pytorch/pytorch import contextlib import torch from torch import _C from torch.cuda import _lazy_call from torch.cuda import device as device_ctx_manager from torch.utils.checkp...
Megatron-LM-master
megatron/core/tensor_parallel/random.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. from typing import List, Sequence import torch from megatron.core import parallel_state from megatron.core.utils import divide def split_tensor_along_last_dim( tensor: torch.Tensor, num_partitions: int, contiguous_split_chunks: bool = False, ) -> L...
Megatron-LM-master
megatron/core/tensor_parallel/utils.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # Parts of the code here are adapted from PyTorch # repo: https://github.com/pytorch/pytorch import math import os import warnings from typing import Callable, Optional import torch import torch.nn.functional as F import torch.nn.init as init from torch....
Megatron-LM-master
megatron/core/tensor_parallel/layers.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import torch from megatron.core.parallel_state import ( get_tensor_model_parallel_group, get_tensor_model_parallel_rank, get_tensor_model_parallel_src_rank, ) _MAX_DATA_DIM = 5 def _check_data_types(keys, data, target_dtype): """Check t...
Megatron-LM-master
megatron/core/tensor_parallel/data.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import torch from megatron.core.parallel_state import ( get_tensor_model_parallel_group, get_tensor_model_parallel_rank, get_tensor_model_parallel_world_size, ) from .utils import split_tensor_along_last_dim def _reduce(input_): """All-...
Megatron-LM-master
megatron/core/tensor_parallel/mappings.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import re from contextlib import nullcontext import torch from megatron.core import parallel_state, tensor_parallel from megatron.core.fusions.fused_layer_norm import FusedLayerNorm from megatron.core.transformer.custom_layers.transformer_engine import T...
Megatron-LM-master
megatron/core/transformer/transformer_block.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. from dataclasses import dataclass from typing import Callable import torch import torch.nn.functional as F from megatron.core import ModelParallelConfig from megatron.core.utils import init_method_normal, scaled_init_method_normal @dataclass class Tran...
Megatron-LM-master
megatron/core/transformer/transformer_config.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. from abc import ABC, abstractmethod import torch from megatron.core import parallel_state, tensor_parallel from megatron.core.models.common.rotary_pos_embedding import apply_rotary_pos_emb from megatron.core.transformer.custom_layers.transformer_engine i...
Megatron-LM-master
megatron/core/transformer/attention.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import enum # can we get rid of this? # it's being used in pipeline schedules class ModelType(enum.Enum): encoder_or_decoder = 1 encoder_and_decoder = 2 # class LayerType(enum.Enum): # encoder = 1 # decoder = 2 class AttnType(enum.Enu...
Megatron-LM-master
megatron/core/transformer/enums.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. from .transformer_config import TransformerConfig
Megatron-LM-master
megatron/core/transformer/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import re import torch from megatron.core import parallel_state from megatron.core.dist_checkpointing.mapping import ShardedObject, ShardedTensor from megatron.core.fusions.fused_bias_dropout import get_bias_dropout_add from megatron.core.transformer.att...
Megatron-LM-master
megatron/core/transformer/transformer_layer.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import torch import torch.nn.functional as F from megatron.core import tensor_parallel from megatron.core.fusions.fused_bias_gelu import bias_gelu_impl from megatron.core.transformer.custom_layers.transformer_engine import ( TELayerNormColumnParallelL...
Megatron-LM-master
megatron/core/transformer/mlp.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import math import torch from torch import Tensor from megatron.core import parallel_state, tensor_parallel from megatron.core.fusions.fused_softmax import FusedScaleMaskSoftmax from megatron.core.transformer.enums import AttnMaskType from megatron.core...
Megatron-LM-master
megatron/core/transformer/dot_product_attention.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Utilities for transformer layers.""" import torch from megatron import get_args def attention_mask_func(attention_scores, attention_mask): attention_scores.masked_fill_(attention_mask, -10000.0) return attention_scores def get_linear_layer...
Megatron-LM-master
megatron/core/transformer/utils.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import torch class IdentityOp(torch.nn.Module): """ This is a placeholder for IdentityOp (NoOp) """ def __init__(self, *args, **kwargs): super(IdentityOp, self).__init__() def forward(self, x, *args, **kwargs): return...
Megatron-LM-master
megatron/core/transformer/identity_op.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. """Megatron Module""" import torch from torch.autograd import Variable from torch.nn.parameter import Parameter from megatron.core import parallel_state, tensor_parallel from megatron.core.transformer.transformer_config import TransformerConfig _FLOAT_T...
Megatron-LM-master
megatron/core/transformer/module.py
from importlib.metadata import version from typing import Callable import torch import transformer_engine as te from pkg_resources import packaging from megatron.core.parallel_state import get_tensor_model_parallel_group from megatron.core.tensor_parallel import get_cuda_rng_tracker from megatron.core.transformer.enu...
Megatron-LM-master
megatron/core/transformer/custom_layers/transformer_engine.py
from .schedules import get_forward_backward_func
Megatron-LM-master
megatron/core/pipeline_parallel/__init__.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import contextlib from typing import Callable, Iterator, List, Optional, Union import torch from torch.autograd.variable import Variable from torch.nn.parallel.distributed import DistributedDataParallel as torchDDP from megatron import core from megatron...
Megatron-LM-master
megatron/core/pipeline_parallel/schedules.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import operator from functools import reduce from typing import Callable, List, Optional, Tuple, Union import torch from megatron import core from megatron.core import ModelParallelConfig from megatron.core.parallel_state import ( get_pipeline_model_...
Megatron-LM-master
megatron/core/pipeline_parallel/p2p_communication.py
Megatron-LM-master
megatron/core/models/__init__.py
from .gpt_model import GPTModel
Megatron-LM-master
megatron/core/models/gpt/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import logging from typing import Literal, Optional import torch from torch import Tensor from megatron.core import parallel_state, tensor_parallel from megatron.core.models.common.rotary_pos_embedding import RotaryEmbedding from megatron.core.models.gpt...
Megatron-LM-master
megatron/core/models/gpt/gpt_model.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import torch from megatron.core import tensor_parallel from megatron.core.transformer.module import MegatronModule from megatron.core.transformer.transformer_config import TransformerConfig from megatron.core.utils import ( make_sharded_tensor_for_che...
Megatron-LM-master
megatron/core/models/gpt/gpt_embedding.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. import importlib.util import torch from torch import einsum, nn __all__ = ['RotaryEmbedding', 'apply_rotary_pos_emb'] class RotaryEmbedding(nn.Module): def __init__(self, dim, seq_len_interpolation_factor=None): super().__init__() s...
Megatron-LM-master
megatron/core/models/common/rotary_pos_embedding.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. """ Utilities for operating with dicts and lists. """ from collections import defaultdict from typing import Any, Callable, Iterable, Optional, Tuple, Union import torch def extract_matching_values( x: Union[dict, list], predicate: Callable )...
Megatron-LM-master
megatron/core/dist_checkpointing/dict_utils.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. from .core import check_is_distributed_checkpoint from .mapping import LocalNonpersitentObject, ShardedTensor from .serialization import load, load_common_state_dict, save
Megatron-LM-master
megatron/core/dist_checkpointing/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. import json from dataclasses import asdict, dataclass from pathlib import Path from typing import Optional CONFIG_FNAME = 'metadata.json' class CheckpointingException(Exception): pass @dataclass class CheckpointingConfig: """ Documents b...
Megatron-LM-master
megatron/core/dist_checkpointing/core.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. from typing import Tuple from .dict_utils import dict_list_map_inplace, extract_matching_values from .mapping import LocalNonpersitentObject, ShardedStateDict, ShardedTensor, StateDict def extract_sharded_tensors( sharded_state_dict: ShardedSt...
Megatron-LM-master
megatron/core/dist_checkpointing/utils.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. """ Optimizer related helpers. """ import logging from copy import deepcopy from dataclasses import replace from itertools import chain from typing import Dict, Iterable, List logger = logging.getLogger(__name__) import torch from .dict_utils imp...
Megatron-LM-master
megatron/core/dist_checkpointing/optimizer.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. """ Core library classes. """ from dataclasses import dataclass, replace from itertools import chain from typing import Any, Dict, Optional, Tuple, Union import numpy as np import torch from .core import CheckpointingException # These type defini...
Megatron-LM-master
megatron/core/dist_checkpointing/mapping.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. import logging import os from collections import Counter, defaultdict from itertools import chain from pathlib import Path from typing import Iterable, List, Tuple, Union import numpy as np import torch from .core import CheckpointingConfig, maybe_...
Megatron-LM-master
megatron/core/dist_checkpointing/serialization.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. """ Various loading and saving strategies """ import logging logger = logging.getLogger(__name__) try: import tensorstore import zarr from .tensorstore import _import_trigger from .zarr import _import_trigger except ImportError: ...
Megatron-LM-master
megatron/core/dist_checkpointing/strategies/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. """ 2-stage checkpoint loading. """ import os import time from collections import defaultdict from dataclasses import dataclass from functools import partial, wraps from itertools import chain from logging import DEBUG, INFO, StreamHandler, getLogger...
Megatron-LM-master
megatron/core/dist_checkpointing/strategies/two_stage.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. """ Strategies using Zarr as an underlying format. """ import os from functools import partial from pathlib import Path from typing import List import numpy as np import torch import zarr from ..core import CheckpointingException from ..dict_utils ...
Megatron-LM-master
megatron/core/dist_checkpointing/strategies/zarr.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. from abc import ABC, abstractmethod from collections import defaultdict from enum import Enum from pathlib import Path from typing import Dict, List, Optional from ..mapping import CheckpointingException, ShardedStateDict, ShardedTensor, StateDict ...
Megatron-LM-master
megatron/core/dist_checkpointing/strategies/base.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. """ Strategies using TensorStore to load and save Zarr arrays. """ from functools import partial from itertools import starmap from pathlib import Path import tensorstore as ts import torch from ..core import CheckpointingException from ..dict_uti...
Megatron-LM-master
megatron/core/dist_checkpointing/strategies/tensorstore.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Gradient clipping.""" import os import torch from torch import inf from apex.multi_tensor_apply import multi_tensor_applier import amp_C from megatron.model.module import param_is_not_shared from megatron.core.tensor_parallel import param_is_not_ten...
Megatron-LM-master
megatron/optimizer/clip_grads.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """Megatron grad scaler.""" from abc import ABC from abc import abstractmethod import torch class MegatronGradScaler(ABC): def __init__(self, initial_scale): """Initialize scale value with the input initial scale.""" assert initial...
Megatron-LM-master
megatron/optimizer/grad_scaler.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. from apex.optimizers import FusedAdam as Adam from apex.optimizers import FusedSGD as SGD from megatron import get_args from .distrib_optimizer import DistributedOptimizer from .grad_scaler import ConstantGradScaler, DynamicGradScaler from .optimizer imp...
Megatron-LM-master
megatron/optimizer/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. """Megatron distributed optimizer.""" from apex.optimizers import FusedAdam as Adam import math import torch from megatron import get_args from megatron import get_timers from megatron import print_rank_0 from megatron.core import mpu, tensor_parallel f...
Megatron-LM-master
megatron/optimizer/distrib_optimizer.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. """Megatron optimizer.""" from abc import ABC from abc import abstractmethod from apex.multi_tensor_apply import multi_tensor_applier import amp_C import torch from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors from megatron import...
Megatron-LM-master
megatron/optimizer/optimizer.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # 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 ...
Megatron-LM-master
megatron/tokenizer/bert_tokenization.py
# coding=utf-8 # Copyright 2018 The Open AI Team Authors and The HuggingFace 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/LICENSE-2.0 # # ...
Megatron-LM-master
megatron/tokenizer/gpt2_tokenization.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. from .tokenizer import build_tokenizer
Megatron-LM-master
megatron/tokenizer/__init__.py