らんだむな記憶

blogというものを体験してみようか!的なー

BERT (1)

取っ付きやすそうなので https://github.com/yukinaga/bert_nlp を使わせてもらう。
ただ、ライブラリのバージョンが古いので

!pip install folium==0.2.1
!pip install urllib3==1.25.11
!pip install transformers==4.13.0

とする。foliumurllib3 も単体ではもっと新しいバージョンがリリースされているのだが、それらを指定すると互換性について Error が表示されているので、許容される中で一番新しい上記とした。

さて、基本的には機械的にコードを replace するだけ・・・と思ったら https://github.com/yukinaga/bert_nlp/blob/main/section_2/03_simple_bert.ipynb の挙動がおかしい。show_continuity にどんな文章を突っ込んでも高確率で連続していることになってしまう。
GitHub を調べると https://github.com/huggingface/transformers/issues/1788 或はそこから誘導される https://github.com/huggingface/transformers/issues/1790 にあるように、

Hi, since pytorch_pretrained_BERT, many breaking changes have happened, two of which are causing confusion in your snippet:

  • The order of arguments in the forward call has been slightly changed (v2.0.0)
  • The models now always return tuples (v1.0.0).

The attention mask and token type ids order has been changed for the forward method to better respect the order of importance, which is important when compiling a model with torchscript.

という感じで重要性に合わせて引数の順番が変更されているらしい。おっと・・・どこかで聞いたような罠だ・・・。なので、

def show_continuity(text, seg_ids):
    ...
    y = nsp_model(x, s)  # 予測

def show_continuity(text, seg_ids):
    ...
    y = nsp_model(x, token_type_ids=s)  # 予測

としなければならないようだった。これは・・・古い記事とかを参考にする場合も要注意だな・・・。

https://github.com/huggingface/transformers/blob/v4.13.0/src/transformers/models/bert/modeling_bert.py
この辺のコードが参考になるかもしれない。