【Karapathy大神build-nanogpt】Take Away Notes

B站翻譯LINK

Personal Note

Andrej rebuild gpt2 in pytorch.

Take Away Points

  • Before entereing serious training, he use Shakespear’s work as a small debugging datset to see if a model can overfit. Overfitging is a should thing.
  • If we use TF32 or BF32, (by default is FP32 in pytorch it takes more memory), gpu can do hundred times faster. Becuase the core is computing really fast, most time (more than 40%) it is waiting for the memory allocation/transfer… Every computation is done in a manner like breaking down to 4x4 matrix multiplication.
  • when time a gpu programing, remember torch.cuda.synchronize()
  • watch gpu: watch -n 0.1 nvidia-smi
  • torch.set_float32_matmul_precision(‘high’) easily activate tf32 mode
    • default is highest -> float 32
    • High-> if avaible tensorflow32 (depends on GPU)
  • simply use torch.set_float32_matmul_precision(‘high’) theoraticlaly should make us have 8x speed. However we only achieve 3x. Becuse we are still memory bound, moving data around still cost a lot.
  • This can only be used in Amphere:
    use torch.autocast(device_type=device,dtype=torch.bfloat16) to wrap the forward process. In this wrap, some CUDA ops can autocast to BF16, many other stays in float32. Matrix Multiplication will be BF16.
  • One debug technique: import code; code.interact(local=locals())
  • torch.compile! Model = torch.compile(model)
  • Flash Attention. Flash Attention2. Online softmax.
    Use F.scale_dot_product_attention(q,k,v,is_causal=True) instead
  • Look for ugly numbers, make it to beautiful numbers. Any ugly numbers->increase it to have as much as 2 (Although flops will increase, time will decrease)
  • ALL ABOVE CHANGES MAKE PRAGRAM TRAINING 10x FASTER!!
  • Linear_warmup + cosine learning rate with minimum learning rate, see GPT3 paper for more details
  • First stage of the training, the model is not differing each tokens, they are just learning which tokens can show up which are not and driving them probability to zero. It is the reason that why in the early training stage, a small batchsize will be OK, as the gradients will not behave different if you use full batchsize.
  • parameters that should be weight decayed and should not be. WD: all weight tensors + embeddings (p.dim()>=2), NWD: all biaes, layernorms (p.dim()<2)
  • AdamW’s use_fused configuration (accelarate training process)
  • Model size up, lr down, batchsize up.
  • Grad accumulation: Remember to normalize: loss /= grad_accum_steps
  • when evaluation, use torch.Generator to create object used in torch.multinomial(xx,xx,generator=.), so that the generating process do not impact the global random number generator used for training.
  • However, torch.compile must be banned, so that you can sample in the training process.

CODES FOR DDP (SAMPLE)

# torchrun --stand_alone --nproc_per_node=<num_gpu_per_node> <your_training_script.py> <script_arguments> 
# Above only applies for single node training.# SETTINGS FOR EACH DIFFERENT RANK
ddp = int(os.environ.get('RANK',-1))!=-1
if ddp:assert torch.cuda.is_available()init_process_group(backend='nccl')ddp_rank = int(os.environ['RANK']) # It is a global rank, for each process it has a unique ddp_rankddp_local_rank = int(os.environ['LOCAL_RANK']) # It is a local rank in the local machine (node)ddp_world_size = int(os.environ['WORLD_SIZE']) # How many gpus (processes) in totaldevice = f'cuda:{ddp_local_rank}'torch.cuda.set_device(device)master_process = ddp_rank == 0
else:ddp_rank = 0ddp_local_rank = 0ddp_world_size = 1master_process = Truedevice = "cpu"if torhc.cuda.is_available():device = "cuda"elif hasattr(torch.backends,"mps") and torch.bakends.mps.is_available():device = "mps"print(f"using device:{device}")# IF YOU USE GRAD ACCUMULATION
total_batch_size = 524288 # batch size measured in token numbers
B = 16 # micro batch for each process
T = 1024 # sequence length
assert total_batch%(B * T * ddp_world_size) == 0
grad_accum_steps = total_batch_size // (B * T * ddp_world_size)# SET DATALOADER
Dataloader = DataLoader(*args, ddp_world_size, ddp_rank) # MUST! make each process deal with different part of datset# CREATE MODEL
model = createmodel()
model.to(device)
model = torch.compile(model)
if ddp:model = DDP(model,device_ids=[ddp_local_rank]) # this must be ddp_local_rank not ddp_rank
raw_model = model.module if ddp else model# FIX SEED
seed = 'YOUR LUCKY NUMBER'
torch.mannual_seed(seed)
if torch.cuda.is_available():torch.cuda.manual_seed(seed)# TRAIN
for step in range(max_steps):t0 = time.time()  model.train()optimizer.zero_grad()loss_accum = 0.0for micro_step in range(grad_accum_steps):x,y = Dataloader.next_batch()x,y = x.to(device),y.to(device)with torch.autocast(device_type=device,dtype=torch.bfloat16):logits, loss = model(x,y)loss = loss / grad_accum_stepsloss_accum += loss.detach()if ddp:model.require_backward_grad_sync = (micro_step == grad_accum_steps - 1) # The ddp sync if applied to every micro step will be wasting time. So only the last backward in one accum cycle should be synchronized. See ddp.no_sync() contextmanager for official advice. Or use it in this way shown here.loss.backward() if ddp:torch.distributed.all_reduce(loss_accum,op=torch.distributed.ReduceOp.AVG)
norm = torch.nn.utils.clip_grad_norm_(model.parameters(),1.0)if step%100 == 0:# start evaluationmodel.eval()with torch.no_grad():# SOME EVALUATION CODE
if ddp:destroy_process_group()

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/46037.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/46037.shtml
英文地址,請注明出處:http://en.pswp.cn/web/46037.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Ansys Zemax|探索OS中的物理光學傳播

