aquachieh
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # [2025李宏毅ML] 助教課:利用多張GPU訓練大型語言模型—從零開始介紹DeepSpeed、Liger Kernel、Flash Attention及Quantization :::success :+1: 筆記全集Book 請至: https://hackmd.io/@4j/r1U_UJ_pye/ ::: :::info 2025生成式AI時代下的機器學習_李宏毅 課程網站 https://speech.ee.ntu.edu.tw/~hylee/ml/2025-spring.php video: https://youtu.be/mpuRca2UZtI?si=GQu-6l4WENr-5zqQ [[Excalidraw]](https://drive.google.com/file/d/1pKgY4EuyXh7SuTbI_r7it1CK5DCFUKYZ/view) ▪ Instructor Hsiu-Hsuan Wang(王秀軒) Find more at https://anthony-wss.github.io/ (20250329) ::: :::spoiler 目錄 [TOC] ::: ![image](https://hackmd.io/_uploads/SkxsXNzJee.png) ## Overview ![image](https://hackmd.io/_uploads/ryN3QEMkgx.png) 在 LLM 時代,一般 pytorch 訓練 NN 的方法會無法訓練 可利用以下 package (場景) 1. **DeepSpeed**: 多張 GPU 平行運算 2. **Liger Kernel, Flash Attention**: 輸入 context 太長 ex: 32k 128k 3. **Quantization**: 如想用 colab 跑作業時 ## Introduction ### 1. Forward & Backward pass ![image](https://hackmd.io/_uploads/r1lC7VGJlx.png) ▪ **LLM訓練為什麼大** ``` cross entropy (output, label)算loss 再 backpropagation 推到輸入 得到 gradient 經由 optimizer 更新 weights ``` 訓練上困難 主要是 **"LLM weights"** 很大! ### 2. Memory needed, assuming LLM is a 8b model ![image](https://hackmd.io/_uploads/HypR7VMkex.png) ▪ **要訓練8B模型** fp32: 一個float=32bit, 就需要 32GB 在訓練時, 常轉成fp16 (nv對fp16也有特別加速) ▪ **adam** 他的設計是每個權重都有個 lr, 故 momentum 跟 variance 大小同 w gradients 作為輸入 更新w ⇒ 儲存空間(不含input)全部加起來為 128GB!!! 但 **input** 才是佔最多的 ### 3. Activations ![image](https://hackmd.io/_uploads/H1ukVVfylg.png) ▪ **activation**: 模型每層對 input 產生的反應 "attention" 在其中佔最大, 空間複雜度為 n平方 ▪ **3.1 Activation recomputation (gradient checkpointion)** 訓練時不把 activation 都存下來, **存重要的就好**, 在 backward 需要時再算(訓練時會慢一點) ### 4. Batch size ![image](https://hackmd.io/_uploads/rkm2LVfkgx.png) Batch size 要夠大才不會有 bias 基本上要 4-60M token (DeepSeek V3: bz=1920) 解法: **Gradient accumulation** 把1920切小批 都過完後再一起合併更新 ### 5. Challenges ![image](https://hackmd.io/_uploads/HyyTI4fJee.png) (紫紅綠) para,grad,opti 在不同輸入長度時的 memory 會是一樣大小 只有 **activations** 會依輸入長度指數型增長 memory ## Part I. parameters, gradients and optimizer states ### 1. How to leverage multiple GPUs? ![image](https://hackmd.io/_uploads/ryrMNVGJge.png) (16/32 bit 對應到前2的圖) 一個GPU放不下, 就分到多個去運算 ### 2. DeepSpeed - Zero Redundancy Optimizer (ZeRO) ![image](https://hackmd.io/_uploads/ryg44VGkee.png) DeepSpeed的套件 他使用 **Zero Redundancy Optimizer (ZeRO)** 演算法 ▪ **3 個 Level** -zero1: opt 佔最大先切分他, 會多一些GPU間的傳輸 -zero2: 再切第二大的部分 grad, LLM -zero3: 再切 LLM (會從32bit 開始切是因為他們 佔體大 且 用到的時間較少) 其實GPU間傳輸是很快的, 如NVLink: 900GB/s ### 3. Memory Reduction ![image](https://hackmd.io/_uploads/BJj4NNGkee.png) DP=8 切八片, 虛線: H100 為 80GB 橘色不會減少, 紫紅綠依序縮小八倍 若使用 zero3, 就可訓練到16k長度的8B模型 :D ▪ **3.1 Traning Speed** 速度還取決於 network bandwidth, model size,...等 但這些都不至於慢太多~ ### 4. Zero - Offload ![image](https://hackmd.io/_uploads/BkmBVNGklg.png) 用了 Zero 還是放不下的話, 借用 CPU 運算 ▪ **4.1 optimizer offload** 把跟 opt 相關的部分都搬到 CPU ▪ **4.2 optimizer + model parameter offload** 全部都搬到 CPU, 要用時再搬過來 GPU 做 但是 CPU GPU間的傳輸是很慢的!! 訓練會變非常慢 ### 5. Simple Experiment on TWCC(國網中心) ![image](https://hackmd.io/_uploads/SkRrVNMygg.png) 實驗有多慢 ``` V100(32G)*4 → 128G input開很小: bz=1, max_len=512 ``` 實測 1GPU 需要 15GB, 1 step 要 74 秒 (非 常 慢) 如果有 8張GPU 就裝得下 不用跑offload, 變 7.3 秒 快了 10 倍 ▪ **結論** 使用 8張V100 是可以做到 fully finetuning 8B的模型, 速度約 7.3 s/step 盡量不要使用 offload 慢 不好用 ## Part II. activations 想改善attention計算的效率 ⇒ 重寫實作的 code ### 1. kernel ![image](https://hackmd.io/_uploads/S1UU4Vfygg.png) Kernel: 跑在 GPU 上的 function ### 2. Flash Attention Algorithm ![image](https://hackmd.io/_uploads/r1lPVEGyll.png) Flash Attention Algorithm (做一個新kernel function) 算得更快 又更少記憶體 (會佔到CPU RAM) ▪ **2.1.1 Fused Kernel** 右圖可發現在attention裡矩陣乘法並不是佔最久的 反而是dropout, softmax,mask ![image](https://hackmd.io/_uploads/SJcv44f1ge.png) ▪ **2.2 Memory** 主要都放在 CPU, 要計算時才放到 GPU ▪ **2.3 Performance** H100上 不同方法實作的速度 ### 3. Liger Kernel ![image](https://hackmd.io/_uploads/rJEd4Nzkll.png) `Liger: [音]賴ger` 是用 Triton 實作的加速套件 用法簡單直接改載入的方式即可 速度記憶體皆有優化 ## Part III. Quantization Quantization 僅用在 inference ### 1. Lossy compression ![image](https://hackmd.io/_uploads/ryGF4EMJxg.png) 壓縮後再還原, 用壓縮過後的儲存, 要計算時再還原 常見的演算法: GGML family,... Q8: 指把每個tensor壓到8 bit儲存 ## Take away You may need packages like DeepSpeed, Flash Attention, or Liger Kernel to train LLM with multiple gpus and limited memory. ### Recommended Reading - https://huggingface.co/spaces/nanotron/ultrascale-playbook - https://huggingface.co/docs/transformers/deepspeed -- END --

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully