TorchScale

repository·main·Indexed 25 days ago

https://github.com/microsoft/torchscale

A PyTorch library for efficiently scaling Transformer architectures. It provides implementations of research-driven architectures including DeepNet, RetNet, LongNet, and X-MoE to enhance the stability, generality, capability, and efficiency of foundation models. The library includes integration with FairSeq and examples for training dense and sparse (MoE) BERT, GPT, and machine translation models, as well as LongViT for large-scale image processing.

Tokens
9.5K
Snippets
19
Records
26
Agent score
84%

What's inside TorchScale

  1. Install TorchScale

    main

    You can install TorchScale via pip:

    pip install torchscale

    To develop locally, clone the repository and install in editable mode:

    git clone https://github.com/microsoft/torchscale.git
    cd torchscale
    pip install -e .
    pip install torchscale
  2. Setup LongViT for TCGA Survival Prediction

    main

    To prepare the dataset for LongViT fine-tuning on TCGA survival prediction, follow these steps:

    1. Organize WSIs: Download TCGA diagnostic whole slides from the NIH Genomic Data Commons Data Portal and organize them in a directory structure.
    2. Download Annotations: Obtain the dataset annotation CSV and cross-validation splits from the MCAT repository.
    3. Generate Index: Create index JSON files for each split using create_tcga_survival_index.py.
    4. Resize Images: Resize whole slide images (WSIs) to your target size using convert_wsi_to_images.py.
    5. Split Large Images (Optional): For very large images (e.g., 32,768x32,768), use split_to_small_images.py to parallelize training across multiple GPUs by splitting the sequence of patches along the sequence dimension.
  3. Setup LongViT environment

    main

    To set up the environment for LongViT, install the required dependencies, a specific version of fairseq, and xformers using the following commands:

    pip install -r requirements.txt
    pip install git+https://github.com/shumingma/fairseq.git@moe
    pip install -v -U git+https://github.com/facebookresearch/xformers.git@v0.0.20#egg=xformers
  4. Prepare data for BERT Pretraining

    main

    BERT pretraining requires a sharded data format managed by a streaming dataloader.

    Directory Structure:

    Data/
    ├── json/
    │   ├── train.json
    │   └── valid.json
    ├── shard/
    │   ├── train/
    │   │   ├── 00000.txt
    │   │   └── ...
    │   └── valid/
    │       ├── 00000.txt
    │       └── ...
    ├── dict.txt
    └── sentencepiece.bpe.model

    Shard File Format: Each shard should contain no more than 10K lines. One sentence per line, with an empty line separating documents.

    JSON Metadata Format:

    [
        {
            "source": [
                "shard/train/00000.txt",
                "shard/train/00001.txt"
            ],
            "source_lang": "en",
            "weight": 1.0
        }
    ]

    Extracting dict.txt from a SentencePiece model:

    spm_export_vocab --model=sentencepiece.bpe.model | sed 's/\t/ /g' | tail -n +4 > dict.txt
  5. Setup TorchScale integration with FairSeq

    main

    To use TorchScale with FairSeq, install the repository as an editable package and install the required dependencies including a specific version of FairSeq and Infinibatch.

    # Install the repo as a package:
    git clone https://github.com/microsoft/torchscale.git
    cd torchscale
    pip install -e .
    pip install git+https://github.com/shumingma/fairseq.git@moe
    pip install git+https://github.com/shumingma/infinibatch.git
    pip install iopath
    pip install numpy==1.23.0
  6. Setup data for LongViT TCGA Subtyping fine-tuning

    main

    To prepare the TCGA dataset for LongViT fine-tuning, follow these steps:

    1. Organize WSIs: Download TCGA diagnostic whole slides from the NIH Genomic Data Commons Data Portal and organize them in a directory.
    2. Download Annotations: Obtain the dataset annotation CSV and cross-validation splits from the HIPT repository.
    3. Generate Index: Run data_preprocessing/create_tcga_subtyping_index.py to generate index JSON files for each split.
    4. Resize Images: Use data_preprocessing/convert_wsi_to_images.py to resize whole slide images to your target size.
    5. Handle Large Images (Optional): For very large images (e.g., 32,768x32,768), use data_preprocessing/split_to_small_images.py to split the sequence of patches along the sequence dimension across multiple GPUs (--num_splits).
    6. Image Augmentation (Optional): For large images, use data_preprocessing/cache_transformed_images.py to perform augmentation and cache the results for each epoch to improve performance.
  7. Pretrain LongViT using DINO

    main

    Self-supervised pretraining can be performed on TCGA diagnostic slides using the DINO objective. For detailed instructions, refer to the get_started_for_tcga_pretraining.md guide.

    Pretrained Model Weights: You can download the pretrained LongViT model (trained on TCGA diagnostic slides) here:

    Model Configuration:

    • #layer=12
    • hidden=384
    • FFN factor=4x
    • #head=16
    • patch=32x32
  8. Generate 1024x1024 crops from WSIs

    main

    To prepare data for LongViT pretraining, you can generate 1,024x1,024 regions from Whole Slide Images (WSIs). Use the data_preprocessing/generate_1024_crops.py script, specifying the source WSI directory, the destination crops directory, and the number of regions to generate per image.

    # we randomly generate 100 small regions for each whole slide image
    python data_preprocessing/generate_1024_crops.py /path/to/your_WSIs /path/to/your_crops 100
  9. Install Flash Attention or xFormers for faster training

    main

    For faster training on Turing, Ampere, Ada, or Hopper GPUs, install Flash Attention:

    pip install flash-attn

    Alternatively, install xFormers based on your CUDA version:

    CUDA 11.8:

    pip3 install -U xformers --index-url https://download.pytorch.org/whl/cu118

    CUDA 12.1:

    pip3 install -U xformers --index-url https://download.pytorch.org/whl/cu121
    pip install flash-attn