# Pretraining BERT

**URL:** <https://d2l.discourse.group/t/pretraining-bert/1497>\
**Category:** pytorch\
**Created:** [November 30, 2020, 6:31am UTC](https://d2l.discourse.group/t/pretraining-bert/1497 "2020-11-30T06:31:58Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![anirudh](https://yyz2.discourse-cdn.com/free1/user_avatar/d2l.discourse.group/anirudh/32/180_2.png) [@anirudh](https://d2l.discourse.group/u/anirudh)\
**Post date:** [November 30, 2020, 6:31am UTC](https://d2l.discourse.group/t/pretraining-bert/1497/1 "2020-11-30T06:31:59Z")

</div>

[https://d2l.ai/chapter\_natural-language-processing-pretraining/bert-pretraining.html](https://d2l.ai/chapter_natural-language-processing-pretraining/bert-pretraining.html)

---

<div class="post-metadata">

**Author:** ![leis](https://avatars.discourse-cdn.com/v4/letter/l/cab0a1/32.png) [@leis](https://d2l.discourse.group/u/leis)\
**Post date:** [May 3, 2021, 10:17am UTC](https://d2l.discourse.group/t/pretraining-bert/1497/2 "2021-05-03T10:17:57Z")

</div>

Hi,

I am wondering if there is an error in Pytorch´s \_get\_batch\_loss\_bert():

mlm\_l = loss(mlm\_Y\_hat.reshape(-1, vocab\_size), mlm\_Y.reshape(-1)) \* mlm\_weights\_X.reshape(-1, 1)  
mlm\_l = mlm\_l.sum() / (mlm\_weights\_X.sum() + 1e-8)

Before, it was defined loss = nn.CrossEntropyLoss(), so it adopts the default reduction=‘mean’. But my impression is that we should use reduction=None instead, in order to average it based on the variable num of real tokens (mlm\_weights\_X.sum()) and not the real tokens + pad tokens as it currently seems to be doing?

In terms of dimensionality: mlm\_Y\_hat = {n,tau,v}, mlm\_Y={n,tau} and mlm\_weights\_X={n,tau}. Currently loss(mlm\_Y\_hat…) seems to yield a scalar, which is then multiplied by mlm\_weights\_X.reshape(-1, 1) of dim {n·tau} which gives a vector of dim {n·tau}. In the 2nd line it is then sumed up and divided by the num of non-zero components in mlm\_weights\_X, effectively giving back the original scalar loss(mlm\_Y\_hat…) which is an average over the real and pad tokens.

I think if for MLM it had been defined loss = nn.CrossEntropyLoss(reduction=None), then loss(mlm\_Y\_hat…) would yield a tensor of dim {n·tau} which multiplied by mlm\_weights\_X.reshape(-1, 1) of dim {n·tau} would give a vector of dim {n·tau}. The 2nd line would then sum it up and divide it by the num of real tokens, without the pad tokens affecting the average.

---

<div class="post-metadata">

**Author:** ![ducatyb](https://yyz2.discourse-cdn.com/free1/user_avatar/d2l.discourse.group/ducatyb/32/2715_2.png) [@ducatyb](https://d2l.discourse.group/u/ducatyb)\
**Post date:** [October 17, 2021, 5:24am UTC](https://d2l.discourse.group/t/pretraining-bert/1497/3 "2021-10-17T05:24:41Z")

</div>

I agree. The `CrossEntropyLoss` object should have been instantiated with the parameter `reduction` specified as `none`. Otherwise it will average the loss over **both** valid and invalid (padded) tokens. The correct instantiation statement is

```auto
loss = nn.CrossEntropyLoss(reduction='none')

```

Also the code filtering out losses for padding tokens

```auto
mlm_l = loss(mlm_Y_hat.reshape(-1, vocab_size), mlm_Y.reshape(-1)) *\
             mlm_weights_X.reshape(-1, 1)

```

should be changed to

```auto
mlm_l = loss(mlm_Y_hat.reshape(-1, vocab_size), mlm_Y.reshape(-1)) *\
        mlm_weights_X.reshape(-1)

```

After this (revised) line of code has been executed, `mlm_l` would have shape of `(5120,)` (here, batch size=512, maximum number of masked tokens=10, 512 times 10 = 5120)

---

<div class="post-metadata">

**Author:** ![piyushmishra12](https://yyz2.discourse-cdn.com/free1/user_avatar/d2l.discourse.group/piyushmishra12/32/4968_2.png) [@piyushmishra12](https://d2l.discourse.group/u/piyushmishra12)\
**Post date:** [July 28, 2022, 6:15am UTC](https://d2l.discourse.group/t/pretraining-bert/1497/4 "2022-07-28T06:15:36Z")

</div>

Hello, I used this method to pretrain a BERT model on a humungous DNA corpus. The “problem” is that it is finishing pertaining in just 15 minutes for the entire dataset whereas a BERT from scratch would take at least a few days (along with the processing capabilities). Could someone let me know why this is happening and if the model is learning or not?

---

<div class="post-metadata">

**Author:** ![GarryKouyu](https://yyz2.discourse-cdn.com/free1/user_avatar/d2l.discourse.group/garrykouyu/32/7832_2.png) [@GarryKouyu](https://d2l.discourse.group/u/GarryKouyu)\
**Post date:** [April 14, 2023, 8:10am UTC](https://d2l.discourse.group/t/pretraining-bert/1497/5 "2023-04-14T08:10:30Z")

</div>

I agree with you, the original code will output the same loss as loss(mlm\_Y\_hat.reshape(-1, vocab\_size), mlm\_Y.reshape(-1)).

---

<div class="post-metadata">

**Author:** ![kyunghee\_cha](https://yyz2.discourse-cdn.com/free1/user_avatar/d2l.discourse.group/kyunghee_cha/32/11042_2.png) [@kyunghee\_cha](https://d2l.discourse.group/u/kyunghee_cha)\
**Post date:** [January 20, 2024, 12:54pm UTC](https://d2l.discourse.group/t/pretraining-bert/1497/6 "2024-01-20T12:54:25Z")

</div>

I’ve revised those to the below:

loss = nn.CrossEntropyLoss(reduction=‘none’)  
mlm\_l = loss(mlm\_Y\_hat.reshape(-1, vocab\_size), mlm\_Y.reshape(-1))\*mlm\_weights\_X.reshape(-1)  
nsp\_l = loss(nsp\_Y\_hat, nsp\_y).mean()

In that case, I’ve got the result of :

accumulation of mlm loss for 50 steps: 366.18415546417236  
accumulation of nsp loss for 50 steps: 37.543556928634644  
MLM loss 7.324, NSP loss 0.751  
5099.7 sentence pairs/sec on [device(type=‘cuda’, index=0)]

Both accumulated losses were increased by 84.5 and 0.2 respectively.  
I am wondering if it is all good.

---

<div class="post-metadata">

**Author:** ![Jaehwan\_Jeong](https://yyz2.discourse-cdn.com/free1/user_avatar/d2l.discourse.group/jaehwan_jeong/32/12829_2.png) [@Jaehwan\_Jeong](https://d2l.discourse.group/u/Jaehwan_Jeong)\
**Post date:** [June 8, 2024, 8:05am UTC](https://d2l.discourse.group/t/pretraining-bert/1497/7 "2024-06-08T08:05:17Z")

</div>

```python
batch_size, max_len = 512, 64
train_iter, vocab = d2l.load_data_wiki(batch_size, max_len)

```

When I try to execute the above cell, I get the error message as **“BadZipFile: File is not a zip file.”** I tried to access the raw URL of Wikitext2 by typing this URL “[https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-v1.zip](https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-v1.zip)” directly on the brower, but it shows a message written as “access denied.” Is there anyone who can check issue?? I’m curious whether the URL is temporarily having access troubles, or it’s been permanently closed.

I would appreciate any of your helps. Thanks!

---

<div class="post-metadata">

**Author:** ![nam-hoang-le-isods](https://yyz2.discourse-cdn.com/free1/user_avatar/d2l.discourse.group/nam-hoang-le-isods/32/13104_2.png) [@nam-hoang-le-isods](https://d2l.discourse.group/u/nam-hoang-le-isods)\
**Post date:** [July 1, 2024, 10:40am UTC](https://d2l.discourse.group/t/pretraining-bert/1497/8 "2024-07-01T10:40:47Z")

</div>

![image](https://global.discourse-cdn.com/free1/uploads/d2l/original/2X/b/bc710ed92315e61b33bb14924e1c1ed3709ff501.png)  
Here we have the problem with downloading the dataset and can’t run the system! Please fix it for me. Thank you!

---

<div class="post-metadata">

**Author:** ![JH.Lam](https://avatars.discourse-cdn.com/v4/letter/j/b782af/32.png) [@JH.Lam](https://d2l.discourse.group/u/JH.Lam)\
**Post date:** [November 22, 2024, 11:15am UTC](https://d2l.discourse.group/t/pretraining-bert/1497/9 "2024-11-22T11:15:45Z")

</div>

sure ,that’s a misused case on ‘scalar \* vector’ to result in fake vector with same shape
