# bigcode-project/megatron-lm architecture

> Architecture diagram of the GitHub repository bigcode-project/megatron-lm, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-05-17). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/bigcode-project/megatron-lm
- Repository: https://github.com/bigcode-project/megatron-lm

## Overview

##### Project type and purpose
- Megatron is an open-source, back-end framework for large-scale transformer model training.
- It focuses on efficient model-parallel (tensor, pipeline, sequence) and data-parallel distributed training of GPT, BERT, T5, and Retro.
- It provides preprocessing tools, training scripts, evaluation tasks, a text-generation server, and utilities for checkpoint management.

##### High-level file-structure analysis
- Top level:
- setup.py, .gitlab-ci.yml, LICENSE, README.md, .coveragerc – project metadata and CI config
- examples/ – shell and Python scripts showing typical workflows (pretrain, finetune, evaluate)
- docs/ – architectural and usage docs
- images/ – graphs and visuals used in README
- Core library (megatron/):
- arguments.py, initialize.py, training.py, utils.py – orchestration and launcher
- core/ – shared enums and parallel-state management
- tensor_parallel/, pipeline_parallel/ – modules for tensor and pipeline parallelism
- data/, tokenizer/ – dataset definitions and tokenizers
- model/ – transformer implementations (GPT, BERT, T5, vision, etc.)
- mpu/ – MPI-style utility for splitting weights and grads
- optimizer/ – distributed optimizer and grad-scaler
- text_generation/ + text_generation_server.py – REST API server
- Tasks (tasks/):
- main.py + subfolders: glue, race, orqa, vision, msdp, zeroshot_gpt – downstream evaluation and finetuning
- Tools (tools/):
- preprocess_data.py, openwebtext/, retro/ – data ingestion and retrieval-enhanced model support
- checkpoint_util.py – merge or reshard checkpoints
- text_generation_cli.py – client for the REST server
- Tests (tests/): unit, functional, pipeline_parallel, tensor_parallel – CI validation

##### Main components
a. Data layer
- Raw data sources (JSON text corpus)
- Preprocessing tools (tools/preprocess_data.py, tools/openwebtext, tools/retro/db/build.py)
- Indexed datasets (binary .bin/.idx)
b. Training layer
- Launcher scripts (pretrain_{bert,gpt,t5}(.sh/.py), torchrun)
- Megatron core: initialize → build model → attach optimizer → training loop
c. Model layer
- Transformer modules (megatron/model/: GPT, BERT, T5, vision)
- Tokenizer modules (megatron/tokenizer)
d. Parallelism layer
- Data parallel (gradient all-reduce via PyTorch DDP or local)
- Model parallel: tensor_parallel, pipeline_parallel, sequence_parallel
e. Checkpointing & optimizer
- Distributed optimizer (ZeRO-style)
- Activation checkpointing (selective/full)
- Checkpoint loader/saver (tools/checkpoint_loader_megatron.py)
f. Evaluation & serving
- Tasks framework (tasks/main.py + subtasks)
- REST server (megatron/text_generation_server.py)
- Client CLI (tools/text_generation_cli.py)
g. External infrastructure
- HPC scheduler (Slurm, SBATCH/SRUN in examples/)
- Container runtime (NVIDIA PyTorch Docker + NCCL, CUDA, APEX)

##### Relationships and interactions
- Data flow: Raw data → Preprocessor → Indexed dataset
- Training flow: Launcher → Megatron.initialize() → Model instantiation → Distributed group setup (NCCL/TCP) → Forward/backward passes → Optimizer step → Checkpoint save
- Comm flow:
- Tensor parallel all-reduce/collectives for weight sync
- Pipeline parallel sends/receives for microbatches
- Data parallel gradient all-reduce
- Evaluation flow: Pretrained checkpoint → tasks/main.py → task-specific data → model inference → metrics/logs
- Serving flow: Load checkpoint → spin up REST API → accept HTTP JSON → generate tokens → return response