概述 物理光學傳播 (Physical Optics Propagation, POP) 分析是OpticStudio序列模式中的一個強大的分析工具&#xff0c;它可以用來分析光束的傳播和光纖耦合的效率。這篇文章旨在介紹這一分析工具的功能&#xff0c;并向您展示一些具體的應用示例。本文同時為您介紹了如何使用…

有關電力電子技術的一些相關仿真和分析:⑦三相橋式電壓型PWM逆變器與直接/間接法控制單相全橋結構PWM整流器(MATLAB/Siumlink仿真)

1.1 題目一要求 以三相橋式電壓型PWM逆變器為對象,研究其在不同調制度下,輸出電壓的頻譜成分變化,依據仿真波形分析其工作時序。 參數要求:三相橋式逆變電路,直流側電壓800V,調制波頻率50HZ,開關頻率10kHZ,阻感負載R=10Ω,L=5mH。 1.2 題目二要求 以單相全橋結構P…

高效接入電商訂單API,掌握這些技巧輕松實現

受全渠道大趨勢的影響&#xff0c;很多實體商家紛紛開展電商業務&#xff0c;為了提升業務管理效率&#xff0c;想要在原有管理系統的基礎上通過接入電商訂單API接口&#xff0c;方便將線上線下的訂單進行統一管理&#xff0c;但各個電商平臺的電商訂單API接口那么多&#xff0…

allure_pytest:AttributeError: ‘str‘ object has no attribute ‘iter_parents‘

踩坑記錄 問題描述&#xff1a; 接口自動化測試時出現報錯&#xff0c;報錯文件是allure_pytest庫 問題分析&#xff1a; 自動化測試框架是比較成熟的代碼&#xff0c;報錯也不是自己寫的文件&#xff0c;而是第三方庫&#xff0c;首先推測是allure_pytest和某些庫有版本不兼…

彩電上自帶的推箱子游戲是什么編程語言開發的?

2000年左右的廈新彩電上&#xff0c;自帶了推箱子、華容道游戲。界面如下&#xff1a; 在線版推箱子游戲&#xff0c;網址&#xff1a;https://www.tuixiangzi.cn/ BASIC&#xff0c;全稱是Beginners All-purpose Symbolic Instruction Code&#xff0c;含義是初學者通用符號…

Ubuntu 添加gcc頭文件搜索路徑

對個人用戶生效 sudo vim ~/.bashrc在該文件末尾添加 #gcc C_INCLUDE_PATH$C_INCLUDE_PATH:your_path export C_INCLUDE_PATH #g CPLUS_INCLUDE_PATH$CPLUS_INCLUDE_PATH:your_path export CPLUS_INCLUDE_PATH最后&#xff0c;重啟終端即可生效 可用以下命令查看搜索路徑 ec…

深入了解Memcached:緩存技術的利器

文章目錄 深入了解Memcached&#xff1a;緩存技術的利器一、Memcached簡介什么是Memcached&#xff1f;Memcached的特點 二、Memcached的工作原理緩存機制分布式緩存 三、Memcached的架構客戶端與服務器數據存儲 四、Memcached的安裝與配置安裝Memcached在Linux上安裝在macOS上…

【IEEE出版順利申請中】2024年第四屆電子信息工程與計算機科學國際會議(EIECS 2024)

2024年第四屆電子信息工程與計算機科學國際會議(EIECS 2024) 2024 4th International Conference on Electronic Information Engineering and Computer Science 中國延吉 | 2024年9月27-29日 電子信息的出現與計算機技術、通信技術和高密度存儲技術的迅速發展并在各個領域里…

每日練習,不要放棄

目錄 題目1.下面敘述錯誤的是 ( )2.java如何返回request范圍內存在的對象&#xff1f;3.以下代碼將打印出4.下列類定義中哪些是合法的抽象類的定義&#xff1f;&#xff08;&#xff09;5.以下代碼段執行后的輸出結果為6.以下代碼運行輸出的是總結 題目 選自牛客網 1.下面敘述…

深度學習驅動智能超材料設計與應用

在深度學習與超材料融合的背景下&#xff0c;不僅提高了設計的效率和質量&#xff0c;還為實現定制化和精準化的治療提供了可能&#xff0c;展現了在材料科學領域的巨大潛力。深度學習可以幫助實現超材料結構參數的優化、電磁響應的預測、拓撲結構的自動設計、相位的預測及結構…

最全—航班信息管理系統【數組版】

航班管理系統&#xff08;數組版&#xff09; 航班信息查詢系統 1、 導言 用所學過的 C 語言&#xff0c;以及鏈表相關知識&#xff0c;實現一個航班信息的錄入、查詢、顯示、 排序等功能。航班信息 節點設計&#xff0c;請參見附錄。 2、 基本功能&#xff1a; 使用鏈表或數組…

開發指南047-前端模塊版本

平臺前端框架內置了一個文件version.vue <template> <div> <br> 應用名稱: {{name}} <br> 當前版本&#xff1a;{{version}} <br> 服務網關: {{gateway}} </div> </template> <scrip…

分析示例 | Simufact Additive鋪粉增材制造工藝缺陷仿真分析方案

近年來&#xff0c;隨著增材制造工藝的快速發展&#xff0c;仿真模擬的重要性日益凸顯&#xff0c;越來越多的科研及應用單位選擇在實際打印之前&#xff0c;通過仿真預測打印問題&#xff0c;從而優化打印工藝、減少物理試錯次數、降低打印成本。就不同增材工藝仿真的占比而言…

netxduo http server 創建回復以及json解析

我們今天要整http的response,比如我創建的http server,我對它發送了一個POST,然后服務器解析出json里的body,再回復過去。今天會用到json的解析庫cjson以及postman去發送消息。這次用nx_web_http_server.h這個庫,不用之前的nx_http_server.h 本教程在最后附帶app_netxduo…

大數據基礎:Doris重點架構原理

文章目錄 Doris重點架構原理 一、Apache Doris介紹 二、Apache Doris使用場景 三、Apache Doris架構原理 四、Apache Doris 特點 Doris重點架構原理 一、Apache Doris介紹 基于 MPP 架構的高性能、實時的分析型數據庫&#xff0c;以極速易用的特點被人們所熟知&#xff…

JVM---對象是否存活及被引用的狀態

1.如何判斷對象是否存活 1.1 引用計數算法 概念&#xff1a;在對象頭部增加一個引用計數器,每當有一個地方引用它時&#xff0c;計數器值就加一&#xff1b;當引用失效時&#xff0c;計數器值就減一&#xff1b;任何時刻計數器為零的對象就是不可能再被使用的。 優點&#xff1…

vue2遷移到vue3注意點

vue2遷移到vue3注意點 1、插槽的修改 使用 #default &#xff0c; 以及加上template 模板 2、 類型的定義&#xff0c;以及路由&#xff0c;vue相關資源&#xff08;ref, reactive,watch&#xff09;的引入等 3、類裝飾器 1&#xff09;vue-class-component是vue官方庫,作…

ubuntu搭建harbor私倉

1、環境準備 鏈接: https://pan.baidu.com/s/1q4XBWPd8WdyEn4l253mpUw 提取碼: 7ekx --來自百度網盤超級會員v2的分享 準備一臺Ubuntu 機器:192.168.124.165 將上面兩個文件考入Ubuntu上面 2、安裝harbor 安裝Docker Harbor倉庫以容器方式運行,需要先安裝好docker,參考:…

詳解python基本語法

文章目錄 數據變量數據結構 循環-判斷-用戶輸入判斷用戶輸入循環 函數參數返回值將函數存儲在模塊中 文件和異常讀取文件異常操作Json文件 類對象創建類使用類類的繼承導入外部類 測試測試函數創建測試 Python 是一種廣泛使用的高級編程語言&#xff0c;以其清晰的語法和代碼可…

which 命令在Linux中是一個快速查找可執行文件位置的工具

文章目錄 0、概念1、which --help2、which命令解釋 0、概念 which命令用于查找命令的可執行文件的路徑which 命令在 Linux 中用于查找可執行命令的完整路徑。當你在 shell 中輸入一個命令時&#xff0c;shell 會在環境變量 $PATH 定義的目錄列表中查找這個命令。which 命令可以…