##### Key architectural patterns and design principles
- Layered modularity: clear separation of core, model, data, tasks, and tools
- Plugin-style tasks: tasks/ directory implements downstream behavior without touching core
- High cohesion: each parallelism strategy encapsulated in its own module (tensor_parallel, pipeline_parallel)
- Extensibility: new models, tokenizers, tasks, or data formats can be plugged in
- HPC-friendly: scripts and code designed around Slurm, Docker, and multi-node PyTorch distributed

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% Data Layer
    subgraph "Data Layer"
        direction TB
        RawData["Raw Data Sources"]:::datacomponent
        Preprocess["Preprocessing Tools"]:::tools
        OpenWebText["OpenWebText Preprocessor"]:::tools
        RETRO["RETRO Preprocessor & DB Builder"]:::tools
        IndexedData["Indexed Dataset"]:::datacomponent
    end

    %% Training Layer
    subgraph "Training Layer"
        direction TB
        PretrainBERT["pretrain_bert.py"]:::tools
        PretrainGPT["pretrain_gpt.py"]:::tools
        PretrainT5["pretrain_t5.py"]:::tools
        Launcher["Launcher (torchrun, scripts)"]:::tools
        Initialize["Megatron.initialize()"]:::compute
        TrainingLoop["Core Training Loop"]:::compute
    end

    %% Model Layer
    subgraph "Model Layer"
        direction TB
        GPTModel["GPT Implementation"]:::compute
        BERTModel["BERT Implementation"]:::compute
        T5Model["T5 Implementation"]:::compute
        VisionModels["Vision Models"]:::compute
        Tokenizer["Tokenizer Modules"]:::compute
    end

    %% Parallelism Layer
    subgraph "Parallelism Layer"
        direction TB
        DataParallel["Data Parallel (DDP)"]:::parallel
        TensorParallel["Tensor Parallelism"]:::parallel
        PipelineParallel["Pipeline Parallelism"]:::parallel
        SequenceParallel["Sequence Parallelism"]:::parallel
    end

    %% Checkpointing & Optimizer
    subgraph "Checkpoint & Optimizer"
        direction TB
        Checkpointing["Checkpoint Management"]:::compute
        DistribOptimizer["Distributed Optimizer (ZeRO)"]:::compute
        CheckpointLoader["Checkpoint Loader Utility"]:::tools
    end

    %% Evaluation & Serving
    subgraph "Evaluation & Serving"
        direction TB
        TasksFramework["Tasks Framework Entry Point"]:::compute
        Downstream["Downstream Task Modules"]:::compute
        RESTServer["REST Text-Generation Server"]:::compute
        ClientCLI["Text Generation CLI"]:::tools
    end

    %% External Infrastructure
    subgraph "External Infrastructure"
        direction TB
        SlurmExamples["Slurm Scheduler Examples"]:::external
        SetupPY["setup.py & CI Config"]:::external
    end

    %% Data Flow
    RawData -->|"filesystem"| Preprocess
    Preprocess -->|"outputs bin/idx"| IndexedData

    %% Training Flow
    IndexedData -->|"load dataset"| Launcher
    Launcher -->|"calls"| Initialize
    Initialize -->|"build model"| GPTModel
    Initialize -->|"build model"| BERTModel
    Initialize -->|"build model"| T5Model
    Initialize -->|"build model"| VisionModels
    Initialize -->|"attach tokenizer"| Tokenizer
    Initialize -->|"setup groups"| DataParallel
    DataParallel --> TensorParallel
    DataParallel --> PipelineParallel
    DataParallel --> SequenceParallel
    SequenceParallel --> TrainingLoop
    TrainingLoop -->|"forward/backward"| DistribOptimizer
    DistribOptimizer -->|"save state"| Checkpointing
    Checkpointing --> CheckpointLoader

    %% Evaluation & Serving Flows
    Checkpointing -->|"load checkpoint"| TasksFramework
    TasksFramework --> Downstream
    TasksFramework -->|"inference"| GPTModel
    TasksFramework -->|"inference"| BERTModel
    TasksFramework -->|"inference"| T5Model
    TasksFramework -->|"inference"| VisionModels

    Checkpointing -->|"load checkpoint"| RESTServer
    RESTServer -->|"HTTP JSON"| ClientCLI

    %% External Usage
    SlurmExamples --> Launcher
    SetupPY -->|"env setup"| Launcher

    %% Click Events
    click Preprocess "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/tools/preprocess_data.py"
    click OpenWebText "https://github.com/bigcode-project/megatron-lm/tree/multi-query-attention/tools/openwebtext/"
    click RETRO "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/tools/retro/db/build.py"
    click IndexedData "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/megatron/data/indexed_dataset.py"
    click PretrainBERT "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/pretrain_bert.py"
    click PretrainGPT "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/pretrain_gpt.py"
    click PretrainT5 "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/pretrain_t5.py"
    click Initialize "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/megatron/initialize.py"
    click TrainingLoop "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/megatron/training.py"
    click GPTModel "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/megatron/model/gpt_model.py"
    click BERTModel "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/megatron/model/bert_model.py"
    click T5Model "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/megatron/model/t5_model.py"
    click VisionModels "https://github.com/bigcode-project/megatron-lm/tree/multi-query-attention/megatron/model/vision/"
    click Tokenizer "https://github.com/bigcode-project/megatron-lm/tree/multi-query-attention/megatron/tokenizer/"
    click TensorParallel "https://github.com/bigcode-project/megatron-lm/tree/multi-query-attention/megatron/core/tensor_parallel/"
    click PipelineParallel "https://github.com/bigcode-project/megatron-lm/tree/multi-query-attention/megatron/core/pipeline_parallel/"
    click SequenceParallel "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/megatron/core/parallel_state.py"
    click Checkpointing "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/megatron/checkpointing.py"
    click DistribOptimizer "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/megatron/optimizer/distrib_optimizer.py"
    click CheckpointLoader "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/tools/checkpoint_loader_megatron.py"
    click TasksFramework "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/tasks/main.py"
    click Downstream "https://github.com/bigcode-project/megatron-lm/tree/multi-query-attention/tasks/"
    click RESTServer "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/megatron/text_generation_server.py"
    click ClientCLI "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/tools/text_generation_cli.py"
    click SlurmExamples "https://github.com/bigcode-project/megatron-lm/tree/multi-query-attention/examples/"
    click SetupPY "https://github.com/bigcode-project/megatron-lm/blob/multi-query-attention/setup.py"

    %% Styles
    classDef datacomponent fill:#AED6F1,stroke:#1B4F72,color:#1B2631;
    classDef compute fill:#ABEBC6,stroke:#196F3D,color:#1D8348;
    classDef parallel fill:#F9E79F,stroke:#B9770E,color:#7D6608;
    classDef tools fill:#D5DBDB,stroke:#424949,color:#1C2833;
    classDef external fill:#E8DAEF,stroke:#6C3483,color:#512E5F
```
