Upload 743 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +29 -0
- SimTranslation/README.md +261 -0
- SimTranslation/bert_model/bert-base-german-dbmdz-uncased/.gitattributes +10 -0
- SimTranslation/bert_model/bert-base-german-dbmdz-uncased/README.md +71 -0
- SimTranslation/bert_model/bert-base-german-dbmdz-uncased/config.json +19 -0
- SimTranslation/bert_model/bert-base-german-dbmdz-uncased/pytorch_model.bin +3 -0
- SimTranslation/bert_model/bert-base-german-dbmdz-uncased/tokenizer_config.json +1 -0
- SimTranslation/bert_model/bert-base-german-dbmdz-uncased/vocab.txt +0 -0
- SimTranslation/bert_model/download_bert.sh +37 -0
- SimTranslation/code/unibert_waitk_0901_stack/CODE_OF_CONDUCT.md +77 -0
- SimTranslation/code/unibert_waitk_0901_stack/CONTRIBUTING.md +28 -0
- SimTranslation/code/unibert_waitk_0901_stack/LICENSE +21 -0
- SimTranslation/code/unibert_waitk_0901_stack/README.md +70 -0
- SimTranslation/code/unibert_waitk_0901_stack/bert/__init__.py +2 -0
- SimTranslation/code/unibert_waitk_0901_stack/bert/__pycache__/__init__.cpython-38.pyc +0 -0
- SimTranslation/code/unibert_waitk_0901_stack/bert/__pycache__/file_utils.cpython-38.pyc +0 -0
- SimTranslation/code/unibert_waitk_0901_stack/bert/__pycache__/modeling.cpython-38.pyc +0 -0
- SimTranslation/code/unibert_waitk_0901_stack/bert/__pycache__/tokenization.cpython-38.pyc +0 -0
- SimTranslation/code/unibert_waitk_0901_stack/bert/file_utils.py +279 -0
- SimTranslation/code/unibert_waitk_0901_stack/bert/modeling.py +1240 -0
- SimTranslation/code/unibert_waitk_0901_stack/bert/tokenization.py +438 -0
- SimTranslation/code/unibert_waitk_0901_stack/bi_dataprocess.sh +8 -0
- SimTranslation/code/unibert_waitk_0901_stack/code +0 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/Makefile +20 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/_static/theme_overrides.css +9 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/command_line_tools.rst +85 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/conf.py +132 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/criterions.rst +31 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/data.rst +58 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/docutils.conf +2 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/getting_started.rst +184 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/index.rst +49 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/lr_scheduler.rst +34 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/make.bat +36 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/models.rst +104 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/modules.rst +9 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/optim.rst +38 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/overview.rst +74 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/requirements.txt +2 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/tasks.rst +61 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/tutorial_classifying_names.rst +416 -0
- SimTranslation/code/unibert_waitk_0901_stack/docs/tutorial_simple_lstm.rst +517 -0
- SimTranslation/code/unibert_waitk_0901_stack/eval_lm.py +11 -0
- SimTranslation/code/unibert_waitk_0901_stack/examples/__init__.py +6 -0
- SimTranslation/code/unibert_waitk_0901_stack/examples/__pycache__/__init__.cpython-38.pyc +0 -0
- SimTranslation/code/unibert_waitk_0901_stack/examples/waitk/README.md +107 -0
- SimTranslation/code/unibert_waitk_0901_stack/examples/waitk/__init__.py +1 -0
- SimTranslation/code/unibert_waitk_0901_stack/examples/waitk/__pycache__/__init__.cpython-38.pyc +0 -0
- SimTranslation/code/unibert_waitk_0901_stack/examples/waitk/eval_delay.py +160 -0
- SimTranslation/code/unibert_waitk_0901_stack/examples/waitk/generators/__init__.py +7 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,32 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
SimTranslation/code/unibert_waitk_0901_stack/fairseq/data/data_utils_fast.cpython-38-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
SimTranslation/code/unibert_waitk_0901_stack/fairseq/data/data_utils_fast.cpython-39-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 63 |
+
SimTranslation/code/unibert_waitk_0901_stack/fairseq/data/token_block_utils_fast.cpython-38-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 64 |
+
SimTranslation/code/unibert_waitk_0901_stack/fairseq/data/token_block_utils_fast.cpython-39-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 65 |
+
SimTranslation/code/unibert_waitk_0901_stack/fairseq/libbleu.cpython-38-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 66 |
+
SimTranslation/code/unibert_waitk_0901_stack/fairseq/libnat.cpython-38-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 67 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/bi_iwslt_de_en/test.bert.de-en.de.idx filter=lfs diff=lfs merge=lfs -text
|
| 68 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/bi_iwslt_de_en/test.de-en.de.idx filter=lfs diff=lfs merge=lfs -text
|
| 69 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/bi_iwslt_de_en/test.de-en.en.idx filter=lfs diff=lfs merge=lfs -text
|
| 70 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/bi_iwslt_de_en/train.bert.de-en.de.idx filter=lfs diff=lfs merge=lfs -text
|
| 71 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/bi_iwslt_de_en/train.de-en.de.idx filter=lfs diff=lfs merge=lfs -text
|
| 72 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/bi_iwslt_de_en/train.de-en.en.idx filter=lfs diff=lfs merge=lfs -text
|
| 73 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/bi_iwslt_de_en/valid.bert.de-en.de.idx filter=lfs diff=lfs merge=lfs -text
|
| 74 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/bi_iwslt_de_en/valid.de-en.de.idx filter=lfs diff=lfs merge=lfs -text
|
| 75 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/bi_iwslt_de_en/valid.de-en.en.idx filter=lfs diff=lfs merge=lfs -text
|
| 76 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/iwslt14-de-en-onlyfariseq/test.de-en.de.idx filter=lfs diff=lfs merge=lfs -text
|
| 77 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/iwslt14-de-en-onlyfariseq/test.de-en.en.idx filter=lfs diff=lfs merge=lfs -text
|
| 78 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/iwslt14-de-en-onlyfariseq/train.de-en.de.idx filter=lfs diff=lfs merge=lfs -text
|
| 79 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/iwslt14-de-en-onlyfariseq/train.de-en.en.idx filter=lfs diff=lfs merge=lfs -text
|
| 80 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/iwslt14-de-en-onlyfariseq/valid.de-en.de.idx filter=lfs diff=lfs merge=lfs -text
|
| 81 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/iwslt14-de-en-onlyfariseq/valid.de-en.en.idx filter=lfs diff=lfs merge=lfs -text
|
| 82 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/train.bert.de filter=lfs diff=lfs merge=lfs -text
|
| 83 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/train.bert.en filter=lfs diff=lfs merge=lfs -text
|
| 84 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/train.de filter=lfs diff=lfs merge=lfs -text
|
| 85 |
+
SimTranslation/code/unibert_waitk_0901_stack/iwslt14.tokenized.de-en/train.en filter=lfs diff=lfs merge=lfs -text
|
| 86 |
+
SimTranslation/code/unibert_waitk_0901_stack/train.bert.de filter=lfs diff=lfs merge=lfs -text
|
| 87 |
+
SimTranslation/code/unibert_waitk_0901_stack/train.bert.en filter=lfs diff=lfs merge=lfs -text
|
| 88 |
+
SimTranslation/code/unibert_waitk_0901_stack/train.de filter=lfs diff=lfs merge=lfs -text
|
| 89 |
+
SimTranslation/code/unibert_waitk_0901_stack/train.en filter=lfs diff=lfs merge=lfs -text
|
SimTranslation/README.md
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 源端信息补全的机器同传 — 完整训练+评估流程
|
| 2 |
+
|
| 3 |
+
> 论文:**Source-Side Context Predictive Completion for Simultaneous Machine Translation** (IEEE TASLP, 2025)
|
| 4 |
+
> 本包不含模型权重,提供从环境搭建到训练评估的完整可复现流程。
|
| 5 |
+
|
| 6 |
+
---
|
| 7 |
+
|
| 8 |
+
## 1. 环境要求
|
| 9 |
+
|
| 10 |
+
| 项目 | 要求 | 已验证 |
|
| 11 |
+
|------|------|--------|
|
| 12 |
+
| Python | 3.8 | ✅ 3.8.20 |
|
| 13 |
+
| PyTorch | 1.10.0+cu113 | ✅ |
|
| 14 |
+
| CUDA | 11.x (Driver 12.x 兼容) | ✅ CUDA 12.1 Driver |
|
| 15 |
+
| GPU 显存 | ≥8 GB (NMT), ≥12 GB (BERT) | ✅ A100 80GB |
|
| 16 |
+
| 内存 | ≥16 GB | ✅ |
|
| 17 |
+
| 磁盘 | ≥15 GB | ✅ |
|
| 18 |
+
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
## 2. 开始(5 步)
|
| 22 |
+
|
| 23 |
+
### 第一步:创建环境
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
conda create -n simt python=3.8 -y
|
| 27 |
+
conda activate simt
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
### 第二步:安装 PyTorch
|
| 31 |
+
|
| 32 |
+
```bash
|
| 33 |
+
# CUDA 11.3
|
| 34 |
+
pip install torch==1.10.0+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
### 第三步:安装依赖
|
| 38 |
+
|
| 39 |
+
```bash
|
| 40 |
+
pip install -r requirements.txt
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
### 第四步:安装 Fairseq
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
cd code/unibert_waitk_0901_stack
|
| 47 |
+
pip install --editable .
|
| 48 |
+
cd ../..
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
### 第五步:下载 BERT 模型
|
| 52 |
+
|
| 53 |
+
```bash
|
| 54 |
+
bash bert_model/download_bert.sh
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
> 脚本使用 hf-mirror.com 国内镜像下载,约 422MB。如网络不通,手动从 https://huggingface.co/dbmdz/bert-base-german-uncased 下载,放到 `bert_model/bert-base-german-dbmdz-uncased/`。
|
| 58 |
+
|
| 59 |
+
### 验证安装
|
| 60 |
+
|
| 61 |
+
```bash
|
| 62 |
+
conda activate simt
|
| 63 |
+
python -c "import torch; print(f'PyTorch {torch.__version__}, CUDA: {torch.cuda.is_available()}')"
|
| 64 |
+
python -c "import fairseq; print(f'Fairseq {fairseq.__version__}')"
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
预期输出:
|
| 68 |
+
```
|
| 69 |
+
PyTorch 1.10.0+cu113, CUDA: True
|
| 70 |
+
Fairseq 0.9.0
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
---
|
| 74 |
+
|
| 75 |
+
## 3. 运行实验
|
| 76 |
+
|
| 77 |
+
### 方法一:一键运行(推荐)
|
| 78 |
+
|
| 79 |
+
```bash
|
| 80 |
+
conda activate simt
|
| 81 |
+
bash run_all.sh
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
脚本自动完成三个阶段:
|
| 85 |
+
|
| 86 |
+
| 阶段 | 内容 | GPU | 预计耗时 (A100) | 验证耗时 |
|
| 87 |
+
|------|------|-----|-----------------|---------|
|
| 88 |
+
| 1 | 训练 NMT warmup k=1,5,9 (512d) | 3×GPU 并行 | ~1.5h | ✅ 86-89 min |
|
| 89 |
+
| 2 | 训练 BERT 模型 k=1,5,9 | 3×GPU 并行 | ~9.5h | ✅ 9.6h |
|
| 90 |
+
| 3 | 评估全部 6 个模型 | 1×GPU | ~6 min | ✅ |
|
| 91 |
+
| **总计** | | | **~11h** | ✅ 验证通过 |
|
| 92 |
+
|
| 93 |
+
结果保存到 `logs/all_results.txt`。
|
| 94 |
+
|
| 95 |
+
### 方法二:单 k 值验证
|
| 96 |
+
|
| 97 |
+
```bash
|
| 98 |
+
bash run_single.sh 5 # 只跑 k=5, ~11h
|
| 99 |
+
bash run_single.sh 5 0 # 指定 GPU 0
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
### 方法三:查看已有结果
|
| 103 |
+
|
| 104 |
+
如果训练已完成,直接查看:
|
| 105 |
+
```bash
|
| 106 |
+
cat logs/all_results.txt
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
---
|
| 110 |
+
|
| 111 |
+
## 4. 已验证结果
|
| 112 |
+
|
| 113 |
+
以下结果在 6×A100-80GB + CUDA 12.1 + PyTorch 1.10.0+cu113 环境上完整验证通过。
|
| 114 |
+
|
| 115 |
+
### NMT Baseline(纯 Wait-k,无 BERT)
|
| 116 |
+
|
| 117 |
+
| 模型 | BLEU4 ↑ | AL ↓ | DAL ↓ | AP |
|
| 118 |
+
|------|---------|------|-------|-----|
|
| 119 |
+
| NMT k=1 | 19.29 | 1.15 | 2.22 | 0.56 |
|
| 120 |
+
| NMT k=5 | **28.39** | **5.05** | **5.45** | 0.77 |
|
| 121 |
+
| NMT k=9 | **31.35** | **8.55** | **8.87** | 0.88 |
|
| 122 |
+
|
| 123 |
+
### BERT 源端补全(论文方法)
|
| 124 |
+
|
| 125 |
+
| 模型 | BLEU4 ↑ | AL ↓ | DAL ↓ | AP |
|
| 126 |
+
|------|---------|------|-------|-----|
|
| 127 |
+
| BERT k=1 | 21.99 | 1.31 | 2.04 | 0.56 |
|
| 128 |
+
| BERT k=5 | **30.03** | **5.01** | **5.43** | 0.77 |
|
| 129 |
+
| BERT k=9 | **32.22** | **8.36** | **8.70** | 0.88 |
|
| 130 |
+
|
| 131 |
+
### 方法效果
|
| 132 |
+
|
| 133 |
+
| k | NMT BLEU | BERT BLEU | ΔBLEU (提升) |
|
| 134 |
+
|---|---------|----------|-------------|
|
| 135 |
+
| 1 | 19.29 | 21.99 | **+2.70** |
|
| 136 |
+
| 5 | 28.39 | 30.03 | **+1.64** |
|
| 137 |
+
| 9 | 31.35 | 32.22 | **+0.87** |
|
| 138 |
+
|
| 139 |
+
**结论**:在相同延迟水平下,BERT 源端补全在所有 k 值下均优于纯 Wait-k baseline。k=5 时提升 +1.64 BLEU,k=9 时提升 +0.87 BLEU。延迟指标(AL/DAL)几乎一致。
|
| 140 |
+
|
| 141 |
+
---
|
| 142 |
+
|
| 143 |
+
## 5. 目录结构
|
| 144 |
+
|
| 145 |
+
```
|
| 146 |
+
SimTranslation_无权重版/
|
| 147 |
+
├── README.md ← 本文档
|
| 148 |
+
├── requirements.txt ← Python 依赖
|
| 149 |
+
├── run_all.sh ← 一键运行全部
|
| 150 |
+
├── run_single.sh ← 单 k 值验证
|
| 151 |
+
├── bert_model/
|
| 152 |
+
│ ├── download_bert.sh ← BERT 下载脚本 (国内镜像)
|
| 153 |
+
│ └── bert-base-german-dbmdz-uncased/ ← 下载后出现
|
| 154 |
+
├── code/unibert_waitk_0901_stack/ ← 完整 Fairseq 代码
|
| 155 |
+
│ ├── train.py / generate.py ← 训练/推理入口
|
| 156 |
+
│ ├── fairseq/ ← Fairseq 0.9.0
|
| 157 |
+
│ ├── bert/ ← 自实现 BERT (无需 transformers)
|
| 158 |
+
│ ├── examples/waitk/ ← Wait-k + BERT 核心
|
| 159 |
+
│ │ ├── models/waitk_transformer.py ← 模型定义
|
| 160 |
+
│ │ ├── modules/transformer_layers.py ← Encoder/Decoder 层
|
| 161 |
+
│ │ └── eval_delay.py ← 延迟指标计算
|
| 162 |
+
│ └── iwslt14.tokenized.de-en/ ← IWSLT14 De→En 数据
|
| 163 |
+
├── logs/ ← 日志输出(运行后生成)
|
| 164 |
+
└── checkpoints/ ← 模型权重(运行后生成,在 code/.../checkpoints/)
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
---
|
| 168 |
+
|
| 169 |
+
## 6. 评估指标
|
| 170 |
+
|
| 171 |
+
| 指标 | 含义 | 方向 |
|
| 172 |
+
|------|------|------|
|
| 173 |
+
| BLEU4 | 翻译质量 (4-gram) | ↑ 越高越好 |
|
| 174 |
+
| AL | Average Lagging (平均延迟) | ↓ 越低越好 |
|
| 175 |
+
| DAL | Differentiable Average Lagging | ↓ 越低越好 |
|
| 176 |
+
| AP | Average Proportion (源端比例) | → 1.0 最优 |
|
| 177 |
+
|
| 178 |
+
---
|
| 179 |
+
|
| 180 |
+
## 7. 技术原理
|
| 181 |
+
|
| 182 |
+
### Wait-k 策略
|
| 183 |
+
|
| 184 |
+
源端每读 k 个词,生成 1 个目标词。k 越小延迟越低但质量越差。
|
| 185 |
+
|
| 186 |
+
### BERT 源端补全
|
| 187 |
+
|
| 188 |
+
预训练 BERT(bert-base-german-dbmdz-uncased, 110M 参数)编码**完整**源端句子,通过 cross-attention 注入 Wait-k Transformer 的 Encoder 和 Decoder,补充单向模型看不到的未来信息。
|
| 189 |
+
|
| 190 |
+
### 训练流程
|
| 191 |
+
|
| 192 |
+
```
|
| 193 |
+
NMT warmup (512d, waitk_transformer_iwslt_de_en)
|
| 194 |
+
↓ 加载为初始化
|
| 195 |
+
BERT 模型 (512d, waitk_transformer_iwslt_de_en + BERT cross-attention)
|
| 196 |
+
↓ 联合训练
|
| 197 |
+
评估:BLEU4 + AL + DAL + AP
|
| 198 |
+
```
|
| 199 |
+
|
| 200 |
+
NMT 和 BERT 使用**相同架构**(`waitk_transformer_iwslt_de_en`, 512d),warmup 时参数完整加载。
|
| 201 |
+
|
| 202 |
+
---
|
| 203 |
+
|
| 204 |
+
## 8. 模型参数
|
| 205 |
+
|
| 206 |
+
| 参数 | NMT | BERT |
|
| 207 |
+
|------|-----|------|
|
| 208 |
+
| 架构 | waitk_transformer_iwslt_de_en | 同 + BERT |
|
| 209 |
+
| Encoder/Decoder 层数 | 6/6 | 6/6 |
|
| 210 |
+
| Embed Dim | 512 | 512 |
|
| 211 |
+
| FFN Dim | 1024 | 1024 |
|
| 212 |
+
| Attention Heads | 4 | 4 |
|
| 213 |
+
| Dropout | 0.3 | 0.3 |
|
| 214 |
+
| BERT 层数 | — | 12 |
|
| 215 |
+
| BERT Hidden | — | 768 |
|
| 216 |
+
| 参数量 | ~58M | ~168M |
|
| 217 |
+
|
| 218 |
+
---
|
| 219 |
+
|
| 220 |
+
## 9. 常见问题
|
| 221 |
+
|
| 222 |
+
**Q: GPU 显存不足?**
|
| 223 |
+
修改 `run_all.sh` 中 `MAX_TOKENS=2000`
|
| 224 |
+
|
| 225 |
+
**Q: BERT 下载失败?**
|
| 226 |
+
脚本已使用 hf-mirror.com 国内镜像。如仍失败,手动下载:
|
| 227 |
+
https://huggingface.co/dbmdz/bert-base-german-uncased
|
| 228 |
+
将 `pytorch_model.bin`, `vocab.txt`, `config.json` 放到 `bert_model/bert-base-german-dbmdz-uncased/`
|
| 229 |
+
|
| 230 |
+
**Q: 训练报 "Cannot load model parameters"?**
|
| 231 |
+
NMT 和 BERT 架构必须一致。确认 run_all.sh 中 NMT 使用 `waitk_transformer_iwslt_de_en`(512d)。
|
| 232 |
+
|
| 233 |
+
**Q: 只想验证 k=5 的效果?**
|
| 234 |
+
```bash
|
| 235 |
+
bash run_single.sh 5
|
| 236 |
+
```
|
| 237 |
+
|
| 238 |
+
**Q: 结果与预期有微小偏差?**
|
| 239 |
+
随机种子固定为 seed=1,但不同 GPU 型号/驱动版本的浮点运算可能有微小差异(<0.5 BLEU)。趋势(BERT > NMT)应始终成立。
|
| 240 |
+
|
| 241 |
+
---
|
| 242 |
+
|
| 243 |
+
## 10. 复现记录
|
| 244 |
+
|
| 245 |
+
本包已在以下环境完整验证通过:
|
| 246 |
+
|
| 247 |
+
| 项目 | 配置 |
|
| 248 |
+
|------|------|
|
| 249 |
+
| 日期 | 2025-06-24 |
|
| 250 |
+
| GPU | 6×NVIDIA A100-SXM4-80GB |
|
| 251 |
+
| Driver | 470.199.02, CUDA 12.1 |
|
| 252 |
+
| Python | 3.8.20 |
|
| 253 |
+
| PyTorch | 1.10.0+cu113 |
|
| 254 |
+
| NMT 训练耗时 | 86-89 min (×3) |
|
| 255 |
+
| BERT 训练耗时 | 9.5-9.7h (×3) |
|
| 256 |
+
| NMT k=5 BLEU | 28.39 |
|
| 257 |
+
| BERT k=5 BLEU | 30.03 (+1.64) |
|
| 258 |
+
| BERT k=9 BLEU | 32.22 (+0.87) |
|
| 259 |
+
|
| 260 |
+
---
|
| 261 |
+
|
SimTranslation/bert_model/bert-base-german-dbmdz-uncased/.gitattributes
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.bin.* filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.tar.gz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
model.safetensors filter=lfs diff=lfs merge=lfs -text
|
SimTranslation/bert_model/bert-base-german-dbmdz-uncased/README.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language: de
|
| 3 |
+
license: mit
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
# 🤗 + 📚 dbmdz German BERT models
|
| 7 |
+
|
| 8 |
+
In this repository the MDZ Digital Library team (dbmdz) at the Bavarian State
|
| 9 |
+
Library open sources another German BERT models 🎉
|
| 10 |
+
|
| 11 |
+
# German BERT
|
| 12 |
+
|
| 13 |
+
## Stats
|
| 14 |
+
|
| 15 |
+
In addition to the recently released [German BERT](https://deepset.ai/german-bert)
|
| 16 |
+
model by [deepset](https://deepset.ai/) we provide another German-language model.
|
| 17 |
+
|
| 18 |
+
The source data for the model consists of a recent Wikipedia dump, EU Bookshop corpus,
|
| 19 |
+
Open Subtitles, CommonCrawl, ParaCrawl and News Crawl. This results in a dataset with
|
| 20 |
+
a size of 16GB and 2,350,234,427 tokens.
|
| 21 |
+
|
| 22 |
+
For sentence splitting, we use [spacy](https://spacy.io/). Our preprocessing steps
|
| 23 |
+
(sentence piece model for vocab generation) follow those used for training
|
| 24 |
+
[SciBERT](https://github.com/allenai/scibert). The model is trained with an initial
|
| 25 |
+
sequence length of 512 subwords and was performed for 1.5M steps.
|
| 26 |
+
|
| 27 |
+
This release includes both cased and uncased models.
|
| 28 |
+
|
| 29 |
+
## Model weights
|
| 30 |
+
|
| 31 |
+
Currently only PyTorch-[Transformers](https://github.com/huggingface/transformers)
|
| 32 |
+
compatible weights are available. If you need access to TensorFlow checkpoints,
|
| 33 |
+
please raise an issue!
|
| 34 |
+
|
| 35 |
+
| Model | Downloads
|
| 36 |
+
| -------------------------------- | ---------------------------------------------------------------------------------------------------------------
|
| 37 |
+
| `bert-base-german-dbmdz-cased` | [`config.json`](https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-german-dbmdz-cased-config.json) • [`pytorch_model.bin`](https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-german-dbmdz-cased-pytorch_model.bin) • [`vocab.txt`](https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-german-dbmdz-cased-vocab.txt)
|
| 38 |
+
| `bert-base-german-dbmdz-uncased` | [`config.json`](https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-german-dbmdz-uncased-config.json) • [`pytorch_model.bin`](https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-german-dbmdz-uncased-pytorch_model.bin) • [`vocab.txt`](https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-german-dbmdz-uncased-vocab.txt)
|
| 39 |
+
|
| 40 |
+
## Usage
|
| 41 |
+
|
| 42 |
+
With Transformers >= 2.3 our German BERT models can be loaded like:
|
| 43 |
+
|
| 44 |
+
```python
|
| 45 |
+
from transformers import AutoModel, AutoTokenizer
|
| 46 |
+
|
| 47 |
+
tokenizer = AutoTokenizer.from_pretrained("dbmdz/bert-base-german-cased")
|
| 48 |
+
model = AutoModel.from_pretrained("dbmdz/bert-base-german-cased")
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
## Results
|
| 52 |
+
|
| 53 |
+
For results on downstream tasks like NER or PoS tagging, please refer to
|
| 54 |
+
[this repository](https://github.com/stefan-it/fine-tuned-berts-seq).
|
| 55 |
+
|
| 56 |
+
# Huggingface model hub
|
| 57 |
+
|
| 58 |
+
All models are available on the [Huggingface model hub](https://huggingface.co/dbmdz).
|
| 59 |
+
|
| 60 |
+
# Contact (Bugs, Feedback, Contribution and more)
|
| 61 |
+
|
| 62 |
+
For questions about our BERT models just open an issue
|
| 63 |
+
[here](https://github.com/dbmdz/berts/issues/new) 🤗
|
| 64 |
+
|
| 65 |
+
# Acknowledgments
|
| 66 |
+
|
| 67 |
+
Research supported with Cloud TPUs from Google's TensorFlow Research Cloud (TFRC).
|
| 68 |
+
Thanks for providing access to the TFRC ❤️
|
| 69 |
+
|
| 70 |
+
Thanks to the generous support from the [Hugging Face](https://huggingface.co/) team,
|
| 71 |
+
it is possible to download both cased and uncased models from their S3 storage 🤗
|
SimTranslation/bert_model/bert-base-german-dbmdz-uncased/config.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"BertForMaskedLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_probs_dropout_prob": 0.1,
|
| 6 |
+
"hidden_act": "gelu",
|
| 7 |
+
"hidden_dropout_prob": 0.1,
|
| 8 |
+
"hidden_size": 768,
|
| 9 |
+
"initializer_range": 0.02,
|
| 10 |
+
"intermediate_size": 3072,
|
| 11 |
+
"layer_norm_eps": 1e-12,
|
| 12 |
+
"max_position_embeddings": 512,
|
| 13 |
+
"model_type": "bert",
|
| 14 |
+
"num_attention_heads": 12,
|
| 15 |
+
"num_hidden_layers": 12,
|
| 16 |
+
"pad_token_id": 0,
|
| 17 |
+
"type_vocab_size": 2,
|
| 18 |
+
"vocab_size": 31102
|
| 19 |
+
}
|
SimTranslation/bert_model/bert-base-german-dbmdz-uncased/pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d5e34cff06116dfdb3dcc78f3ad9819c4b9dc3fd66e0cf7889776f9f548df2ec
|
| 3 |
+
size 442256365
|
SimTranslation/bert_model/bert-base-german-dbmdz-uncased/tokenizer_config.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"do_lower_case": true, "max_len": 512, "init_inputs": []}
|
SimTranslation/bert_model/bert-base-german-dbmdz-uncased/vocab.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
SimTranslation/bert_model/download_bert.sh
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# 下载 bert-base-german-dbmdz-uncased 模型权重
|
| 3 |
+
# 来源: HuggingFace (https://huggingface.co/dbmdz/bert-base-german-uncased)
|
| 4 |
+
# 优先使用国内镜像 hf-mirror.com,失败则回退到 huggingface.co
|
| 5 |
+
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
| 6 |
+
TARGET_DIR="${SCRIPT_DIR}/bert-base-german-dbmdz-uncased"
|
| 7 |
+
|
| 8 |
+
pip install huggingface_hub
|
| 9 |
+
|
| 10 |
+
# 尝试使用国内镜像下载
|
| 11 |
+
echo "尝试从国内镜像 hf-mirror.com 下载..."
|
| 12 |
+
if env HF_ENDPOINT=https://hf-mirror.com python3 -c "
|
| 13 |
+
from huggingface_hub import snapshot_download
|
| 14 |
+
snapshot_download('dbmdz/bert-base-german-uncased',
|
| 15 |
+
local_dir='${TARGET_DIR}',
|
| 16 |
+
local_dir_use_symlinks=False)
|
| 17 |
+
" 2>/dev/null; then
|
| 18 |
+
echo "BERT model downloaded (via mirror) to ${TARGET_DIR}/"
|
| 19 |
+
else
|
| 20 |
+
# 回退到官方源
|
| 21 |
+
echo "镜像失败,尝试官方源..."
|
| 22 |
+
python3 -c "
|
| 23 |
+
from huggingface_hub import snapshot_download
|
| 24 |
+
snapshot_download('dbmdz/bert-base-german-uncased',
|
| 25 |
+
local_dir='${TARGET_DIR}',
|
| 26 |
+
local_dir_use_symlinks=False)
|
| 27 |
+
"
|
| 28 |
+
echo "BERT model downloaded (via official) to ${TARGET_DIR}/"
|
| 29 |
+
fi
|
| 30 |
+
|
| 31 |
+
# 清理其他框架的权重,仅保留 PyTorch 格式 (~1.35GB 冗余)
|
| 32 |
+
echo "清理冗余格式..."
|
| 33 |
+
rm -f "${TARGET_DIR}/flax_model.msgpack" \
|
| 34 |
+
"${TARGET_DIR}/model.safetensors" \
|
| 35 |
+
"${TARGET_DIR}/tf_model.h5"
|
| 36 |
+
rm -rf "${TARGET_DIR}/.cache"
|
| 37 |
+
echo "完成,BERT 模型大小: $(du -sh ${TARGET_DIR} | cut -f1)"
|
SimTranslation/code/unibert_waitk_0901_stack/CODE_OF_CONDUCT.md
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Code of Conduct
|
| 2 |
+
|
| 3 |
+
## Our Pledge
|
| 4 |
+
|
| 5 |
+
In the interest of fostering an open and welcoming environment, we as
|
| 6 |
+
contributors and maintainers pledge to make participation in our project and
|
| 7 |
+
our community a harassment-free experience for everyone, regardless of age, body
|
| 8 |
+
size, disability, ethnicity, sex characteristics, gender identity and expression,
|
| 9 |
+
level of experience, education, socio-economic status, nationality, personal
|
| 10 |
+
appearance, race, religion, or sexual identity and orientation.
|
| 11 |
+
|
| 12 |
+
## Our Standards
|
| 13 |
+
|
| 14 |
+
Examples of behavior that contributes to creating a positive environment
|
| 15 |
+
include:
|
| 16 |
+
|
| 17 |
+
* Using welcoming and inclusive language
|
| 18 |
+
* Being respectful of differing viewpoints and experiences
|
| 19 |
+
* Gracefully accepting constructive criticism
|
| 20 |
+
* Focusing on what is best for the community
|
| 21 |
+
* Showing empathy towards other community members
|
| 22 |
+
|
| 23 |
+
Examples of unacceptable behavior by participants include:
|
| 24 |
+
|
| 25 |
+
* The use of sexualized language or imagery and unwelcome sexual attention or
|
| 26 |
+
advances
|
| 27 |
+
* Trolling, insulting/derogatory comments, and personal or political attacks
|
| 28 |
+
* Public or private harassment
|
| 29 |
+
* Publishing others' private information, such as a physical or electronic
|
| 30 |
+
address, without explicit permission
|
| 31 |
+
* Other conduct which could reasonably be considered inappropriate in a
|
| 32 |
+
professional setting
|
| 33 |
+
|
| 34 |
+
## Our Responsibilities
|
| 35 |
+
|
| 36 |
+
Project maintainers are responsible for clarifying the standards of acceptable
|
| 37 |
+
behavior and are expected to take appropriate and fair corrective action in
|
| 38 |
+
response to any instances of unacceptable behavior.
|
| 39 |
+
|
| 40 |
+
Project maintainers have the right and responsibility to remove, edit, or
|
| 41 |
+
reject comments, commits, code, wiki edits, issues, and other contributions
|
| 42 |
+
that are not aligned to this Code of Conduct, or to ban temporarily or
|
| 43 |
+
permanently any contributor for other behaviors that they deem inappropriate,
|
| 44 |
+
threatening, offensive, or harmful.
|
| 45 |
+
|
| 46 |
+
## Scope
|
| 47 |
+
|
| 48 |
+
This Code of Conduct applies within all project spaces, and it also applies when
|
| 49 |
+
an individual is representing the project or its community in public spaces.
|
| 50 |
+
Examples of representing a project or community include using an official
|
| 51 |
+
project e-mail address, posting via an official social media account, or acting
|
| 52 |
+
as an appointed representative at an online or offline event. Representation of
|
| 53 |
+
a project may be further defined and clarified by project maintainers.
|
| 54 |
+
|
| 55 |
+
## Enforcement
|
| 56 |
+
|
| 57 |
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
| 58 |
+
reported by contacting the project team at <conduct@pytorch.org>. All
|
| 59 |
+
complaints will be reviewed and investigated and will result in a response that
|
| 60 |
+
is deemed necessary and appropriate to the circumstances. The project team is
|
| 61 |
+
obligated to maintain confidentiality with regard to the reporter of an incident.
|
| 62 |
+
Further details of specific enforcement policies may be posted separately.
|
| 63 |
+
|
| 64 |
+
Project maintainers who do not follow or enforce the Code of Conduct in good
|
| 65 |
+
faith may face temporary or permanent repercussions as determined by other
|
| 66 |
+
members of the project's leadership.
|
| 67 |
+
|
| 68 |
+
## Attribution
|
| 69 |
+
|
| 70 |
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
| 71 |
+
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
| 72 |
+
|
| 73 |
+
[homepage]: https://www.contributor-covenant.org
|
| 74 |
+
|
| 75 |
+
For answers to common questions about this code of conduct, see
|
| 76 |
+
https://www.contributor-covenant.org/faq
|
| 77 |
+
|
SimTranslation/code/unibert_waitk_0901_stack/CONTRIBUTING.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Contributing to Facebook AI Research Sequence-to-Sequence Toolkit (fairseq)
|
| 2 |
+
We want to make contributing to this project as easy and transparent as
|
| 3 |
+
possible.
|
| 4 |
+
|
| 5 |
+
## Pull Requests
|
| 6 |
+
We actively welcome your pull requests.
|
| 7 |
+
|
| 8 |
+
1. Fork the repo and create your branch from `master`.
|
| 9 |
+
2. If you've added code that should be tested, add tests.
|
| 10 |
+
3. If you've changed APIs, update the documentation.
|
| 11 |
+
4. Ensure the test suite passes.
|
| 12 |
+
5. Make sure your code lints.
|
| 13 |
+
6. If you haven't already, complete the Contributor License Agreement ("CLA").
|
| 14 |
+
|
| 15 |
+
## Contributor License Agreement ("CLA")
|
| 16 |
+
In order to accept your pull request, we need you to submit a CLA. You only need
|
| 17 |
+
to do this once to work on any of Facebook's open source projects.
|
| 18 |
+
|
| 19 |
+
Complete your CLA here: <https://code.facebook.com/cla>
|
| 20 |
+
|
| 21 |
+
## Issues
|
| 22 |
+
We use GitHub issues to track public bugs. Please ensure your description is
|
| 23 |
+
clear and has sufficient instructions to be able to reproduce the issue.
|
| 24 |
+
|
| 25 |
+
## License
|
| 26 |
+
By contributing to Facebook AI Research Sequence-to-Sequence Toolkit (fairseq),
|
| 27 |
+
you agree that your contributions will be licensed under the LICENSE file in
|
| 28 |
+
the root directory of this source tree.
|
SimTranslation/code/unibert_waitk_0901_stack/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) Facebook, Inc. and its affiliates.
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
SimTranslation/code/unibert_waitk_0901_stack/README.md
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
This is a fork of Fairseq(-py) with implementations of the following models:
|
| 2 |
+
|
| 3 |
+
## Pervasive Attention - 2D Convolutional Neural Networks for Sequence-to-Sequence Prediction
|
| 4 |
+
|
| 5 |
+
An NMT models with two-dimensional convolutions to jointly encode the source and the target sequences.
|
| 6 |
+
|
| 7 |
+
Pervasive Attention also provides an extensive decoding grid that we leverage to efficiently train wait-k models.
|
| 8 |
+
|
| 9 |
+
See [README](examples/pervasive/README.md).
|
| 10 |
+
|
| 11 |
+
## Efficient Wait-k Models for Simultaneous Machine Translation
|
| 12 |
+
|
| 13 |
+
Transformer Wait-k models (Ma et al., 2019) with unidirectional encoders and with joint training of multiple wait-k paths.
|
| 14 |
+
|
| 15 |
+
See [README](examples/waitk/README.md).
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# Fairseq Requirements and Installation
|
| 19 |
+
|
| 20 |
+
* [PyTorch](http://pytorch.org/) version >= 1.4.0
|
| 21 |
+
* Python version >= 3.6
|
| 22 |
+
* For training new models, you'll also need an NVIDIA GPU and [NCCL](https://github.com/NVIDIA/nccl)
|
| 23 |
+
|
| 24 |
+
**Installing Fairseq**
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
git clone https://github.com/elbayadm/attn2d
|
| 28 |
+
cd attn2d
|
| 29 |
+
pip install --editable .
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
# License
|
| 33 |
+
fairseq(-py) is MIT-licensed.
|
| 34 |
+
The license applies to the pre-trained models as well.
|
| 35 |
+
|
| 36 |
+
# Citation
|
| 37 |
+
|
| 38 |
+
For Pervasive Attention, please cite:
|
| 39 |
+
|
| 40 |
+
```bibtex
|
| 41 |
+
@InProceedings{elbayad18conll,
|
| 42 |
+
author ="Elbayad, Maha and Besacier, Laurent and Verbeek, Jakob",
|
| 43 |
+
title = "Pervasive Attention: 2D Convolutional Neural Networks for Sequence-to-Sequence Prediction",
|
| 44 |
+
booktitle = "Proceedings of the 22nd Conference on Computational Natural Language Learning",
|
| 45 |
+
year = "2018",
|
| 46 |
+
}
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
For our wait-k models, please cite:
|
| 50 |
+
|
| 51 |
+
```bibtex
|
| 52 |
+
@article{elbayad20waitk,
|
| 53 |
+
title={Efficient Wait-k Models for Simultaneous Machine Translation},
|
| 54 |
+
author={Elbayad, Maha and Besacier, Laurent and Verbeek, Jakob},
|
| 55 |
+
journal={arXiv preprint arXiv:2005.08595},
|
| 56 |
+
year={2020}
|
| 57 |
+
}
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
For Fairseq, please cite:
|
| 61 |
+
|
| 62 |
+
```bibtex
|
| 63 |
+
@inproceedings{ott2019fairseq,
|
| 64 |
+
title = {fairseq: A Fast, Extensible Toolkit for Sequence Modeling},
|
| 65 |
+
author = {Myle Ott and Sergey Edunov and Alexei Baevski and Angela Fan and Sam Gross and Nathan Ng and David Grangier and Michael Auli},
|
| 66 |
+
booktitle = {Proceedings of NAACL-HLT 2019: Demonstrations},
|
| 67 |
+
year = {2019},
|
| 68 |
+
}
|
| 69 |
+
```
|
| 70 |
+
|
SimTranslation/code/unibert_waitk_0901_stack/bert/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .tokenization import BasicTokenizer, BertTokenizer
|
| 2 |
+
from .modeling import BertModel
|
SimTranslation/code/unibert_waitk_0901_stack/bert/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (330 Bytes). View file
|
|
|
SimTranslation/code/unibert_waitk_0901_stack/bert/__pycache__/file_utils.cpython-38.pyc
ADDED
|
Binary file (7.46 kB). View file
|
|
|
SimTranslation/code/unibert_waitk_0901_stack/bert/__pycache__/modeling.cpython-38.pyc
ADDED
|
Binary file (52 kB). View file
|
|
|
SimTranslation/code/unibert_waitk_0901_stack/bert/__pycache__/tokenization.cpython-38.pyc
ADDED
|
Binary file (13.5 kB). View file
|
|
|
SimTranslation/code/unibert_waitk_0901_stack/bert/file_utils.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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dataset cache.
|
| 3 |
+
This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp
|
| 4 |
+
Copyright by the AllenNLP authors.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import (absolute_import, division, print_function, unicode_literals)
|
| 7 |
+
|
| 8 |
+
import sys
|
| 9 |
+
import json
|
| 10 |
+
import logging
|
| 11 |
+
import os
|
| 12 |
+
import shutil
|
| 13 |
+
import tempfile
|
| 14 |
+
import fnmatch
|
| 15 |
+
from functools import wraps
|
| 16 |
+
from hashlib import sha256
|
| 17 |
+
import sys
|
| 18 |
+
from io import open
|
| 19 |
+
|
| 20 |
+
import boto3
|
| 21 |
+
import requests
|
| 22 |
+
from botocore.exceptions import ClientError
|
| 23 |
+
from tqdm import tqdm
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
from torch.hub import _get_torch_home
|
| 27 |
+
torch_cache_home = _get_torch_home()
|
| 28 |
+
except ImportError:
|
| 29 |
+
torch_cache_home = os.path.expanduser(
|
| 30 |
+
os.getenv('TORCH_HOME', os.path.join(
|
| 31 |
+
os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch')))
|
| 32 |
+
default_cache_path = os.path.join(torch_cache_home, 'pytorch_pretrained_bert')
|
| 33 |
+
|
| 34 |
+
try:
|
| 35 |
+
from urllib.parse import urlparse
|
| 36 |
+
except ImportError:
|
| 37 |
+
from urlparse import urlparse
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
from pathlib import Path
|
| 41 |
+
PYTORCH_PRETRAINED_BERT_CACHE = Path(
|
| 42 |
+
os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path))
|
| 43 |
+
except (AttributeError, ImportError):
|
| 44 |
+
PYTORCH_PRETRAINED_BERT_CACHE = os.getenv('PYTORCH_PRETRAINED_BERT_CACHE',
|
| 45 |
+
default_cache_path)
|
| 46 |
+
|
| 47 |
+
CONFIG_NAME = "config.json"
|
| 48 |
+
WEIGHTS_NAME = "pytorch_model.bin"
|
| 49 |
+
|
| 50 |
+
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def url_to_filename(url, etag=None):
|
| 54 |
+
"""
|
| 55 |
+
Convert `url` into a hashed filename in a repeatable way.
|
| 56 |
+
If `etag` is specified, append its hash to the url's, delimited
|
| 57 |
+
by a period.
|
| 58 |
+
"""
|
| 59 |
+
url_bytes = url.encode('utf-8')
|
| 60 |
+
url_hash = sha256(url_bytes)
|
| 61 |
+
filename = url_hash.hexdigest()
|
| 62 |
+
|
| 63 |
+
if etag:
|
| 64 |
+
etag_bytes = etag.encode('utf-8')
|
| 65 |
+
etag_hash = sha256(etag_bytes)
|
| 66 |
+
filename += '.' + etag_hash.hexdigest()
|
| 67 |
+
|
| 68 |
+
return filename
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def filename_to_url(filename, cache_dir=None):
|
| 72 |
+
"""
|
| 73 |
+
Return the url and etag (which may be ``None``) stored for `filename`.
|
| 74 |
+
Raise ``EnvironmentError`` if `filename` or its stored metadata do not exist.
|
| 75 |
+
"""
|
| 76 |
+
if cache_dir is None:
|
| 77 |
+
cache_dir = PYTORCH_PRETRAINED_BERT_CACHE
|
| 78 |
+
if sys.version_info[0] == 3 and isinstance(cache_dir, Path):
|
| 79 |
+
cache_dir = str(cache_dir)
|
| 80 |
+
|
| 81 |
+
cache_path = os.path.join(cache_dir, filename)
|
| 82 |
+
if not os.path.exists(cache_path):
|
| 83 |
+
raise EnvironmentError("file {} not found".format(cache_path))
|
| 84 |
+
|
| 85 |
+
meta_path = cache_path + '.json'
|
| 86 |
+
if not os.path.exists(meta_path):
|
| 87 |
+
raise EnvironmentError("file {} not found".format(meta_path))
|
| 88 |
+
|
| 89 |
+
with open(meta_path, encoding="utf-8") as meta_file:
|
| 90 |
+
metadata = json.load(meta_file)
|
| 91 |
+
url = metadata['url']
|
| 92 |
+
etag = metadata['etag']
|
| 93 |
+
|
| 94 |
+
return url, etag
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def cached_path(url_or_filename, cache_dir=None):
|
| 98 |
+
"""
|
| 99 |
+
Given something that might be a URL (or might be a local path),
|
| 100 |
+
determine which. If it's a URL, download the file and cache it, and
|
| 101 |
+
return the path to the cached file. If it's already a local path,
|
| 102 |
+
make sure the file exists and then return the path.
|
| 103 |
+
"""
|
| 104 |
+
if cache_dir is None:
|
| 105 |
+
cache_dir = PYTORCH_PRETRAINED_BERT_CACHE
|
| 106 |
+
if sys.version_info[0] == 3 and isinstance(url_or_filename, Path):
|
| 107 |
+
url_or_filename = str(url_or_filename)
|
| 108 |
+
if sys.version_info[0] == 3 and isinstance(cache_dir, Path):
|
| 109 |
+
cache_dir = str(cache_dir)
|
| 110 |
+
|
| 111 |
+
parsed = urlparse(url_or_filename)
|
| 112 |
+
|
| 113 |
+
if parsed.scheme in ('http', 'https', 's3'):
|
| 114 |
+
# URL, so get it from the cache (downloading if necessary)
|
| 115 |
+
return get_from_cache(url_or_filename, cache_dir)
|
| 116 |
+
elif os.path.exists(url_or_filename):
|
| 117 |
+
# File, and it exists.
|
| 118 |
+
return url_or_filename
|
| 119 |
+
elif parsed.scheme == '':
|
| 120 |
+
# File, but it doesn't exist.
|
| 121 |
+
raise EnvironmentError("file {} not found".format(url_or_filename))
|
| 122 |
+
else:
|
| 123 |
+
# Something unknown
|
| 124 |
+
raise ValueError("unable to parse {} as a URL or as a local path".format(url_or_filename))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def split_s3_path(url):
|
| 128 |
+
"""Split a full s3 path into the bucket name and path."""
|
| 129 |
+
parsed = urlparse(url)
|
| 130 |
+
if not parsed.netloc or not parsed.path:
|
| 131 |
+
raise ValueError("bad s3 path {}".format(url))
|
| 132 |
+
bucket_name = parsed.netloc
|
| 133 |
+
s3_path = parsed.path
|
| 134 |
+
# Remove '/' at beginning of path.
|
| 135 |
+
if s3_path.startswith("/"):
|
| 136 |
+
s3_path = s3_path[1:]
|
| 137 |
+
return bucket_name, s3_path
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def s3_request(func):
|
| 141 |
+
"""
|
| 142 |
+
Wrapper function for s3 requests in order to create more helpful error
|
| 143 |
+
messages.
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
@wraps(func)
|
| 147 |
+
def wrapper(url, *args, **kwargs):
|
| 148 |
+
try:
|
| 149 |
+
return func(url, *args, **kwargs)
|
| 150 |
+
except ClientError as exc:
|
| 151 |
+
if int(exc.response["Error"]["Code"]) == 404:
|
| 152 |
+
raise EnvironmentError("file {} not found".format(url))
|
| 153 |
+
else:
|
| 154 |
+
raise
|
| 155 |
+
|
| 156 |
+
return wrapper
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@s3_request
|
| 160 |
+
def s3_etag(url):
|
| 161 |
+
"""Check ETag on S3 object."""
|
| 162 |
+
s3_resource = boto3.resource("s3")
|
| 163 |
+
bucket_name, s3_path = split_s3_path(url)
|
| 164 |
+
s3_object = s3_resource.Object(bucket_name, s3_path)
|
| 165 |
+
return s3_object.e_tag
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
@s3_request
|
| 169 |
+
def s3_get(url, temp_file):
|
| 170 |
+
"""Pull a file directly from S3."""
|
| 171 |
+
s3_resource = boto3.resource("s3")
|
| 172 |
+
bucket_name, s3_path = split_s3_path(url)
|
| 173 |
+
s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def http_get(url, temp_file):
|
| 177 |
+
req = requests.get(url, stream=True)
|
| 178 |
+
content_length = req.headers.get('Content-Length')
|
| 179 |
+
total = int(content_length) if content_length is not None else None
|
| 180 |
+
progress = tqdm(unit="B", total=total)
|
| 181 |
+
for chunk in req.iter_content(chunk_size=1024):
|
| 182 |
+
if chunk: # filter out keep-alive new chunks
|
| 183 |
+
progress.update(len(chunk))
|
| 184 |
+
temp_file.write(chunk)
|
| 185 |
+
progress.close()
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def get_from_cache(url, cache_dir=None):
|
| 189 |
+
"""
|
| 190 |
+
Given a URL, look for the corresponding dataset in the local cache.
|
| 191 |
+
If it's not there, download it. Then return the path to the cached file.
|
| 192 |
+
"""
|
| 193 |
+
if cache_dir is None:
|
| 194 |
+
cache_dir = PYTORCH_PRETRAINED_BERT_CACHE
|
| 195 |
+
if sys.version_info[0] == 3 and isinstance(cache_dir, Path):
|
| 196 |
+
cache_dir = str(cache_dir)
|
| 197 |
+
|
| 198 |
+
if not os.path.exists(cache_dir):
|
| 199 |
+
os.makedirs(cache_dir)
|
| 200 |
+
|
| 201 |
+
# Get eTag to add to filename, if it exists.
|
| 202 |
+
if url.startswith("s3://"):
|
| 203 |
+
etag = s3_etag(url)
|
| 204 |
+
else:
|
| 205 |
+
try:
|
| 206 |
+
response = requests.head(url, allow_redirects=True)
|
| 207 |
+
if response.status_code != 200:
|
| 208 |
+
etag = None
|
| 209 |
+
else:
|
| 210 |
+
etag = response.headers.get("ETag")
|
| 211 |
+
except EnvironmentError:
|
| 212 |
+
etag = None
|
| 213 |
+
|
| 214 |
+
if sys.version_info[0] == 2 and etag is not None:
|
| 215 |
+
etag = etag.decode('utf-8')
|
| 216 |
+
filename = url_to_filename(url, etag)
|
| 217 |
+
|
| 218 |
+
# get cache path to put the file
|
| 219 |
+
cache_path = os.path.join(cache_dir, filename)
|
| 220 |
+
|
| 221 |
+
# If we don't have a connection (etag is None) and can't identify the file
|
| 222 |
+
# try to get the last downloaded one
|
| 223 |
+
if not os.path.exists(cache_path) and etag is None:
|
| 224 |
+
matching_files = fnmatch.filter(os.listdir(cache_dir), filename + '.*')
|
| 225 |
+
matching_files = list(filter(lambda s: not s.endswith('.json'), matching_files))
|
| 226 |
+
if matching_files:
|
| 227 |
+
cache_path = os.path.join(cache_dir, matching_files[-1])
|
| 228 |
+
|
| 229 |
+
if not os.path.exists(cache_path):
|
| 230 |
+
# Download to temporary file, then copy to cache dir once finished.
|
| 231 |
+
# Otherwise you get corrupt cache entries if the download gets interrupted.
|
| 232 |
+
with tempfile.NamedTemporaryFile() as temp_file:
|
| 233 |
+
logger.info("%s not found in cache, downloading to %s", url, temp_file.name)
|
| 234 |
+
|
| 235 |
+
# GET file object
|
| 236 |
+
if url.startswith("s3://"):
|
| 237 |
+
s3_get(url, temp_file)
|
| 238 |
+
else:
|
| 239 |
+
http_get(url, temp_file)
|
| 240 |
+
|
| 241 |
+
# we are copying the file before closing it, so flush to avoid truncation
|
| 242 |
+
temp_file.flush()
|
| 243 |
+
# shutil.copyfileobj() starts at the current position, so go to the start
|
| 244 |
+
temp_file.seek(0)
|
| 245 |
+
|
| 246 |
+
logger.info("copying %s to cache at %s", temp_file.name, cache_path)
|
| 247 |
+
with open(cache_path, 'wb') as cache_file:
|
| 248 |
+
shutil.copyfileobj(temp_file, cache_file)
|
| 249 |
+
|
| 250 |
+
logger.info("creating metadata file for %s", cache_path)
|
| 251 |
+
meta = {'url': url, 'etag': etag}
|
| 252 |
+
meta_path = cache_path + '.json'
|
| 253 |
+
with open(meta_path, 'w') as meta_file:
|
| 254 |
+
output_string = json.dumps(meta)
|
| 255 |
+
if sys.version_info[0] == 2 and isinstance(output_string, str):
|
| 256 |
+
output_string = unicode(output_string, 'utf-8') # The beauty of python 2
|
| 257 |
+
meta_file.write(output_string)
|
| 258 |
+
|
| 259 |
+
logger.info("removing temp file %s", temp_file.name)
|
| 260 |
+
|
| 261 |
+
return cache_path
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def read_set_from_file(filename):
|
| 265 |
+
'''
|
| 266 |
+
Extract a de-duped collection (set) of text from a file.
|
| 267 |
+
Expected file format is one item per line.
|
| 268 |
+
'''
|
| 269 |
+
collection = set()
|
| 270 |
+
with open(filename, 'r', encoding='utf-8') as file_:
|
| 271 |
+
for line in file_:
|
| 272 |
+
collection.add(line.rstrip())
|
| 273 |
+
return collection
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def get_file_extension(path, dot=True, lower=True):
|
| 277 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""PyTorch BERT model."""
|
| 17 |
+
|
| 18 |
+
from __future__ import absolute_import, division, print_function, unicode_literals
|
| 19 |
+
|
| 20 |
+
import copy
|
| 21 |
+
import json
|
| 22 |
+
import logging
|
| 23 |
+
import math
|
| 24 |
+
import os
|
| 25 |
+
import shutil
|
| 26 |
+
import tarfile
|
| 27 |
+
import tempfile
|
| 28 |
+
import sys
|
| 29 |
+
from io import open
|
| 30 |
+
|
| 31 |
+
import torch
|
| 32 |
+
from torch import nn
|
| 33 |
+
from torch.nn import CrossEntropyLoss
|
| 34 |
+
|
| 35 |
+
from fairseq import utils
|
| 36 |
+
|
| 37 |
+
from .file_utils import cached_path, WEIGHTS_NAME, CONFIG_NAME
|
| 38 |
+
|
| 39 |
+
logger = logging.getLogger(__name__)
|
| 40 |
+
|
| 41 |
+
PRETRAINED_MODEL_ARCHIVE_MAP = {
|
| 42 |
+
'bert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased.tar.gz",
|
| 43 |
+
'bert-large-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased.tar.gz",
|
| 44 |
+
'bert-base-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased.tar.gz",
|
| 45 |
+
'bert-large-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased.tar.gz",
|
| 46 |
+
'bert-base-multilingual-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased.tar.gz",
|
| 47 |
+
'bert-base-multilingual-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased.tar.gz",
|
| 48 |
+
'bert-base-chinese': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese.tar.gz",
|
| 49 |
+
'bert-base-german-cased': "https://int-deepset-models-bert.s3.eu-central-1.amazonaws.com/pytorch/bert-base-german-cased.tar.gz",
|
| 50 |
+
}
|
| 51 |
+
BERT_CONFIG_NAME = 'bert_config.json'
|
| 52 |
+
TF_WEIGHTS_NAME = 'model.ckpt'
|
| 53 |
+
|
| 54 |
+
def load_tf_weights_in_bert(model, tf_checkpoint_path):
|
| 55 |
+
""" Load tf checkpoints in a pytorch model
|
| 56 |
+
"""
|
| 57 |
+
try:
|
| 58 |
+
import re
|
| 59 |
+
import numpy as np
|
| 60 |
+
import tensorflow as tf
|
| 61 |
+
except ImportError:
|
| 62 |
+
print("Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see "
|
| 63 |
+
"https://www.tensorflow.org/install/ for installation instructions.")
|
| 64 |
+
raise
|
| 65 |
+
tf_path = os.path.abspath(tf_checkpoint_path)
|
| 66 |
+
print("Converting TensorFlow checkpoint from {}".format(tf_path))
|
| 67 |
+
# Load weights from TF model
|
| 68 |
+
init_vars = tf.train.list_variables(tf_path)
|
| 69 |
+
names = []
|
| 70 |
+
arrays = []
|
| 71 |
+
for name, shape in init_vars:
|
| 72 |
+
print("Loading TF weight {} with shape {}".format(name, shape))
|
| 73 |
+
array = tf.train.load_variable(tf_path, name)
|
| 74 |
+
names.append(name)
|
| 75 |
+
arrays.append(array)
|
| 76 |
+
|
| 77 |
+
for name, array in zip(names, arrays):
|
| 78 |
+
name = name.split('/')
|
| 79 |
+
# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
|
| 80 |
+
# which are not required for using pretrained model
|
| 81 |
+
if any(n in ["adam_v", "adam_m", "global_step"] for n in name):
|
| 82 |
+
print("Skipping {}".format("/".join(name)))
|
| 83 |
+
continue
|
| 84 |
+
pointer = model
|
| 85 |
+
for m_name in name:
|
| 86 |
+
if re.fullmatch(r'[A-Za-z]+_\d+', m_name):
|
| 87 |
+
l = re.split(r'_(\d+)', m_name)
|
| 88 |
+
else:
|
| 89 |
+
l = [m_name]
|
| 90 |
+
if l[0] == 'kernel' or l[0] == 'gamma':
|
| 91 |
+
pointer = getattr(pointer, 'weight')
|
| 92 |
+
elif l[0] == 'output_bias' or l[0] == 'beta':
|
| 93 |
+
pointer = getattr(pointer, 'bias')
|
| 94 |
+
elif l[0] == 'output_weights':
|
| 95 |
+
pointer = getattr(pointer, 'weight')
|
| 96 |
+
elif l[0] == 'squad':
|
| 97 |
+
pointer = getattr(pointer, 'classifier')
|
| 98 |
+
else:
|
| 99 |
+
try:
|
| 100 |
+
pointer = getattr(pointer, l[0])
|
| 101 |
+
except AttributeError:
|
| 102 |
+
print("Skipping {}".format("/".join(name)))
|
| 103 |
+
continue
|
| 104 |
+
if len(l) >= 2:
|
| 105 |
+
num = int(l[1])
|
| 106 |
+
pointer = pointer[num]
|
| 107 |
+
if m_name[-11:] == '_embeddings':
|
| 108 |
+
pointer = getattr(pointer, 'weight')
|
| 109 |
+
elif m_name == 'kernel':
|
| 110 |
+
array = np.transpose(array)
|
| 111 |
+
try:
|
| 112 |
+
assert pointer.shape == array.shape
|
| 113 |
+
except AssertionError as e:
|
| 114 |
+
e.args += (pointer.shape, array.shape)
|
| 115 |
+
raise
|
| 116 |
+
print("Initialize PyTorch weight {}".format(name))
|
| 117 |
+
pointer.data = torch.from_numpy(array)
|
| 118 |
+
return model
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def gelu(x):
|
| 122 |
+
"""Implementation of the gelu activation function.
|
| 123 |
+
For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
|
| 124 |
+
0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
|
| 125 |
+
Also see https://arxiv.org/abs/1606.08415
|
| 126 |
+
"""
|
| 127 |
+
return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def swish(x):
|
| 131 |
+
return x * torch.sigmoid(x)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
ACT2FN = {"gelu": gelu, "relu": torch.nn.functional.relu, "swish": swish}
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class BertConfig(object):
|
| 138 |
+
"""Configuration class to store the configuration of a `BertModel`.
|
| 139 |
+
"""
|
| 140 |
+
def __init__(self,
|
| 141 |
+
vocab_size_or_config_json_file,
|
| 142 |
+
hidden_size=768,
|
| 143 |
+
num_hidden_layers=12,
|
| 144 |
+
num_attention_heads=12,
|
| 145 |
+
intermediate_size=3072,
|
| 146 |
+
hidden_act="gelu",
|
| 147 |
+
hidden_dropout_prob=0.1,
|
| 148 |
+
attention_probs_dropout_prob=0.1,
|
| 149 |
+
max_position_embeddings=512,
|
| 150 |
+
type_vocab_size=2,
|
| 151 |
+
initializer_range=0.02,
|
| 152 |
+
layer_norm_eps=1e-12):
|
| 153 |
+
"""Constructs BertConfig.
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
vocab_size_or_config_json_file: Vocabulary size of `inputs_ids` in `BertModel`.
|
| 157 |
+
hidden_size: Size of the encoder layers and the pooler layer.
|
| 158 |
+
num_hidden_layers: Number of hidden layers in the Transformer encoder.
|
| 159 |
+
num_attention_heads: Number of attention heads for each attention layer in
|
| 160 |
+
the Transformer encoder.
|
| 161 |
+
intermediate_size: The size of the "intermediate" (i.e., feed-forward)
|
| 162 |
+
layer in the Transformer encoder.
|
| 163 |
+
hidden_act: The non-linear activation function (function or string) in the
|
| 164 |
+
encoder and pooler. If string, "gelu", "relu" and "swish" are supported.
|
| 165 |
+
hidden_dropout_prob: The dropout probabilitiy for all fully connected
|
| 166 |
+
layers in the embeddings, encoder, and pooler.
|
| 167 |
+
attention_probs_dropout_prob: The dropout ratio for the attention
|
| 168 |
+
probabilities.
|
| 169 |
+
max_position_embeddings: The maximum sequence length that this model might
|
| 170 |
+
ever be used with. Typically set this to something large just in case
|
| 171 |
+
(e.g., 512 or 1024 or 2048).
|
| 172 |
+
type_vocab_size: The vocabulary size of the `token_type_ids` passed into
|
| 173 |
+
`BertModel`.
|
| 174 |
+
initializer_range: The sttdev of the truncated_normal_initializer for
|
| 175 |
+
initializing all weight matrices.
|
| 176 |
+
layer_norm_eps: The epsilon used by LayerNorm.
|
| 177 |
+
"""
|
| 178 |
+
if isinstance(vocab_size_or_config_json_file, str) or (sys.version_info[0] == 2
|
| 179 |
+
and isinstance(vocab_size_or_config_json_file, unicode)):
|
| 180 |
+
with open(vocab_size_or_config_json_file, "r", encoding='utf-8') as reader:
|
| 181 |
+
json_config = json.loads(reader.read())
|
| 182 |
+
for key, value in json_config.items():
|
| 183 |
+
self.__dict__[key] = value
|
| 184 |
+
elif isinstance(vocab_size_or_config_json_file, int):
|
| 185 |
+
self.vocab_size = vocab_size_or_config_json_file
|
| 186 |
+
self.hidden_size = hidden_size
|
| 187 |
+
self.num_hidden_layers = num_hidden_layers
|
| 188 |
+
self.num_attention_heads = num_attention_heads
|
| 189 |
+
self.hidden_act = hidden_act
|
| 190 |
+
self.intermediate_size = intermediate_size
|
| 191 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 192 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 193 |
+
self.max_position_embeddings = max_position_embeddings
|
| 194 |
+
self.type_vocab_size = type_vocab_size
|
| 195 |
+
self.initializer_range = initializer_range
|
| 196 |
+
self.layer_norm_eps = layer_norm_eps
|
| 197 |
+
else:
|
| 198 |
+
raise ValueError("First argument must be either a vocabulary size (int)"
|
| 199 |
+
"or the path to a pretrained model config file (str)")
|
| 200 |
+
|
| 201 |
+
@classmethod
|
| 202 |
+
def from_dict(cls, json_object):
|
| 203 |
+
"""Constructs a `BertConfig` from a Python dictionary of parameters."""
|
| 204 |
+
config = BertConfig(vocab_size_or_config_json_file=-1)
|
| 205 |
+
for key, value in json_object.items():
|
| 206 |
+
config.__dict__[key] = value
|
| 207 |
+
return config
|
| 208 |
+
|
| 209 |
+
@classmethod
|
| 210 |
+
def from_json_file(cls, json_file):
|
| 211 |
+
"""Constructs a `BertConfig` from a json file of parameters."""
|
| 212 |
+
with open(json_file, "r", encoding='utf-8') as reader:
|
| 213 |
+
text = reader.read()
|
| 214 |
+
return cls.from_dict(json.loads(text))
|
| 215 |
+
|
| 216 |
+
def __repr__(self):
|
| 217 |
+
return str(self.to_json_string())
|
| 218 |
+
|
| 219 |
+
def to_dict(self):
|
| 220 |
+
"""Serializes this instance to a Python dictionary."""
|
| 221 |
+
output = copy.deepcopy(self.__dict__)
|
| 222 |
+
return output
|
| 223 |
+
|
| 224 |
+
def to_json_string(self):
|
| 225 |
+
"""Serializes this instance to a JSON string."""
|
| 226 |
+
return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
|
| 227 |
+
|
| 228 |
+
def to_json_file(self, json_file_path):
|
| 229 |
+
""" Save this instance to a json file."""
|
| 230 |
+
with open(json_file_path, "w", encoding='utf-8') as writer:
|
| 231 |
+
writer.write(self.to_json_string())
|
| 232 |
+
|
| 233 |
+
try:
|
| 234 |
+
from apex.normalization.fused_layer_norm import FusedLayerNorm as BertLayerNorm
|
| 235 |
+
except ImportError:
|
| 236 |
+
logger.info("Better speed can be achieved with apex installed from https://www.github.com/nvidia/apex .")
|
| 237 |
+
class BertLayerNorm(nn.Module):
|
| 238 |
+
def __init__(self, hidden_size, eps=1e-12):
|
| 239 |
+
"""Construct a layernorm module in the TF style (epsilon inside the square root).
|
| 240 |
+
"""
|
| 241 |
+
super(BertLayerNorm, self).__init__()
|
| 242 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 243 |
+
self.bias = nn.Parameter(torch.zeros(hidden_size))
|
| 244 |
+
self.variance_epsilon = eps
|
| 245 |
+
|
| 246 |
+
def forward(self, x):
|
| 247 |
+
u = x.mean(-1, keepdim=True)
|
| 248 |
+
s = (x - u).pow(2).mean(-1, keepdim=True)
|
| 249 |
+
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
|
| 250 |
+
return self.weight * x + self.bias
|
| 251 |
+
|
| 252 |
+
class BertEmbeddings(nn.Module):
|
| 253 |
+
"""Construct the embeddings from word, position and token_type embeddings.
|
| 254 |
+
"""
|
| 255 |
+
def __init__(self, config):
|
| 256 |
+
super(BertEmbeddings, self).__init__()
|
| 257 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=0)
|
| 258 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 259 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
| 260 |
+
|
| 261 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 262 |
+
# any TensorFlow checkpoint file
|
| 263 |
+
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 264 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 265 |
+
|
| 266 |
+
def forward(self, input_ids, token_type_ids=None):
|
| 267 |
+
seq_length = input_ids.size(1)
|
| 268 |
+
position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device)
|
| 269 |
+
position_ids = position_ids.unsqueeze(0).expand_as(input_ids)
|
| 270 |
+
if token_type_ids is None:
|
| 271 |
+
token_type_ids = torch.zeros_like(input_ids)
|
| 272 |
+
|
| 273 |
+
words_embeddings = self.word_embeddings(input_ids)
|
| 274 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 275 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 276 |
+
|
| 277 |
+
embeddings = words_embeddings + position_embeddings + token_type_embeddings
|
| 278 |
+
embeddings = self.LayerNorm(embeddings)
|
| 279 |
+
embeddings = self.dropout(embeddings)
|
| 280 |
+
return embeddings
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class BertSelfAttention(nn.Module):
|
| 284 |
+
def __init__(self, config):
|
| 285 |
+
super(BertSelfAttention, self).__init__()
|
| 286 |
+
if config.hidden_size % config.num_attention_heads != 0:
|
| 287 |
+
raise ValueError(
|
| 288 |
+
"The hidden size (%d) is not a multiple of the number of attention "
|
| 289 |
+
"heads (%d)" % (config.hidden_size, config.num_attention_heads))
|
| 290 |
+
self.num_attention_heads = config.num_attention_heads
|
| 291 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 292 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 293 |
+
|
| 294 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 295 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 296 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 297 |
+
|
| 298 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 299 |
+
|
| 300 |
+
def transpose_for_scores(self, x):
|
| 301 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 302 |
+
x = x.view(*new_x_shape)
|
| 303 |
+
return x.permute(0, 2, 1, 3)
|
| 304 |
+
|
| 305 |
+
def forward(self, hidden_states, attention_mask):
|
| 306 |
+
mixed_query_layer = self.query(hidden_states)
|
| 307 |
+
mixed_key_layer = self.key(hidden_states)
|
| 308 |
+
mixed_value_layer = self.value(hidden_states)
|
| 309 |
+
|
| 310 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 311 |
+
key_layer = self.transpose_for_scores(mixed_key_layer)
|
| 312 |
+
value_layer = self.transpose_for_scores(mixed_value_layer)
|
| 313 |
+
|
| 314 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 315 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 316 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 317 |
+
|
| 318 |
+
# 加入单向注意力机制 (直接创建在 GPU 上,避免 CPU→GPU 传输)
|
| 319 |
+
add_uniatten=True
|
| 320 |
+
if add_uniatten:
|
| 321 |
+
seq_len = attention_mask.size()[-1]
|
| 322 |
+
uniatten_mask = attention_scores.new_full((seq_len, seq_len), float('-inf'))
|
| 323 |
+
uniatten_mask = torch.triu(uniatten_mask, diagonal=1)
|
| 324 |
+
uniatten_mask_expanded = uniatten_mask.unsqueeze(0).unsqueeze(0)
|
| 325 |
+
attention_scores = attention_scores + attention_mask + uniatten_mask_expanded
|
| 326 |
+
else:
|
| 327 |
+
attention_scores = attention_scores + attention_mask
|
| 328 |
+
|
| 329 |
+
# Normalize the attention scores to probabilities.
|
| 330 |
+
attention_probs = nn.Softmax(dim=-1)(attention_scores)
|
| 331 |
+
|
| 332 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 333 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 334 |
+
attention_probs = self.dropout(attention_probs)
|
| 335 |
+
|
| 336 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 337 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 338 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 339 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
| 340 |
+
return context_layer
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
class BertSelfOutput(nn.Module):
|
| 344 |
+
def __init__(self, config):
|
| 345 |
+
super(BertSelfOutput, self).__init__()
|
| 346 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 347 |
+
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 348 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 349 |
+
|
| 350 |
+
def forward(self, hidden_states, input_tensor):
|
| 351 |
+
hidden_states = self.dense(hidden_states)
|
| 352 |
+
hidden_states = self.dropout(hidden_states)
|
| 353 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 354 |
+
return hidden_states
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
class BertAttention(nn.Module):
|
| 358 |
+
def __init__(self, config):
|
| 359 |
+
super(BertAttention, self).__init__()
|
| 360 |
+
self.self = BertSelfAttention(config)
|
| 361 |
+
self.output = BertSelfOutput(config)
|
| 362 |
+
|
| 363 |
+
def forward(self, input_tensor, attention_mask):
|
| 364 |
+
self_output = self.self(input_tensor, attention_mask)
|
| 365 |
+
attention_output = self.output(self_output, input_tensor)
|
| 366 |
+
return attention_output
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
class BertIntermediate(nn.Module):
|
| 370 |
+
def __init__(self, config):
|
| 371 |
+
super(BertIntermediate, self).__init__()
|
| 372 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 373 |
+
if isinstance(config.hidden_act, str) or (sys.version_info[0] == 2 and isinstance(config.hidden_act, unicode)):
|
| 374 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 375 |
+
else:
|
| 376 |
+
self.intermediate_act_fn = config.hidden_act
|
| 377 |
+
|
| 378 |
+
def forward(self, hidden_states):
|
| 379 |
+
hidden_states = self.dense(hidden_states)
|
| 380 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 381 |
+
return hidden_states
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
class BertOutput(nn.Module):
|
| 385 |
+
def __init__(self, config):
|
| 386 |
+
super(BertOutput, self).__init__()
|
| 387 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 388 |
+
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 389 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 390 |
+
|
| 391 |
+
def forward(self, hidden_states, input_tensor):
|
| 392 |
+
hidden_states = self.dense(hidden_states)
|
| 393 |
+
hidden_states = self.dropout(hidden_states)
|
| 394 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 395 |
+
return hidden_states
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
class BertLayer(nn.Module):
|
| 399 |
+
def __init__(self, config):
|
| 400 |
+
super(BertLayer, self).__init__()
|
| 401 |
+
self.attention = BertAttention(config)
|
| 402 |
+
self.intermediate = BertIntermediate(config)
|
| 403 |
+
self.output = BertOutput(config)
|
| 404 |
+
|
| 405 |
+
def forward(self, hidden_states, attention_mask):
|
| 406 |
+
attention_output = self.attention(hidden_states, attention_mask)
|
| 407 |
+
intermediate_output = self.intermediate(attention_output)
|
| 408 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 409 |
+
return layer_output
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
class BertEncoder(nn.Module):
|
| 413 |
+
def __init__(self, config):
|
| 414 |
+
super(BertEncoder, self).__init__()
|
| 415 |
+
layer = BertLayer(config)
|
| 416 |
+
self.layer = nn.ModuleList([copy.deepcopy(layer) for _ in range(config.num_hidden_layers)])
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def forward(self, hidden_states, attention_mask, output_all_encoded_layers=True):
|
| 420 |
+
all_encoder_layers = []
|
| 421 |
+
for layer_module in self.layer:
|
| 422 |
+
|
| 423 |
+
hidden_states = layer_module(hidden_states, attention_mask)
|
| 424 |
+
if output_all_encoded_layers:
|
| 425 |
+
all_encoder_layers.append(hidden_states)
|
| 426 |
+
if not output_all_encoded_layers:
|
| 427 |
+
all_encoder_layers.append(hidden_states)
|
| 428 |
+
return all_encoder_layers
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
class BertPooler(nn.Module):
|
| 432 |
+
def __init__(self, config):
|
| 433 |
+
super(BertPooler, self).__init__()
|
| 434 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 435 |
+
self.activation = nn.Tanh()
|
| 436 |
+
|
| 437 |
+
def forward(self, hidden_states):
|
| 438 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 439 |
+
# to the first token.
|
| 440 |
+
first_token_tensor = hidden_states[:, 0]
|
| 441 |
+
pooled_output = self.dense(first_token_tensor)
|
| 442 |
+
pooled_output = self.activation(pooled_output)
|
| 443 |
+
return pooled_output
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
class BertPredictionHeadTransform(nn.Module):
|
| 447 |
+
def __init__(self, config):
|
| 448 |
+
super(BertPredictionHeadTransform, self).__init__()
|
| 449 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 450 |
+
if isinstance(config.hidden_act, str) or (sys.version_info[0] == 2 and isinstance(config.hidden_act, unicode)):
|
| 451 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
| 452 |
+
else:
|
| 453 |
+
self.transform_act_fn = config.hidden_act
|
| 454 |
+
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 455 |
+
|
| 456 |
+
def forward(self, hidden_states):
|
| 457 |
+
hidden_states = self.dense(hidden_states)
|
| 458 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
| 459 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 460 |
+
return hidden_states
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
class BertLMPredictionHead(nn.Module):
|
| 464 |
+
def __init__(self, config, bert_model_embedding_weights):
|
| 465 |
+
super(BertLMPredictionHead, self).__init__()
|
| 466 |
+
self.transform = BertPredictionHeadTransform(config)
|
| 467 |
+
|
| 468 |
+
# The output weights are the same as the input embeddings, but there is
|
| 469 |
+
# an output-only bias for each token.
|
| 470 |
+
self.decoder = nn.Linear(bert_model_embedding_weights.size(1),
|
| 471 |
+
bert_model_embedding_weights.size(0),
|
| 472 |
+
bias=False)
|
| 473 |
+
self.decoder.weight = bert_model_embedding_weights
|
| 474 |
+
self.bias = nn.Parameter(torch.zeros(bert_model_embedding_weights.size(0)))
|
| 475 |
+
|
| 476 |
+
def forward(self, hidden_states):
|
| 477 |
+
hidden_states = self.transform(hidden_states)
|
| 478 |
+
hidden_states = self.decoder(hidden_states) + self.bias
|
| 479 |
+
return hidden_states
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
class BertOnlyMLMHead(nn.Module):
|
| 483 |
+
def __init__(self, config, bert_model_embedding_weights):
|
| 484 |
+
super(BertOnlyMLMHead, self).__init__()
|
| 485 |
+
self.predictions = BertLMPredictionHead(config, bert_model_embedding_weights)
|
| 486 |
+
|
| 487 |
+
def forward(self, sequence_output):
|
| 488 |
+
prediction_scores = self.predictions(sequence_output)
|
| 489 |
+
return prediction_scores
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
class BertOnlyNSPHead(nn.Module):
|
| 493 |
+
def __init__(self, config):
|
| 494 |
+
super(BertOnlyNSPHead, self).__init__()
|
| 495 |
+
self.seq_relationship = nn.Linear(config.hidden_size, 2)
|
| 496 |
+
|
| 497 |
+
def forward(self, pooled_output):
|
| 498 |
+
seq_relationship_score = self.seq_relationship(pooled_output)
|
| 499 |
+
return seq_relationship_score
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
class BertPreTrainingHeads(nn.Module):
|
| 503 |
+
def __init__(self, config, bert_model_embedding_weights):
|
| 504 |
+
super(BertPreTrainingHeads, self).__init__()
|
| 505 |
+
self.predictions = BertLMPredictionHead(config, bert_model_embedding_weights)
|
| 506 |
+
self.seq_relationship = nn.Linear(config.hidden_size, 2)
|
| 507 |
+
|
| 508 |
+
def forward(self, sequence_output, pooled_output):
|
| 509 |
+
prediction_scores = self.predictions(sequence_output)
|
| 510 |
+
seq_relationship_score = self.seq_relationship(pooled_output)
|
| 511 |
+
return prediction_scores, seq_relationship_score
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
class BertPreTrainedModel(nn.Module):
|
| 515 |
+
""" An abstract class to handle weights initialization and
|
| 516 |
+
a simple interface for dowloading and loading pretrained models.
|
| 517 |
+
"""
|
| 518 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 519 |
+
super(BertPreTrainedModel, self).__init__()
|
| 520 |
+
if not isinstance(config, BertConfig):
|
| 521 |
+
raise ValueError(
|
| 522 |
+
"Parameter config in `{}(config)` should be an instance of class `BertConfig`. "
|
| 523 |
+
"To create a model from a Google pretrained model use "
|
| 524 |
+
"`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`".format(
|
| 525 |
+
self.__class__.__name__, self.__class__.__name__
|
| 526 |
+
))
|
| 527 |
+
self.config = config
|
| 528 |
+
|
| 529 |
+
def init_bert_weights(self, module):
|
| 530 |
+
""" Initialize the weights.
|
| 531 |
+
"""
|
| 532 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
| 533 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 534 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 535 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 536 |
+
elif isinstance(module, BertLayerNorm):
|
| 537 |
+
module.bias.data.zero_()
|
| 538 |
+
module.weight.data.fill_(1.0)
|
| 539 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
| 540 |
+
module.bias.data.zero_()
|
| 541 |
+
|
| 542 |
+
@classmethod
|
| 543 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):
|
| 544 |
+
"""
|
| 545 |
+
Instantiate a BertPreTrainedModel from a pre-trained model file or a pytorch state dict.
|
| 546 |
+
Download and cache the pre-trained model file if needed.
|
| 547 |
+
|
| 548 |
+
Params:
|
| 549 |
+
pretrained_model_name_or_path: either:
|
| 550 |
+
- a str with the name of a pre-trained model to load selected in the list of:
|
| 551 |
+
. `bert-base-uncased`
|
| 552 |
+
. `bert-large-uncased`
|
| 553 |
+
. `bert-base-cased`
|
| 554 |
+
. `bert-large-cased`
|
| 555 |
+
. `bert-base-multilingual-uncased`
|
| 556 |
+
. `bert-base-multilingual-cased`
|
| 557 |
+
. `bert-base-chinese`
|
| 558 |
+
- a path or url to a pretrained model archive containing:
|
| 559 |
+
. `bert_config.json` a configuration file for the model
|
| 560 |
+
. `pytorch_model.bin` a PyTorch dump of a BertForPreTraining instance
|
| 561 |
+
- a path or url to a pretrained model archive containing:
|
| 562 |
+
. `bert_config.json` a configuration file for the model
|
| 563 |
+
. `model.chkpt` a TensorFlow checkpoint
|
| 564 |
+
from_tf: should we load the weights from a locally saved TensorFlow checkpoint
|
| 565 |
+
cache_dir: an optional path to a folder in which the pre-trained models will be cached.
|
| 566 |
+
state_dict: an optional state dictionnary (collections.OrderedDict object) to use instead of Google pre-trained models
|
| 567 |
+
*inputs, **kwargs: additional input for the specific Bert class
|
| 568 |
+
(ex: num_labels for BertForSequenceClassification)
|
| 569 |
+
"""
|
| 570 |
+
state_dict = kwargs.get('state_dict', None)
|
| 571 |
+
kwargs.pop('state_dict', None)
|
| 572 |
+
cache_dir = kwargs.get('cache_dir', None)
|
| 573 |
+
kwargs.pop('cache_dir', None)
|
| 574 |
+
from_tf = kwargs.get('from_tf', False)
|
| 575 |
+
kwargs.pop('from_tf', None)
|
| 576 |
+
|
| 577 |
+
if pretrained_model_name_or_path in PRETRAINED_MODEL_ARCHIVE_MAP:
|
| 578 |
+
archive_file = PRETRAINED_MODEL_ARCHIVE_MAP[pretrained_model_name_or_path]
|
| 579 |
+
else:
|
| 580 |
+
archive_file = pretrained_model_name_or_path
|
| 581 |
+
# redirect to the cache, if necessary
|
| 582 |
+
try:
|
| 583 |
+
resolved_archive_file = cached_path(archive_file, cache_dir=cache_dir)
|
| 584 |
+
except EnvironmentError:
|
| 585 |
+
logger.error(
|
| 586 |
+
"Model name '{}' was not found in model name list ({}). "
|
| 587 |
+
"We assumed '{}' was a path or url but couldn't find any file "
|
| 588 |
+
"associated to this path or url.".format(
|
| 589 |
+
pretrained_model_name_or_path,
|
| 590 |
+
', '.join(PRETRAINED_MODEL_ARCHIVE_MAP.keys()),
|
| 591 |
+
archive_file))
|
| 592 |
+
return None
|
| 593 |
+
if resolved_archive_file == archive_file:
|
| 594 |
+
logger.info("loading archive file {}".format(archive_file))
|
| 595 |
+
else:
|
| 596 |
+
logger.info("loading archive file {} from cache at {}".format(
|
| 597 |
+
archive_file, resolved_archive_file))
|
| 598 |
+
tempdir = None
|
| 599 |
+
if os.path.isdir(resolved_archive_file) or from_tf:
|
| 600 |
+
serialization_dir = resolved_archive_file
|
| 601 |
+
else:
|
| 602 |
+
# Extract archive to temp dir
|
| 603 |
+
tempdir = tempfile.mkdtemp()
|
| 604 |
+
logger.info("extracting archive file {} to temp dir {}".format(
|
| 605 |
+
resolved_archive_file, tempdir))
|
| 606 |
+
with tarfile.open(resolved_archive_file, 'r:gz') as archive:
|
| 607 |
+
archive.extractall(tempdir)
|
| 608 |
+
serialization_dir = tempdir
|
| 609 |
+
# Load config
|
| 610 |
+
config_file = os.path.join(serialization_dir, CONFIG_NAME)
|
| 611 |
+
if not os.path.exists(config_file):
|
| 612 |
+
# Backward compatibility with old naming format
|
| 613 |
+
config_file = os.path.join(serialization_dir, BERT_CONFIG_NAME)
|
| 614 |
+
config = BertConfig.from_json_file(config_file)
|
| 615 |
+
logger.info("Model config {}".format(config))
|
| 616 |
+
# Instantiate model.
|
| 617 |
+
model = cls(config, *inputs, **kwargs)
|
| 618 |
+
if state_dict is None and not from_tf:
|
| 619 |
+
weights_path = os.path.join(serialization_dir, WEIGHTS_NAME)
|
| 620 |
+
state_dict = torch.load(weights_path, map_location='cpu')
|
| 621 |
+
if tempdir:
|
| 622 |
+
# Clean up temp dir
|
| 623 |
+
shutil.rmtree(tempdir)
|
| 624 |
+
if from_tf:
|
| 625 |
+
# Directly load from a TensorFlow checkpoint
|
| 626 |
+
weights_path = os.path.join(serialization_dir, TF_WEIGHTS_NAME)
|
| 627 |
+
return load_tf_weights_in_bert(model, weights_path)
|
| 628 |
+
# Load from a PyTorch state_dict
|
| 629 |
+
old_keys = []
|
| 630 |
+
new_keys = []
|
| 631 |
+
for key in state_dict.keys():
|
| 632 |
+
new_key = None
|
| 633 |
+
if 'gamma' in key:
|
| 634 |
+
new_key = key.replace('gamma', 'weight')
|
| 635 |
+
if 'beta' in key:
|
| 636 |
+
new_key = key.replace('beta', 'bias')
|
| 637 |
+
if new_key:
|
| 638 |
+
old_keys.append(key)
|
| 639 |
+
new_keys.append(new_key)
|
| 640 |
+
for old_key, new_key in zip(old_keys, new_keys):
|
| 641 |
+
state_dict[new_key] = state_dict.pop(old_key)
|
| 642 |
+
|
| 643 |
+
missing_keys = []
|
| 644 |
+
unexpected_keys = []
|
| 645 |
+
error_msgs = []
|
| 646 |
+
# copy state_dict so _load_from_state_dict can modify it
|
| 647 |
+
metadata = getattr(state_dict, '_metadata', None)
|
| 648 |
+
state_dict = state_dict.copy()
|
| 649 |
+
if metadata is not None:
|
| 650 |
+
state_dict._metadata = metadata
|
| 651 |
+
|
| 652 |
+
def load(module, prefix=''):
|
| 653 |
+
local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})
|
| 654 |
+
module._load_from_state_dict(
|
| 655 |
+
state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs)
|
| 656 |
+
for name, child in module._modules.items():
|
| 657 |
+
if child is not None:
|
| 658 |
+
load(child, prefix + name + '.')
|
| 659 |
+
start_prefix = ''
|
| 660 |
+
if not hasattr(model, 'bert') and any(s.startswith('bert.') for s in state_dict.keys()):
|
| 661 |
+
start_prefix = 'bert.'
|
| 662 |
+
load(model, prefix=start_prefix)
|
| 663 |
+
if len(missing_keys) > 0:
|
| 664 |
+
logger.info("Weights of {} not initialized from pretrained model: {}".format(
|
| 665 |
+
model.__class__.__name__, missing_keys))
|
| 666 |
+
if len(unexpected_keys) > 0:
|
| 667 |
+
logger.info("Weights from pretrained model not used in {}: {}".format(
|
| 668 |
+
model.__class__.__name__, unexpected_keys))
|
| 669 |
+
if len(error_msgs) > 0:
|
| 670 |
+
raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format(
|
| 671 |
+
model.__class__.__name__, "\n\t".join(error_msgs)))
|
| 672 |
+
return model
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
class BertModel(BertPreTrainedModel):
|
| 676 |
+
"""BERT model ("Bidirectional Embedding Representations from a Transformer").
|
| 677 |
+
|
| 678 |
+
Params:
|
| 679 |
+
config: a BertConfig class instance with the configuration to build a new model
|
| 680 |
+
|
| 681 |
+
Inputs:
|
| 682 |
+
`input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
|
| 683 |
+
with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
|
| 684 |
+
`extract_features.py`, `run_classifier.py` and `run_squad.py`)
|
| 685 |
+
`token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
|
| 686 |
+
types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
|
| 687 |
+
a `sentence B` token (see BERT paper for more details).
|
| 688 |
+
`attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
|
| 689 |
+
selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
|
| 690 |
+
input sequence length in the current batch. It's the mask that we typically use for attention when
|
| 691 |
+
a batch has varying length sentences.
|
| 692 |
+
`output_all_encoded_layers`: boolean which controls the content of the `encoded_layers` output as described below. Default: `True`.
|
| 693 |
+
|
| 694 |
+
Outputs: Tuple of (encoded_layers, pooled_output)
|
| 695 |
+
`encoded_layers`: controled by `output_all_encoded_layers` argument:
|
| 696 |
+
- `output_all_encoded_layers=True`: outputs a list of the full sequences of encoded-hidden-states at the end
|
| 697 |
+
of each attention block (i.e. 12 full sequences for BERT-base, 24 for BERT-large), each
|
| 698 |
+
encoded-hidden-state is a torch.FloatTensor of size [batch_size, sequence_length, hidden_size],
|
| 699 |
+
- `output_all_encoded_layers=False`: outputs only the full sequence of hidden-states corresponding
|
| 700 |
+
to the last attention block of shape [batch_size, sequence_length, hidden_size],
|
| 701 |
+
`pooled_output`: a torch.FloatTensor of size [batch_size, hidden_size] which is the output of a
|
| 702 |
+
classifier pretrained on top of the hidden state associated to the first character of the
|
| 703 |
+
input (`CLS`) to train on the Next-Sentence task (see BERT's paper).
|
| 704 |
+
|
| 705 |
+
Example usage:
|
| 706 |
+
```python
|
| 707 |
+
# Already been converted into WordPiece token ids
|
| 708 |
+
input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
|
| 709 |
+
input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
|
| 710 |
+
token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
|
| 711 |
+
|
| 712 |
+
config = modeling.BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
|
| 713 |
+
num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
|
| 714 |
+
|
| 715 |
+
model = modeling.BertModel(config=config)
|
| 716 |
+
all_encoder_layers, pooled_output = model(input_ids, token_type_ids, input_mask)
|
| 717 |
+
```
|
| 718 |
+
"""
|
| 719 |
+
def __init__(self, config):
|
| 720 |
+
super(BertModel, self).__init__(config)
|
| 721 |
+
self.embeddings = BertEmbeddings(config)
|
| 722 |
+
self.encoder = BertEncoder(config)
|
| 723 |
+
self.pooler = BertPooler(config)
|
| 724 |
+
self.apply(self.init_bert_weights)
|
| 725 |
+
self.hidden_size = config.hidden_size
|
| 726 |
+
|
| 727 |
+
def forward(self, input_ids, token_type_ids=None, attention_mask=None, output_all_encoded_layers=True):
|
| 728 |
+
if attention_mask is None:
|
| 729 |
+
attention_mask = torch.ones_like(input_ids)
|
| 730 |
+
if token_type_ids is None:
|
| 731 |
+
token_type_ids = torch.zeros_like(input_ids)
|
| 732 |
+
|
| 733 |
+
# We create a 3D attention mask from a 2D tensor mask.
|
| 734 |
+
# Sizes are [batch_size, 1, 1, to_seq_length]
|
| 735 |
+
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
|
| 736 |
+
# this attention mask is more simple than the triangular masking of causal attention
|
| 737 |
+
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
|
| 738 |
+
extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
| 739 |
+
|
| 740 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
| 741 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
| 742 |
+
# positions we want to attend and -10000.0 for masked positions.
|
| 743 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
| 744 |
+
# effectively the same as removing these entirely.
|
| 745 |
+
extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility
|
| 746 |
+
extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
|
| 747 |
+
|
| 748 |
+
embedding_output = self.embeddings(input_ids, token_type_ids)
|
| 749 |
+
encoded_layers = self.encoder(embedding_output,
|
| 750 |
+
extended_attention_mask,
|
| 751 |
+
output_all_encoded_layers=output_all_encoded_layers)
|
| 752 |
+
sequence_output = encoded_layers[-1]
|
| 753 |
+
pooled_output = self.pooler(sequence_output)
|
| 754 |
+
if not output_all_encoded_layers:
|
| 755 |
+
encoded_layers = encoded_layers[-1]
|
| 756 |
+
return encoded_layers, pooled_output
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
class BertForPreTraining(BertPreTrainedModel):
|
| 760 |
+
"""BERT model with pre-training heads.
|
| 761 |
+
This module comprises the BERT model followed by the two pre-training heads:
|
| 762 |
+
- the masked language modeling head, and
|
| 763 |
+
- the next sentence classification head.
|
| 764 |
+
|
| 765 |
+
Params:
|
| 766 |
+
config: a BertConfig class instance with the configuration to build a new model.
|
| 767 |
+
|
| 768 |
+
Inputs:
|
| 769 |
+
`input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
|
| 770 |
+
with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
|
| 771 |
+
`extract_features.py`, `run_classifier.py` and `run_squad.py`)
|
| 772 |
+
`token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
|
| 773 |
+
types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
|
| 774 |
+
a `sentence B` token (see BERT paper for more details).
|
| 775 |
+
`attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
|
| 776 |
+
selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
|
| 777 |
+
input sequence length in the current batch. It's the mask that we typically use for attention when
|
| 778 |
+
a batch has varying length sentences.
|
| 779 |
+
`masked_lm_labels`: optional masked language modeling labels: torch.LongTensor of shape [batch_size, sequence_length]
|
| 780 |
+
with indices selected in [-1, 0, ..., vocab_size]. All labels set to -1 are ignored (masked), the loss
|
| 781 |
+
is only computed for the labels set in [0, ..., vocab_size]
|
| 782 |
+
`next_sentence_label`: optional next sentence classification loss: torch.LongTensor of shape [batch_size]
|
| 783 |
+
with indices selected in [0, 1].
|
| 784 |
+
0 => next sentence is the continuation, 1 => next sentence is a random sentence.
|
| 785 |
+
|
| 786 |
+
Outputs:
|
| 787 |
+
if `masked_lm_labels` and `next_sentence_label` are not `None`:
|
| 788 |
+
Outputs the total_loss which is the sum of the masked language modeling loss and the next
|
| 789 |
+
sentence classification loss.
|
| 790 |
+
if `masked_lm_labels` or `next_sentence_label` is `None`:
|
| 791 |
+
Outputs a tuple comprising
|
| 792 |
+
- the masked language modeling logits of shape [batch_size, sequence_length, vocab_size], and
|
| 793 |
+
- the next sentence classification logits of shape [batch_size, 2].
|
| 794 |
+
|
| 795 |
+
Example usage:
|
| 796 |
+
```python
|
| 797 |
+
# Already been converted into WordPiece token ids
|
| 798 |
+
input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
|
| 799 |
+
input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
|
| 800 |
+
token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
|
| 801 |
+
|
| 802 |
+
config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
|
| 803 |
+
num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
|
| 804 |
+
|
| 805 |
+
model = BertForPreTraining(config)
|
| 806 |
+
masked_lm_logits_scores, seq_relationship_logits = model(input_ids, token_type_ids, input_mask)
|
| 807 |
+
```
|
| 808 |
+
"""
|
| 809 |
+
def __init__(self, config):
|
| 810 |
+
super(BertForPreTraining, self).__init__(config)
|
| 811 |
+
self.bert = BertModel(config)
|
| 812 |
+
self.cls = BertPreTrainingHeads(config, self.bert.embeddings.word_embeddings.weight)
|
| 813 |
+
self.apply(self.init_bert_weights)
|
| 814 |
+
|
| 815 |
+
def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None, next_sentence_label=None):
|
| 816 |
+
sequence_output, pooled_output = self.bert(input_ids, token_type_ids, attention_mask,
|
| 817 |
+
output_all_encoded_layers=False)
|
| 818 |
+
prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
|
| 819 |
+
|
| 820 |
+
if masked_lm_labels is not None and next_sentence_label is not None:
|
| 821 |
+
loss_fct = CrossEntropyLoss(ignore_index=-1)
|
| 822 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))
|
| 823 |
+
next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
|
| 824 |
+
total_loss = masked_lm_loss + next_sentence_loss
|
| 825 |
+
return total_loss
|
| 826 |
+
else:
|
| 827 |
+
return prediction_scores, seq_relationship_score
|
| 828 |
+
|
| 829 |
+
|
| 830 |
+
class BertForMaskedLM(BertPreTrainedModel):
|
| 831 |
+
"""BERT model with the masked language modeling head.
|
| 832 |
+
This module comprises the BERT model followed by the masked language modeling head.
|
| 833 |
+
|
| 834 |
+
Params:
|
| 835 |
+
config: a BertConfig class instance with the configuration to build a new model.
|
| 836 |
+
|
| 837 |
+
Inputs:
|
| 838 |
+
`input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
|
| 839 |
+
with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
|
| 840 |
+
`extract_features.py`, `run_classifier.py` and `run_squad.py`)
|
| 841 |
+
`token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
|
| 842 |
+
types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
|
| 843 |
+
a `sentence B` token (see BERT paper for more details).
|
| 844 |
+
`attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
|
| 845 |
+
selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
|
| 846 |
+
input sequence length in the current batch. It's the mask that we typically use for attention when
|
| 847 |
+
a batch has varying length sentences.
|
| 848 |
+
`masked_lm_labels`: masked language modeling labels: torch.LongTensor of shape [batch_size, sequence_length]
|
| 849 |
+
with indices selected in [-1, 0, ..., vocab_size]. All labels set to -1 are ignored (masked), the loss
|
| 850 |
+
is only computed for the labels set in [0, ..., vocab_size]
|
| 851 |
+
|
| 852 |
+
Outputs:
|
| 853 |
+
if `masked_lm_labels` is not `None`:
|
| 854 |
+
Outputs the masked language modeling loss.
|
| 855 |
+
if `masked_lm_labels` is `None`:
|
| 856 |
+
Outputs the masked language modeling logits of shape [batch_size, sequence_length, vocab_size].
|
| 857 |
+
|
| 858 |
+
Example usage:
|
| 859 |
+
```python
|
| 860 |
+
# Already been converted into WordPiece token ids
|
| 861 |
+
input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
|
| 862 |
+
input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
|
| 863 |
+
token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
|
| 864 |
+
|
| 865 |
+
config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
|
| 866 |
+
num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
|
| 867 |
+
|
| 868 |
+
model = BertForMaskedLM(config)
|
| 869 |
+
masked_lm_logits_scores = model(input_ids, token_type_ids, input_mask)
|
| 870 |
+
```
|
| 871 |
+
"""
|
| 872 |
+
def __init__(self, config):
|
| 873 |
+
super(BertForMaskedLM, self).__init__(config)
|
| 874 |
+
self.bert = BertModel(config)
|
| 875 |
+
self.cls = BertOnlyMLMHead(config, self.bert.embeddings.word_embeddings.weight)
|
| 876 |
+
self.apply(self.init_bert_weights)
|
| 877 |
+
|
| 878 |
+
def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None):
|
| 879 |
+
sequence_output, _ = self.bert(input_ids, token_type_ids, attention_mask,
|
| 880 |
+
output_all_encoded_layers=False)
|
| 881 |
+
prediction_scores = self.cls(sequence_output)
|
| 882 |
+
|
| 883 |
+
if masked_lm_labels is not None:
|
| 884 |
+
loss_fct = CrossEntropyLoss(ignore_index=-1)
|
| 885 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))
|
| 886 |
+
return masked_lm_loss
|
| 887 |
+
else:
|
| 888 |
+
return prediction_scores
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
class BertForNextSentencePrediction(BertPreTrainedModel):
|
| 892 |
+
"""BERT model with next sentence prediction head.
|
| 893 |
+
This module comprises the BERT model followed by the next sentence classification head.
|
| 894 |
+
|
| 895 |
+
Params:
|
| 896 |
+
config: a BertConfig class instance with the configuration to build a new model.
|
| 897 |
+
|
| 898 |
+
Inputs:
|
| 899 |
+
`input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
|
| 900 |
+
with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
|
| 901 |
+
`extract_features.py`, `run_classifier.py` and `run_squad.py`)
|
| 902 |
+
`token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
|
| 903 |
+
types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
|
| 904 |
+
a `sentence B` token (see BERT paper for more details).
|
| 905 |
+
`attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
|
| 906 |
+
selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
|
| 907 |
+
input sequence length in the current batch. It's the mask that we typically use for attention when
|
| 908 |
+
a batch has varying length sentences.
|
| 909 |
+
`next_sentence_label`: next sentence classification loss: torch.LongTensor of shape [batch_size]
|
| 910 |
+
with indices selected in [0, 1].
|
| 911 |
+
0 => next sentence is the continuation, 1 => next sentence is a random sentence.
|
| 912 |
+
|
| 913 |
+
Outputs:
|
| 914 |
+
if `next_sentence_label` is not `None`:
|
| 915 |
+
Outputs the total_loss which is the sum of the masked language modeling loss and the next
|
| 916 |
+
sentence classification loss.
|
| 917 |
+
if `next_sentence_label` is `None`:
|
| 918 |
+
Outputs the next sentence classification logits of shape [batch_size, 2].
|
| 919 |
+
|
| 920 |
+
Example usage:
|
| 921 |
+
```python
|
| 922 |
+
# Already been converted into WordPiece token ids
|
| 923 |
+
input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
|
| 924 |
+
input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
|
| 925 |
+
token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
|
| 926 |
+
|
| 927 |
+
config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
|
| 928 |
+
num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
|
| 929 |
+
|
| 930 |
+
model = BertForNextSentencePrediction(config)
|
| 931 |
+
seq_relationship_logits = model(input_ids, token_type_ids, input_mask)
|
| 932 |
+
```
|
| 933 |
+
"""
|
| 934 |
+
def __init__(self, config):
|
| 935 |
+
super(BertForNextSentencePrediction, self).__init__(config)
|
| 936 |
+
self.bert = BertModel(config)
|
| 937 |
+
self.cls = BertOnlyNSPHead(config)
|
| 938 |
+
self.apply(self.init_bert_weights)
|
| 939 |
+
|
| 940 |
+
def forward(self, input_ids, token_type_ids=None, attention_mask=None, next_sentence_label=None):
|
| 941 |
+
_, pooled_output = self.bert(input_ids, token_type_ids, attention_mask,
|
| 942 |
+
output_all_encoded_layers=False)
|
| 943 |
+
seq_relationship_score = self.cls( pooled_output)
|
| 944 |
+
|
| 945 |
+
if next_sentence_label is not None:
|
| 946 |
+
loss_fct = CrossEntropyLoss(ignore_index=-1)
|
| 947 |
+
next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
|
| 948 |
+
return next_sentence_loss
|
| 949 |
+
else:
|
| 950 |
+
return seq_relationship_score
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
class BertForSequenceClassification(BertPreTrainedModel):
|
| 954 |
+
"""BERT model for classification.
|
| 955 |
+
This module is composed of the BERT model with a linear layer on top of
|
| 956 |
+
the pooled output.
|
| 957 |
+
|
| 958 |
+
Params:
|
| 959 |
+
`config`: a BertConfig class instance with the configuration to build a new model.
|
| 960 |
+
`num_labels`: the number of classes for the classifier. Default = 2.
|
| 961 |
+
|
| 962 |
+
Inputs:
|
| 963 |
+
`input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
|
| 964 |
+
with the word token indices in the vocabulary. Items in the batch should begin with the special "CLS" token. (see the tokens preprocessing logic in the scripts
|
| 965 |
+
`extract_features.py`, `run_classifier.py` and `run_squad.py`)
|
| 966 |
+
`token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
|
| 967 |
+
types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
|
| 968 |
+
a `sentence B` token (see BERT paper for more details).
|
| 969 |
+
`attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
|
| 970 |
+
selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
|
| 971 |
+
input sequence length in the current batch. It's the mask that we typically use for attention when
|
| 972 |
+
a batch has varying length sentences.
|
| 973 |
+
`labels`: labels for the classification output: torch.LongTensor of shape [batch_size]
|
| 974 |
+
with indices selected in [0, ..., num_labels].
|
| 975 |
+
|
| 976 |
+
Outputs:
|
| 977 |
+
if `labels` is not `None`:
|
| 978 |
+
Outputs the CrossEntropy classification loss of the output with the labels.
|
| 979 |
+
if `labels` is `None`:
|
| 980 |
+
Outputs the classification logits of shape [batch_size, num_labels].
|
| 981 |
+
|
| 982 |
+
Example usage:
|
| 983 |
+
```python
|
| 984 |
+
# Already been converted into WordPiece token ids
|
| 985 |
+
input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
|
| 986 |
+
input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
|
| 987 |
+
token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
|
| 988 |
+
|
| 989 |
+
config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
|
| 990 |
+
num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
|
| 991 |
+
|
| 992 |
+
num_labels = 2
|
| 993 |
+
|
| 994 |
+
model = BertForSequenceClassification(config, num_labels)
|
| 995 |
+
logits = model(input_ids, token_type_ids, input_mask)
|
| 996 |
+
```
|
| 997 |
+
"""
|
| 998 |
+
def __init__(self, config, num_labels=2):
|
| 999 |
+
super(BertForSequenceClassification, self).__init__(config)
|
| 1000 |
+
self.num_labels = num_labels
|
| 1001 |
+
self.bert = BertModel(config)
|
| 1002 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 1003 |
+
self.classifier = nn.Linear(config.hidden_size, num_labels)
|
| 1004 |
+
self.apply(self.init_bert_weights)
|
| 1005 |
+
|
| 1006 |
+
def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None):
|
| 1007 |
+
_, pooled_output = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)
|
| 1008 |
+
pooled_output = self.dropout(pooled_output)
|
| 1009 |
+
logits = self.classifier(pooled_output)
|
| 1010 |
+
|
| 1011 |
+
if labels is not None:
|
| 1012 |
+
loss_fct = CrossEntropyLoss()
|
| 1013 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1014 |
+
return loss
|
| 1015 |
+
else:
|
| 1016 |
+
return logits
|
| 1017 |
+
|
| 1018 |
+
|
| 1019 |
+
class BertForMultipleChoice(BertPreTrainedModel):
|
| 1020 |
+
"""BERT model for multiple choice tasks.
|
| 1021 |
+
This module is composed of the BERT model with a linear layer on top of
|
| 1022 |
+
the pooled output.
|
| 1023 |
+
|
| 1024 |
+
Params:
|
| 1025 |
+
`config`: a BertConfig class instance with the configuration to build a new model.
|
| 1026 |
+
`num_choices`: the number of classes for the classifier. Default = 2.
|
| 1027 |
+
|
| 1028 |
+
Inputs:
|
| 1029 |
+
`input_ids`: a torch.LongTensor of shape [batch_size, num_choices, sequence_length]
|
| 1030 |
+
with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
|
| 1031 |
+
`extract_features.py`, `run_classifier.py` and `run_squad.py`)
|
| 1032 |
+
`token_type_ids`: an optional torch.LongTensor of shape [batch_size, num_choices, sequence_length]
|
| 1033 |
+
with the token types indices selected in [0, 1]. Type 0 corresponds to a `sentence A`
|
| 1034 |
+
and type 1 corresponds to a `sentence B` token (see BERT paper for more details).
|
| 1035 |
+
`attention_mask`: an optional torch.LongTensor of shape [batch_size, num_choices, sequence_length] with indices
|
| 1036 |
+
selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
|
| 1037 |
+
input sequence length in the current batch. It's the mask that we typically use for attention when
|
| 1038 |
+
a batch has varying length sentences.
|
| 1039 |
+
`labels`: labels for the classification output: torch.LongTensor of shape [batch_size]
|
| 1040 |
+
with indices selected in [0, ..., num_choices].
|
| 1041 |
+
|
| 1042 |
+
Outputs:
|
| 1043 |
+
if `labels` is not `None`:
|
| 1044 |
+
Outputs the CrossEntropy classification loss of the output with the labels.
|
| 1045 |
+
if `labels` is `None`:
|
| 1046 |
+
Outputs the classification logits of shape [batch_size, num_labels].
|
| 1047 |
+
|
| 1048 |
+
Example usage:
|
| 1049 |
+
```python
|
| 1050 |
+
# Already been converted into WordPiece token ids
|
| 1051 |
+
input_ids = torch.LongTensor([[[31, 51, 99], [15, 5, 0]], [[12, 16, 42], [14, 28, 57]]])
|
| 1052 |
+
input_mask = torch.LongTensor([[[1, 1, 1], [1, 1, 0]],[[1,1,0], [1, 0, 0]]])
|
| 1053 |
+
token_type_ids = torch.LongTensor([[[0, 0, 1], [0, 1, 0]],[[0, 1, 1], [0, 0, 1]]])
|
| 1054 |
+
config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
|
| 1055 |
+
num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
|
| 1056 |
+
|
| 1057 |
+
num_choices = 2
|
| 1058 |
+
|
| 1059 |
+
model = BertForMultipleChoice(config, num_choices)
|
| 1060 |
+
logits = model(input_ids, token_type_ids, input_mask)
|
| 1061 |
+
```
|
| 1062 |
+
"""
|
| 1063 |
+
def __init__(self, config, num_choices=2):
|
| 1064 |
+
super(BertForMultipleChoice, self).__init__(config)
|
| 1065 |
+
self.num_choices = num_choices
|
| 1066 |
+
self.bert = BertModel(config)
|
| 1067 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 1068 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
| 1069 |
+
self.apply(self.init_bert_weights)
|
| 1070 |
+
|
| 1071 |
+
def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None):
|
| 1072 |
+
flat_input_ids = input_ids.view(-1, input_ids.size(-1))
|
| 1073 |
+
flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
|
| 1074 |
+
flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
| 1075 |
+
_, pooled_output = self.bert(flat_input_ids, flat_token_type_ids, flat_attention_mask, output_all_encoded_layers=False)
|
| 1076 |
+
pooled_output = self.dropout(pooled_output)
|
| 1077 |
+
logits = self.classifier(pooled_output)
|
| 1078 |
+
reshaped_logits = logits.view(-1, self.num_choices)
|
| 1079 |
+
|
| 1080 |
+
if labels is not None:
|
| 1081 |
+
loss_fct = CrossEntropyLoss()
|
| 1082 |
+
loss = loss_fct(reshaped_logits, labels)
|
| 1083 |
+
return loss
|
| 1084 |
+
else:
|
| 1085 |
+
return reshaped_logits
|
| 1086 |
+
|
| 1087 |
+
|
| 1088 |
+
class BertForTokenClassification(BertPreTrainedModel):
|
| 1089 |
+
"""BERT model for token-level classification.
|
| 1090 |
+
This module is composed of the BERT model with a linear layer on top of
|
| 1091 |
+
the full hidden state of the last layer.
|
| 1092 |
+
|
| 1093 |
+
Params:
|
| 1094 |
+
`config`: a BertConfig class instance with the configuration to build a new model.
|
| 1095 |
+
`num_labels`: the number of classes for the classifier. Default = 2.
|
| 1096 |
+
|
| 1097 |
+
Inputs:
|
| 1098 |
+
`input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
|
| 1099 |
+
with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
|
| 1100 |
+
`extract_features.py`, `run_classifier.py` and `run_squad.py`)
|
| 1101 |
+
`token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
|
| 1102 |
+
types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
|
| 1103 |
+
a `sentence B` token (see BERT paper for more details).
|
| 1104 |
+
`attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
|
| 1105 |
+
selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
|
| 1106 |
+
input sequence length in the current batch. It's the mask that we typically use for attention when
|
| 1107 |
+
a batch has varying length sentences.
|
| 1108 |
+
`labels`: labels for the classification output: torch.LongTensor of shape [batch_size, sequence_length]
|
| 1109 |
+
with indices selected in [0, ..., num_labels].
|
| 1110 |
+
|
| 1111 |
+
Outputs:
|
| 1112 |
+
if `labels` is not `None`:
|
| 1113 |
+
Outputs the CrossEntropy classification loss of the output with the labels.
|
| 1114 |
+
if `labels` is `None`:
|
| 1115 |
+
Outputs the classification logits of shape [batch_size, sequence_length, num_labels].
|
| 1116 |
+
|
| 1117 |
+
Example usage:
|
| 1118 |
+
```python
|
| 1119 |
+
# Already been converted into WordPiece token ids
|
| 1120 |
+
input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
|
| 1121 |
+
input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
|
| 1122 |
+
token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
|
| 1123 |
+
|
| 1124 |
+
config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
|
| 1125 |
+
num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
|
| 1126 |
+
|
| 1127 |
+
num_labels = 2
|
| 1128 |
+
|
| 1129 |
+
model = BertForTokenClassification(config, num_labels)
|
| 1130 |
+
logits = model(input_ids, token_type_ids, input_mask)
|
| 1131 |
+
```
|
| 1132 |
+
"""
|
| 1133 |
+
def __init__(self, config, num_labels=2):
|
| 1134 |
+
super(BertForTokenClassification, self).__init__(config)
|
| 1135 |
+
self.num_labels = num_labels
|
| 1136 |
+
self.bert = BertModel(config)
|
| 1137 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 1138 |
+
self.classifier = nn.Linear(config.hidden_size, num_labels)
|
| 1139 |
+
self.apply(self.init_bert_weights)
|
| 1140 |
+
|
| 1141 |
+
def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None):
|
| 1142 |
+
sequence_output, _ = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)
|
| 1143 |
+
sequence_output = self.dropout(sequence_output)
|
| 1144 |
+
logits = self.classifier(sequence_output)
|
| 1145 |
+
|
| 1146 |
+
if labels is not None:
|
| 1147 |
+
loss_fct = CrossEntropyLoss()
|
| 1148 |
+
# Only keep active parts of the loss
|
| 1149 |
+
if attention_mask is not None:
|
| 1150 |
+
active_loss = attention_mask.view(-1) == 1
|
| 1151 |
+
active_logits = logits.view(-1, self.num_labels)[active_loss]
|
| 1152 |
+
active_labels = labels.view(-1)[active_loss]
|
| 1153 |
+
loss = loss_fct(active_logits, active_labels)
|
| 1154 |
+
else:
|
| 1155 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1156 |
+
return loss
|
| 1157 |
+
else:
|
| 1158 |
+
return logits
|
| 1159 |
+
|
| 1160 |
+
|
| 1161 |
+
class BertForQuestionAnswering(BertPreTrainedModel):
|
| 1162 |
+
"""BERT model for Question Answering (span extraction).
|
| 1163 |
+
This module is composed of the BERT model with a linear layer on top of
|
| 1164 |
+
the sequence output that computes start_logits and end_logits
|
| 1165 |
+
|
| 1166 |
+
Params:
|
| 1167 |
+
`config`: a BertConfig class instance with the configuration to build a new model.
|
| 1168 |
+
|
| 1169 |
+
Inputs:
|
| 1170 |
+
`input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
|
| 1171 |
+
with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
|
| 1172 |
+
`extract_features.py`, `run_classifier.py` and `run_squad.py`)
|
| 1173 |
+
`token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
|
| 1174 |
+
types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
|
| 1175 |
+
a `sentence B` token (see BERT paper for more details).
|
| 1176 |
+
`attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
|
| 1177 |
+
selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
|
| 1178 |
+
input sequence length in the current batch. It's the mask that we typically use for attention when
|
| 1179 |
+
a batch has varying length sentences.
|
| 1180 |
+
`start_positions`: position of the first token for the labeled span: torch.LongTensor of shape [batch_size].
|
| 1181 |
+
Positions are clamped to the length of the sequence and position outside of the sequence are not taken
|
| 1182 |
+
into account for computing the loss.
|
| 1183 |
+
`end_positions`: position of the last token for the labeled span: torch.LongTensor of shape [batch_size].
|
| 1184 |
+
Positions are clamped to the length of the sequence and position outside of the sequence are not taken
|
| 1185 |
+
into account for computing the loss.
|
| 1186 |
+
|
| 1187 |
+
Outputs:
|
| 1188 |
+
if `start_positions` and `end_positions` are not `None`:
|
| 1189 |
+
Outputs the total_loss which is the sum of the CrossEntropy loss for the start and end token positions.
|
| 1190 |
+
if `start_positions` or `end_positions` is `None`:
|
| 1191 |
+
Outputs a tuple of start_logits, end_logits which are the logits respectively for the start and end
|
| 1192 |
+
position tokens of shape [batch_size, sequence_length].
|
| 1193 |
+
|
| 1194 |
+
Example usage:
|
| 1195 |
+
```python
|
| 1196 |
+
# Already been converted into WordPiece token ids
|
| 1197 |
+
input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
|
| 1198 |
+
input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
|
| 1199 |
+
token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
|
| 1200 |
+
|
| 1201 |
+
config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
|
| 1202 |
+
num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
|
| 1203 |
+
|
| 1204 |
+
model = BertForQuestionAnswering(config)
|
| 1205 |
+
start_logits, end_logits = model(input_ids, token_type_ids, input_mask)
|
| 1206 |
+
```
|
| 1207 |
+
"""
|
| 1208 |
+
def __init__(self, config):
|
| 1209 |
+
super(BertForQuestionAnswering, self).__init__(config)
|
| 1210 |
+
self.bert = BertModel(config)
|
| 1211 |
+
# TODO check with Google if it's normal there is no dropout on the token classifier of SQuAD in the TF version
|
| 1212 |
+
# self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 1213 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
| 1214 |
+
self.apply(self.init_bert_weights)
|
| 1215 |
+
|
| 1216 |
+
def forward(self, input_ids, token_type_ids=None, attention_mask=None, start_positions=None, end_positions=None):
|
| 1217 |
+
sequence_output, _ = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)
|
| 1218 |
+
logits = self.qa_outputs(sequence_output)
|
| 1219 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1220 |
+
start_logits = start_logits.squeeze(-1)
|
| 1221 |
+
end_logits = end_logits.squeeze(-1)
|
| 1222 |
+
|
| 1223 |
+
if start_positions is not None and end_positions is not None:
|
| 1224 |
+
# If we are on multi-GPU, split add a dimension
|
| 1225 |
+
if len(start_positions.size()) > 1:
|
| 1226 |
+
start_positions = start_positions.squeeze(-1)
|
| 1227 |
+
if len(end_positions.size()) > 1:
|
| 1228 |
+
end_positions = end_positions.squeeze(-1)
|
| 1229 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1230 |
+
ignored_index = start_logits.size(1)
|
| 1231 |
+
start_positions.clamp_(0, ignored_index)
|
| 1232 |
+
end_positions.clamp_(0, ignored_index)
|
| 1233 |
+
|
| 1234 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1235 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1236 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1237 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1238 |
+
return total_loss
|
| 1239 |
+
else:
|
| 1240 |
+
return start_logits, end_logits
|
SimTranslation/code/unibert_waitk_0901_stack/bert/tokenization.py
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes."""
|
| 16 |
+
|
| 17 |
+
from __future__ import absolute_import, division, print_function, unicode_literals
|
| 18 |
+
|
| 19 |
+
import collections
|
| 20 |
+
import logging
|
| 21 |
+
import os
|
| 22 |
+
import unicodedata
|
| 23 |
+
from io import open
|
| 24 |
+
|
| 25 |
+
from .file_utils import cached_path
|
| 26 |
+
|
| 27 |
+
logger = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
PRETRAINED_VOCAB_ARCHIVE_MAP = {
|
| 30 |
+
'bert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt",
|
| 31 |
+
'bert-large-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt",
|
| 32 |
+
'bert-base-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt",
|
| 33 |
+
'bert-large-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt",
|
| 34 |
+
'bert-base-multilingual-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txt",
|
| 35 |
+
'bert-base-multilingual-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txt",
|
| 36 |
+
'bert-base-chinese': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt",
|
| 37 |
+
'bert-base-german-cased': "https://int-deepset-models-bert.s3.eu-central-1.amazonaws.com/pytorch/bert-base-german-cased-vocab.txt",
|
| 38 |
+
}
|
| 39 |
+
PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP = {
|
| 40 |
+
'bert-base-uncased': 512,
|
| 41 |
+
'bert-large-uncased': 512,
|
| 42 |
+
'bert-base-cased': 512,
|
| 43 |
+
'bert-large-cased': 512,
|
| 44 |
+
'bert-base-multilingual-uncased': 512,
|
| 45 |
+
'bert-base-multilingual-cased': 512,
|
| 46 |
+
'bert-base-chinese': 512,
|
| 47 |
+
'bert-base-german-cased': 512,
|
| 48 |
+
}
|
| 49 |
+
VOCAB_NAME = 'vocab.txt'
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def load_vocab(vocab_file):
|
| 53 |
+
"""Loads a vocabulary file into a dictionary."""
|
| 54 |
+
vocab = collections.OrderedDict()
|
| 55 |
+
index = 0
|
| 56 |
+
with open(vocab_file, "r", encoding="utf-8") as reader:
|
| 57 |
+
while True:
|
| 58 |
+
token = reader.readline()
|
| 59 |
+
if not token:
|
| 60 |
+
break
|
| 61 |
+
token = token.strip()
|
| 62 |
+
vocab[token] = index
|
| 63 |
+
index += 1
|
| 64 |
+
return vocab
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def whitespace_tokenize(text):
|
| 68 |
+
"""Runs basic whitespace cleaning and splitting on a piece of text."""
|
| 69 |
+
text = text.strip()
|
| 70 |
+
if not text:
|
| 71 |
+
return []
|
| 72 |
+
tokens = text.split()
|
| 73 |
+
return tokens
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class BertTokenizer(object):
|
| 77 |
+
"""Runs end-to-end tokenization: punctuation splitting + wordpiece"""
|
| 78 |
+
|
| 79 |
+
def __init__(self, vocab_file, do_lower_case=True, max_len=None, do_basic_tokenize=True,
|
| 80 |
+
never_split=("[UNK]", "[SEP]", "[PAD]", "[CLS]", "[MASK]")):
|
| 81 |
+
"""Constructs a BertTokenizer.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
vocab_file: Path to a one-wordpiece-per-line vocabulary file
|
| 85 |
+
do_lower_case: Whether to lower case the input
|
| 86 |
+
Only has an effect when do_wordpiece_only=False
|
| 87 |
+
do_basic_tokenize: Whether to do basic tokenization before wordpiece.
|
| 88 |
+
max_len: An artificial maximum length to truncate tokenized sequences to;
|
| 89 |
+
Effective maximum length is always the minimum of this
|
| 90 |
+
value (if specified) and the underlying BERT model's
|
| 91 |
+
sequence length.
|
| 92 |
+
never_split: List of tokens which will never be split during tokenization.
|
| 93 |
+
Only has an effect when do_wordpiece_only=False
|
| 94 |
+
"""
|
| 95 |
+
if not os.path.isfile(vocab_file):
|
| 96 |
+
raise ValueError(
|
| 97 |
+
"Can't find a vocabulary file at path '{}'. To load the vocabulary from a Google pretrained "
|
| 98 |
+
"model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`".format(vocab_file))
|
| 99 |
+
self.vocab = load_vocab(vocab_file)
|
| 100 |
+
self.ids_to_tokens = collections.OrderedDict(
|
| 101 |
+
[(ids, tok) for tok, ids in self.vocab.items()])
|
| 102 |
+
self.do_basic_tokenize = do_basic_tokenize
|
| 103 |
+
if do_basic_tokenize:
|
| 104 |
+
self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case,
|
| 105 |
+
never_split=never_split)
|
| 106 |
+
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab)
|
| 107 |
+
self.max_len = max_len if max_len is not None else int(1e12)
|
| 108 |
+
self.unk_word = "[UNK]"
|
| 109 |
+
self.unk_index = self.vocab[self.unk_word]
|
| 110 |
+
self.pad_word = "[PAD]"
|
| 111 |
+
self.pad_index = self.vocab[self.pad_word]
|
| 112 |
+
self.cls_word = "[CLS]"
|
| 113 |
+
self.cls_index = self.vocab[self.cls_word]
|
| 114 |
+
self.sep_word = "[SEP]"
|
| 115 |
+
self.sep_index = self.vocab[self.sep_word]
|
| 116 |
+
|
| 117 |
+
def tokenize(self, text):
|
| 118 |
+
split_tokens = []
|
| 119 |
+
if self.do_basic_tokenize:
|
| 120 |
+
for token in self.basic_tokenizer.tokenize(text):
|
| 121 |
+
for sub_token in self.wordpiece_tokenizer.tokenize(token):
|
| 122 |
+
split_tokens.append(sub_token)
|
| 123 |
+
else:
|
| 124 |
+
split_tokens = self.wordpiece_tokenizer.tokenize(text)
|
| 125 |
+
return split_tokens
|
| 126 |
+
|
| 127 |
+
def __len__(self):
|
| 128 |
+
"""Returns the number of symbols in the dictionary"""
|
| 129 |
+
return len(self.vocab)
|
| 130 |
+
|
| 131 |
+
def pad(self):
|
| 132 |
+
return self.pad_index
|
| 133 |
+
|
| 134 |
+
def cls(self):
|
| 135 |
+
return self.cls_index
|
| 136 |
+
|
| 137 |
+
def sep(self):
|
| 138 |
+
return self.sep_index
|
| 139 |
+
|
| 140 |
+
def convert_tokens_to_ids(self, tokens):
|
| 141 |
+
"""Converts a sequence of tokens into ids using the vocab."""
|
| 142 |
+
ids = []
|
| 143 |
+
for token in tokens:
|
| 144 |
+
ids.append(self.vocab[token])
|
| 145 |
+
if len(ids) > self.max_len:
|
| 146 |
+
logger.warning(
|
| 147 |
+
"Token indices sequence length is longer than the specified maximum "
|
| 148 |
+
" sequence length for this BERT model ({} > {}). Running this"
|
| 149 |
+
" sequence through BERT will result in indexing errors".format(len(ids), self.max_len)
|
| 150 |
+
)
|
| 151 |
+
return ids
|
| 152 |
+
|
| 153 |
+
def convert_ids_to_tokens(self, ids):
|
| 154 |
+
"""Converts a sequence of ids in wordpiece tokens using the vocab."""
|
| 155 |
+
tokens = []
|
| 156 |
+
for i in ids:
|
| 157 |
+
tokens.append(self.ids_to_tokens[i])
|
| 158 |
+
return tokens
|
| 159 |
+
|
| 160 |
+
def save_vocabulary(self, vocab_path):
|
| 161 |
+
"""Save the tokenizer vocabulary to a directory or file."""
|
| 162 |
+
index = 0
|
| 163 |
+
if os.path.isdir(vocab_path):
|
| 164 |
+
vocab_file = os.path.join(vocab_path, VOCAB_NAME)
|
| 165 |
+
with open(vocab_file, "w", encoding="utf-8") as writer:
|
| 166 |
+
for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
|
| 167 |
+
if index != token_index:
|
| 168 |
+
logger.warning("Saving vocabulary to {}: vocabulary indices are not consecutive."
|
| 169 |
+
" Please check that the vocabulary is not corrupted!".format(vocab_file))
|
| 170 |
+
index = token_index
|
| 171 |
+
writer.write(token + u'\n')
|
| 172 |
+
index += 1
|
| 173 |
+
return vocab_file
|
| 174 |
+
|
| 175 |
+
@classmethod
|
| 176 |
+
def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs):
|
| 177 |
+
"""
|
| 178 |
+
Instantiate a PreTrainedBertModel from a pre-trained model file.
|
| 179 |
+
Download and cache the pre-trained model file if needed.
|
| 180 |
+
"""
|
| 181 |
+
if pretrained_model_name_or_path in PRETRAINED_VOCAB_ARCHIVE_MAP:
|
| 182 |
+
vocab_file = PRETRAINED_VOCAB_ARCHIVE_MAP[pretrained_model_name_or_path]
|
| 183 |
+
if '-cased' in pretrained_model_name_or_path and kwargs.get('do_lower_case', True):
|
| 184 |
+
logger.warning("The pre-trained model you are loading is a cased model but you have not set "
|
| 185 |
+
"`do_lower_case` to False. We are setting `do_lower_case=False` for you but "
|
| 186 |
+
"you may want to check this behavior.")
|
| 187 |
+
kwargs['do_lower_case'] = False
|
| 188 |
+
elif '-cased' not in pretrained_model_name_or_path and not kwargs.get('do_lower_case', True):
|
| 189 |
+
logger.warning("The pre-trained model you are loading is an uncased model but you have set "
|
| 190 |
+
"`do_lower_case` to False. We are setting `do_lower_case=True` for you "
|
| 191 |
+
"but you may want to check this behavior.")
|
| 192 |
+
kwargs['do_lower_case'] = True
|
| 193 |
+
else:
|
| 194 |
+
vocab_file = pretrained_model_name_or_path
|
| 195 |
+
if os.path.isdir(vocab_file):
|
| 196 |
+
vocab_file = os.path.join(vocab_file, VOCAB_NAME)
|
| 197 |
+
# redirect to the cache, if necessary
|
| 198 |
+
try:
|
| 199 |
+
resolved_vocab_file = cached_path(vocab_file, cache_dir=cache_dir)
|
| 200 |
+
except EnvironmentError:
|
| 201 |
+
logger.error(
|
| 202 |
+
"Model name '{}' was not found in model name list ({}). "
|
| 203 |
+
"We assumed '{}' was a path or url but couldn't find any file "
|
| 204 |
+
"associated to this path or url.".format(
|
| 205 |
+
pretrained_model_name_or_path,
|
| 206 |
+
', '.join(PRETRAINED_VOCAB_ARCHIVE_MAP.keys()),
|
| 207 |
+
vocab_file))
|
| 208 |
+
return None
|
| 209 |
+
if resolved_vocab_file == vocab_file:
|
| 210 |
+
logger.info("loading vocabulary file {}".format(vocab_file))
|
| 211 |
+
else:
|
| 212 |
+
logger.info("loading vocabulary file {} from cache at {}".format(
|
| 213 |
+
vocab_file, resolved_vocab_file))
|
| 214 |
+
if pretrained_model_name_or_path in PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP:
|
| 215 |
+
# if we're using a pretrained model, ensure the tokenizer wont index sequences longer
|
| 216 |
+
# than the number of positional embeddings
|
| 217 |
+
max_len = PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP[pretrained_model_name_or_path]
|
| 218 |
+
kwargs['max_len'] = min(kwargs.get('max_len', int(1e12)), max_len)
|
| 219 |
+
# Instantiate tokenizer.
|
| 220 |
+
tokenizer = cls(resolved_vocab_file, *inputs, **kwargs)
|
| 221 |
+
return tokenizer
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
class BasicTokenizer(object):
|
| 225 |
+
"""Runs basic tokenization (punctuation splitting, lower casing, etc.)."""
|
| 226 |
+
|
| 227 |
+
def __init__(self,
|
| 228 |
+
do_lower_case=True,
|
| 229 |
+
never_split=("[UNK]", "[SEP]", "[PAD]", "[CLS]", "[MASK]")):
|
| 230 |
+
"""Constructs a BasicTokenizer.
|
| 231 |
+
|
| 232 |
+
Args:
|
| 233 |
+
do_lower_case: Whether to lower case the input.
|
| 234 |
+
"""
|
| 235 |
+
self.do_lower_case = do_lower_case
|
| 236 |
+
self.never_split = never_split
|
| 237 |
+
|
| 238 |
+
def tokenize(self, text):
|
| 239 |
+
"""Tokenizes a piece of text."""
|
| 240 |
+
text = self._clean_text(text)
|
| 241 |
+
# This was added on November 1st, 2018 for the multilingual and Chinese
|
| 242 |
+
# models. This is also applied to the English models now, but it doesn't
|
| 243 |
+
# matter since the English models were not trained on any Chinese data
|
| 244 |
+
# and generally don't have any Chinese data in them (there are Chinese
|
| 245 |
+
# characters in the vocabulary because Wikipedia does have some Chinese
|
| 246 |
+
# words in the English Wikipedia.).
|
| 247 |
+
text = self._tokenize_chinese_chars(text)
|
| 248 |
+
orig_tokens = whitespace_tokenize(text)
|
| 249 |
+
split_tokens = []
|
| 250 |
+
for token in orig_tokens:
|
| 251 |
+
if self.do_lower_case and token not in self.never_split:
|
| 252 |
+
token = token.lower()
|
| 253 |
+
token = self._run_strip_accents(token)
|
| 254 |
+
split_tokens.extend(self._run_split_on_punc(token))
|
| 255 |
+
|
| 256 |
+
output_tokens = whitespace_tokenize(" ".join(split_tokens))
|
| 257 |
+
return output_tokens
|
| 258 |
+
|
| 259 |
+
def _run_strip_accents(self, text):
|
| 260 |
+
"""Strips accents from a piece of text."""
|
| 261 |
+
text = unicodedata.normalize("NFD", text)
|
| 262 |
+
output = []
|
| 263 |
+
for char in text:
|
| 264 |
+
cat = unicodedata.category(char)
|
| 265 |
+
if cat == "Mn":
|
| 266 |
+
continue
|
| 267 |
+
output.append(char)
|
| 268 |
+
return "".join(output)
|
| 269 |
+
|
| 270 |
+
def _run_split_on_punc(self, text):
|
| 271 |
+
"""Splits punctuation on a piece of text."""
|
| 272 |
+
if text in self.never_split:
|
| 273 |
+
return [text]
|
| 274 |
+
chars = list(text)
|
| 275 |
+
i = 0
|
| 276 |
+
start_new_word = True
|
| 277 |
+
output = []
|
| 278 |
+
while i < len(chars):
|
| 279 |
+
char = chars[i]
|
| 280 |
+
if _is_punctuation(char):
|
| 281 |
+
output.append([char])
|
| 282 |
+
start_new_word = True
|
| 283 |
+
else:
|
| 284 |
+
if start_new_word:
|
| 285 |
+
output.append([])
|
| 286 |
+
start_new_word = False
|
| 287 |
+
output[-1].append(char)
|
| 288 |
+
i += 1
|
| 289 |
+
|
| 290 |
+
return ["".join(x) for x in output]
|
| 291 |
+
|
| 292 |
+
def _tokenize_chinese_chars(self, text):
|
| 293 |
+
"""Adds whitespace around any CJK character."""
|
| 294 |
+
output = []
|
| 295 |
+
for char in text:
|
| 296 |
+
cp = ord(char)
|
| 297 |
+
if self._is_chinese_char(cp):
|
| 298 |
+
output.append(" ")
|
| 299 |
+
output.append(char)
|
| 300 |
+
output.append(" ")
|
| 301 |
+
else:
|
| 302 |
+
output.append(char)
|
| 303 |
+
return "".join(output)
|
| 304 |
+
|
| 305 |
+
def _is_chinese_char(self, cp):
|
| 306 |
+
"""Checks whether CP is the codepoint of a CJK character."""
|
| 307 |
+
# This defines a "chinese character" as anything in the CJK Unicode block:
|
| 308 |
+
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
|
| 309 |
+
#
|
| 310 |
+
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
|
| 311 |
+
# despite its name. The modern Korean Hangul alphabet is a different block,
|
| 312 |
+
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
|
| 313 |
+
# space-separated words, so they are not treated specially and handled
|
| 314 |
+
# like the all of the other languages.
|
| 315 |
+
if ((cp >= 0x4E00 and cp <= 0x9FFF) or #
|
| 316 |
+
(cp >= 0x3400 and cp <= 0x4DBF) or #
|
| 317 |
+
(cp >= 0x20000 and cp <= 0x2A6DF) or #
|
| 318 |
+
(cp >= 0x2A700 and cp <= 0x2B73F) or #
|
| 319 |
+
(cp >= 0x2B740 and cp <= 0x2B81F) or #
|
| 320 |
+
(cp >= 0x2B820 and cp <= 0x2CEAF) or
|
| 321 |
+
(cp >= 0xF900 and cp <= 0xFAFF) or #
|
| 322 |
+
(cp >= 0x2F800 and cp <= 0x2FA1F)): #
|
| 323 |
+
return True
|
| 324 |
+
|
| 325 |
+
return False
|
| 326 |
+
|
| 327 |
+
def _clean_text(self, text):
|
| 328 |
+
"""Performs invalid character removal and whitespace cleanup on text."""
|
| 329 |
+
output = []
|
| 330 |
+
for char in text:
|
| 331 |
+
cp = ord(char)
|
| 332 |
+
if cp == 0 or cp == 0xfffd or _is_control(char):
|
| 333 |
+
continue
|
| 334 |
+
if _is_whitespace(char):
|
| 335 |
+
output.append(" ")
|
| 336 |
+
else:
|
| 337 |
+
output.append(char)
|
| 338 |
+
return "".join(output)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class WordpieceTokenizer(object):
|
| 342 |
+
"""Runs WordPiece tokenization."""
|
| 343 |
+
|
| 344 |
+
def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=100):
|
| 345 |
+
self.vocab = vocab
|
| 346 |
+
self.unk_token = unk_token
|
| 347 |
+
self.max_input_chars_per_word = max_input_chars_per_word
|
| 348 |
+
|
| 349 |
+
def tokenize(self, text):
|
| 350 |
+
"""Tokenizes a piece of text into its word pieces.
|
| 351 |
+
|
| 352 |
+
This uses a greedy longest-match-first algorithm to perform tokenization
|
| 353 |
+
using the given vocabulary.
|
| 354 |
+
|
| 355 |
+
For example:
|
| 356 |
+
input = "unaffable"
|
| 357 |
+
output = ["un", "##aff", "##able"]
|
| 358 |
+
|
| 359 |
+
Args:
|
| 360 |
+
text: A single token or whitespace separated tokens. This should have
|
| 361 |
+
already been passed through `BasicTokenizer`.
|
| 362 |
+
|
| 363 |
+
Returns:
|
| 364 |
+
A list of wordpiece tokens.
|
| 365 |
+
"""
|
| 366 |
+
|
| 367 |
+
output_tokens = []
|
| 368 |
+
for token in whitespace_tokenize(text):
|
| 369 |
+
chars = list(token)
|
| 370 |
+
if len(chars) > self.max_input_chars_per_word:
|
| 371 |
+
output_tokens.append(self.unk_token)
|
| 372 |
+
continue
|
| 373 |
+
|
| 374 |
+
is_bad = False
|
| 375 |
+
start = 0
|
| 376 |
+
sub_tokens = []
|
| 377 |
+
while start < len(chars):
|
| 378 |
+
end = len(chars)
|
| 379 |
+
cur_substr = None
|
| 380 |
+
while start < end:
|
| 381 |
+
substr = "".join(chars[start:end])
|
| 382 |
+
if start > 0:
|
| 383 |
+
substr = "##" + substr
|
| 384 |
+
if substr in self.vocab:
|
| 385 |
+
cur_substr = substr
|
| 386 |
+
break
|
| 387 |
+
end -= 1
|
| 388 |
+
if cur_substr is None:
|
| 389 |
+
is_bad = True
|
| 390 |
+
break
|
| 391 |
+
sub_tokens.append(cur_substr)
|
| 392 |
+
start = end
|
| 393 |
+
|
| 394 |
+
if is_bad:
|
| 395 |
+
output_tokens.append(self.unk_token)
|
| 396 |
+
else:
|
| 397 |
+
output_tokens.extend(sub_tokens)
|
| 398 |
+
return output_tokens
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def _is_whitespace(char):
|
| 402 |
+
"""Checks whether `chars` is a whitespace character."""
|
| 403 |
+
# \t, \n, and \r are technically contorl characters but we treat them
|
| 404 |
+
# as whitespace since they are generally considered as such.
|
| 405 |
+
if char == " " or char == "\t" or char == "\n" or char == "\r":
|
| 406 |
+
return True
|
| 407 |
+
cat = unicodedata.category(char)
|
| 408 |
+
if cat == "Zs":
|
| 409 |
+
return True
|
| 410 |
+
return False
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def _is_control(char):
|
| 414 |
+
"""Checks whether `chars` is a control character."""
|
| 415 |
+
# These are technically control characters but we count them as whitespace
|
| 416 |
+
# characters.
|
| 417 |
+
if char == "\t" or char == "\n" or char == "\r":
|
| 418 |
+
return False
|
| 419 |
+
cat = unicodedata.category(char)
|
| 420 |
+
if cat.startswith("C"):
|
| 421 |
+
return True
|
| 422 |
+
return False
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def _is_punctuation(char):
|
| 426 |
+
"""Checks whether `chars` is a punctuation character."""
|
| 427 |
+
cp = ord(char)
|
| 428 |
+
# We treat all non-letter/number ASCII as punctuation.
|
| 429 |
+
# Characters such as "^", "$", and "`" are not in the Unicode
|
| 430 |
+
# Punctuation class but we treat them as punctuation anyways, for
|
| 431 |
+
# consistency.
|
| 432 |
+
if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or
|
| 433 |
+
(cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)):
|
| 434 |
+
return True
|
| 435 |
+
cat = unicodedata.category(char)
|
| 436 |
+
if cat.startswith("P"):
|
| 437 |
+
return True
|
| 438 |
+
return False
|
SimTranslation/code/unibert_waitk_0901_stack/bi_dataprocess.sh
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 这里有了一个bert-model-name的内容,这个内容是之前没见过的
|
| 2 |
+
TEXT=./
|
| 3 |
+
src=de
|
| 4 |
+
tgt=en
|
| 5 |
+
destdir=bi_iwslt_${src}_${tgt}
|
| 6 |
+
python preprocess.py --source-lang $src --target-lang $tgt \
|
| 7 |
+
--trainpref $TEXT/train --validpref $TEXT/valid --testpref $TEXT/test \
|
| 8 |
+
--destdir $destdir --joined-dictionary --bert-model-name ./bert-base-german-dbmdz-uncased \
|
SimTranslation/code/unibert_waitk_0901_stack/code
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
SimTranslation/code/unibert_waitk_0901_stack/docs/Makefile
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Minimal makefile for Sphinx documentation
|
| 2 |
+
#
|
| 3 |
+
|
| 4 |
+
# You can set these variables from the command line.
|
| 5 |
+
SPHINXOPTS =
|
| 6 |
+
SPHINXBUILD = python -msphinx
|
| 7 |
+
SPHINXPROJ = fairseq
|
| 8 |
+
SOURCEDIR = .
|
| 9 |
+
BUILDDIR = _build
|
| 10 |
+
|
| 11 |
+
# Put it first so that "make" without argument is like "make help".
|
| 12 |
+
help:
|
| 13 |
+
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
| 14 |
+
|
| 15 |
+
.PHONY: help Makefile
|
| 16 |
+
|
| 17 |
+
# Catch-all target: route all unknown targets to Sphinx using the new
|
| 18 |
+
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
|
| 19 |
+
%: Makefile
|
| 20 |
+
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
SimTranslation/code/unibert_waitk_0901_stack/docs/_static/theme_overrides.css
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.wy-table-responsive table td kbd {
|
| 2 |
+
white-space: nowrap;
|
| 3 |
+
}
|
| 4 |
+
.wy-table-responsive table td {
|
| 5 |
+
white-space: normal !important;
|
| 6 |
+
}
|
| 7 |
+
.wy-table-responsive {
|
| 8 |
+
overflow: visible !important;
|
| 9 |
+
}
|
SimTranslation/code/unibert_waitk_0901_stack/docs/command_line_tools.rst
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. _Command-line Tools:
|
| 2 |
+
|
| 3 |
+
Command-line Tools
|
| 4 |
+
==================
|
| 5 |
+
|
| 6 |
+
Fairseq provides several command-line tools for training and evaluating models:
|
| 7 |
+
|
| 8 |
+
- :ref:`fairseq-preprocess`: Data pre-processing: build vocabularies and binarize training data
|
| 9 |
+
- :ref:`fairseq-train`: Train a new model on one or multiple GPUs
|
| 10 |
+
- :ref:`fairseq-generate`: Translate pre-processed data with a trained model
|
| 11 |
+
- :ref:`fairseq-interactive`: Translate raw text with a trained model
|
| 12 |
+
- :ref:`fairseq-score`: BLEU scoring of generated translations against reference translations
|
| 13 |
+
- :ref:`fairseq-eval-lm`: Language model evaluation
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
.. _fairseq-preprocess:
|
| 17 |
+
|
| 18 |
+
fairseq-preprocess
|
| 19 |
+
~~~~~~~~~~~~~~~~~~
|
| 20 |
+
.. automodule:: preprocess
|
| 21 |
+
|
| 22 |
+
.. argparse::
|
| 23 |
+
:module: fairseq.options
|
| 24 |
+
:func: get_preprocessing_parser
|
| 25 |
+
:prog: fairseq-preprocess
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
.. _fairseq-train:
|
| 29 |
+
|
| 30 |
+
fairseq-train
|
| 31 |
+
~~~~~~~~~~~~~
|
| 32 |
+
.. automodule:: train
|
| 33 |
+
|
| 34 |
+
.. argparse::
|
| 35 |
+
:module: fairseq.options
|
| 36 |
+
:func: get_training_parser
|
| 37 |
+
:prog: fairseq-train
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
.. _fairseq-generate:
|
| 41 |
+
|
| 42 |
+
fairseq-generate
|
| 43 |
+
~~~~~~~~~~~~~~~~
|
| 44 |
+
.. automodule:: generate
|
| 45 |
+
|
| 46 |
+
.. argparse::
|
| 47 |
+
:module: fairseq.options
|
| 48 |
+
:func: get_generation_parser
|
| 49 |
+
:prog: fairseq-generate
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
.. _fairseq-interactive:
|
| 53 |
+
|
| 54 |
+
fairseq-interactive
|
| 55 |
+
~~~~~~~~~~~~~~~~~~~
|
| 56 |
+
.. automodule:: interactive
|
| 57 |
+
|
| 58 |
+
.. argparse::
|
| 59 |
+
:module: fairseq.options
|
| 60 |
+
:func: get_interactive_generation_parser
|
| 61 |
+
:prog: fairseq-interactive
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
.. _fairseq-score:
|
| 65 |
+
|
| 66 |
+
fairseq-score
|
| 67 |
+
~~~~~~~~~~~~~
|
| 68 |
+
.. automodule:: score
|
| 69 |
+
|
| 70 |
+
.. argparse::
|
| 71 |
+
:module: fairseq_cli.score
|
| 72 |
+
:func: get_parser
|
| 73 |
+
:prog: fairseq-score
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
.. _fairseq-eval-lm:
|
| 77 |
+
|
| 78 |
+
fairseq-eval-lm
|
| 79 |
+
~~~~~~~~~~~~~~~
|
| 80 |
+
.. automodule:: eval_lm
|
| 81 |
+
|
| 82 |
+
.. argparse::
|
| 83 |
+
:module: fairseq.options
|
| 84 |
+
:func: get_eval_lm_parser
|
| 85 |
+
:prog: fairseq-eval-lm
|
SimTranslation/code/unibert_waitk_0901_stack/docs/conf.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
#
|
| 4 |
+
# fairseq documentation build configuration file, created by
|
| 5 |
+
# sphinx-quickstart on Fri Aug 17 21:45:30 2018.
|
| 6 |
+
#
|
| 7 |
+
# This file is execfile()d with the current directory set to its
|
| 8 |
+
# containing dir.
|
| 9 |
+
#
|
| 10 |
+
# Note that not all possible configuration values are present in this
|
| 11 |
+
# autogenerated file.
|
| 12 |
+
#
|
| 13 |
+
# All configuration values have a default; values that are commented out
|
| 14 |
+
# serve to show the default.
|
| 15 |
+
|
| 16 |
+
# If extensions (or modules to document with autodoc) are in another directory,
|
| 17 |
+
# add these directories to sys.path here. If the directory is relative to the
|
| 18 |
+
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
| 19 |
+
|
| 20 |
+
import os
|
| 21 |
+
import sys
|
| 22 |
+
|
| 23 |
+
# source code directory, relative to this file, for sphinx-autobuild
|
| 24 |
+
sys.path.insert(0, os.path.abspath('..'))
|
| 25 |
+
|
| 26 |
+
source_suffix = ['.rst']
|
| 27 |
+
|
| 28 |
+
# -- General configuration ------------------------------------------------
|
| 29 |
+
|
| 30 |
+
# If your documentation needs a minimal Sphinx version, state it here.
|
| 31 |
+
#
|
| 32 |
+
# needs_sphinx = '1.0'
|
| 33 |
+
|
| 34 |
+
# Add any Sphinx extension module names here, as strings. They can be
|
| 35 |
+
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
|
| 36 |
+
# ones.
|
| 37 |
+
extensions = [
|
| 38 |
+
'sphinx.ext.autodoc',
|
| 39 |
+
'sphinx.ext.intersphinx',
|
| 40 |
+
'sphinx.ext.viewcode',
|
| 41 |
+
'sphinx.ext.napoleon',
|
| 42 |
+
'sphinxarg.ext',
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
# Add any paths that contain templates here, relative to this directory.
|
| 46 |
+
templates_path = ['_templates']
|
| 47 |
+
|
| 48 |
+
# The master toctree document.
|
| 49 |
+
master_doc = 'index'
|
| 50 |
+
|
| 51 |
+
# General information about the project.
|
| 52 |
+
project = 'fairseq'
|
| 53 |
+
copyright = '2019, Facebook AI Research (FAIR)'
|
| 54 |
+
author = 'Facebook AI Research (FAIR)'
|
| 55 |
+
|
| 56 |
+
github_doc_root = 'https://github.com/pytorch/fairseq/tree/master/docs/'
|
| 57 |
+
|
| 58 |
+
# The version info for the project you're documenting, acts as replacement for
|
| 59 |
+
# |version| and |release|, also used in various other places throughout the
|
| 60 |
+
# built documents.
|
| 61 |
+
#
|
| 62 |
+
# The short X.Y version.
|
| 63 |
+
version = '0.9.0'
|
| 64 |
+
# The full version, including alpha/beta/rc tags.
|
| 65 |
+
release = '0.9.0'
|
| 66 |
+
|
| 67 |
+
# The language for content autogenerated by Sphinx. Refer to documentation
|
| 68 |
+
# for a list of supported languages.
|
| 69 |
+
#
|
| 70 |
+
# This is also used if you do content translation via gettext catalogs.
|
| 71 |
+
# Usually you set "language" from the command line for these cases.
|
| 72 |
+
language = None
|
| 73 |
+
|
| 74 |
+
# List of patterns, relative to source directory, that match files and
|
| 75 |
+
# directories to ignore when looking for source files.
|
| 76 |
+
# This patterns also effect to html_static_path and html_extra_path
|
| 77 |
+
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
|
| 78 |
+
|
| 79 |
+
# The name of the Pygments (syntax highlighting) style to use.
|
| 80 |
+
pygments_style = 'sphinx'
|
| 81 |
+
highlight_language = 'python'
|
| 82 |
+
|
| 83 |
+
# If true, `todo` and `todoList` produce output, else they produce nothing.
|
| 84 |
+
todo_include_todos = False
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# -- Options for HTML output ----------------------------------------------
|
| 88 |
+
|
| 89 |
+
# The theme to use for HTML and HTML Help pages. See the documentation for
|
| 90 |
+
# a list of builtin themes.
|
| 91 |
+
#
|
| 92 |
+
html_theme = 'sphinx_rtd_theme'
|
| 93 |
+
|
| 94 |
+
# Theme options are theme-specific and customize the look and feel of a theme
|
| 95 |
+
# further. For a list of options available for each theme, see the
|
| 96 |
+
# documentation.
|
| 97 |
+
#
|
| 98 |
+
# html_theme_options = {}
|
| 99 |
+
|
| 100 |
+
# Add any paths that contain custom static files (such as style sheets) here,
|
| 101 |
+
# relative to this directory. They are copied after the builtin static files,
|
| 102 |
+
# so a file named "default.css" will overwrite the builtin "default.css".
|
| 103 |
+
html_static_path = ['_static']
|
| 104 |
+
|
| 105 |
+
html_context = {
|
| 106 |
+
'css_files': [
|
| 107 |
+
'_static/theme_overrides.css', # override wide tables in RTD theme
|
| 108 |
+
],
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
# Custom sidebar templates, must be a dictionary that maps document names
|
| 112 |
+
# to template names.
|
| 113 |
+
#
|
| 114 |
+
# This is required for the alabaster theme
|
| 115 |
+
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
|
| 116 |
+
#html_sidebars = {
|
| 117 |
+
# '**': [
|
| 118 |
+
# 'about.html',
|
| 119 |
+
# 'navigation.html',
|
| 120 |
+
# 'relations.html', # needs 'show_related': True theme option to display
|
| 121 |
+
# 'searchbox.html',
|
| 122 |
+
# 'donate.html',
|
| 123 |
+
# ]
|
| 124 |
+
#}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# Example configuration for intersphinx: refer to the Python standard library.
|
| 128 |
+
intersphinx_mapping = {
|
| 129 |
+
'numpy': ('http://docs.scipy.org/doc/numpy/', None),
|
| 130 |
+
'python': ('https://docs.python.org/', None),
|
| 131 |
+
'torch': ('https://pytorch.org/docs/master/', None),
|
| 132 |
+
}
|
SimTranslation/code/unibert_waitk_0901_stack/docs/criterions.rst
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. role:: hidden
|
| 2 |
+
:class: hidden-section
|
| 3 |
+
|
| 4 |
+
.. _Criterions:
|
| 5 |
+
|
| 6 |
+
Criterions
|
| 7 |
+
==========
|
| 8 |
+
|
| 9 |
+
Criterions compute the loss function given the model and batch, roughly::
|
| 10 |
+
|
| 11 |
+
loss = criterion(model, batch)
|
| 12 |
+
|
| 13 |
+
.. automodule:: fairseq.criterions
|
| 14 |
+
:members:
|
| 15 |
+
|
| 16 |
+
.. autoclass:: fairseq.criterions.FairseqCriterion
|
| 17 |
+
:members:
|
| 18 |
+
:undoc-members:
|
| 19 |
+
|
| 20 |
+
.. autoclass:: fairseq.criterions.adaptive_loss.AdaptiveLoss
|
| 21 |
+
:members:
|
| 22 |
+
:undoc-members:
|
| 23 |
+
.. autoclass:: fairseq.criterions.composite_loss.CompositeLoss
|
| 24 |
+
:members:
|
| 25 |
+
:undoc-members:
|
| 26 |
+
.. autoclass:: fairseq.criterions.cross_entropy.CrossEntropyCriterion
|
| 27 |
+
:members:
|
| 28 |
+
:undoc-members:
|
| 29 |
+
.. autoclass:: fairseq.criterions.label_smoothed_cross_entropy.LabelSmoothedCrossEntropyCriterion
|
| 30 |
+
:members:
|
| 31 |
+
:undoc-members:
|
SimTranslation/code/unibert_waitk_0901_stack/docs/data.rst
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. role:: hidden
|
| 2 |
+
:class: hidden-section
|
| 3 |
+
|
| 4 |
+
.. module:: fairseq.data
|
| 5 |
+
|
| 6 |
+
Data Loading and Utilities
|
| 7 |
+
==========================
|
| 8 |
+
|
| 9 |
+
.. _datasets:
|
| 10 |
+
|
| 11 |
+
Datasets
|
| 12 |
+
--------
|
| 13 |
+
|
| 14 |
+
**Datasets** define the data format and provide helpers for creating
|
| 15 |
+
mini-batches.
|
| 16 |
+
|
| 17 |
+
.. autoclass:: fairseq.data.FairseqDataset
|
| 18 |
+
:members:
|
| 19 |
+
.. autoclass:: fairseq.data.LanguagePairDataset
|
| 20 |
+
:members:
|
| 21 |
+
.. autoclass:: fairseq.data.MonolingualDataset
|
| 22 |
+
:members:
|
| 23 |
+
|
| 24 |
+
**Helper Datasets**
|
| 25 |
+
|
| 26 |
+
These datasets wrap other :class:`fairseq.data.FairseqDataset` instances and
|
| 27 |
+
provide additional functionality:
|
| 28 |
+
|
| 29 |
+
.. autoclass:: fairseq.data.BacktranslationDataset
|
| 30 |
+
:members:
|
| 31 |
+
.. autoclass:: fairseq.data.ConcatDataset
|
| 32 |
+
:members:
|
| 33 |
+
.. autoclass:: fairseq.data.ResamplingDataset
|
| 34 |
+
:members:
|
| 35 |
+
.. autoclass:: fairseq.data.RoundRobinZipDatasets
|
| 36 |
+
:members:
|
| 37 |
+
.. autoclass:: fairseq.data.TransformEosDataset
|
| 38 |
+
:members:
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
Dictionary
|
| 42 |
+
----------
|
| 43 |
+
|
| 44 |
+
.. autoclass:: fairseq.data.Dictionary
|
| 45 |
+
:members:
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
Iterators
|
| 49 |
+
---------
|
| 50 |
+
|
| 51 |
+
.. autoclass:: fairseq.data.CountingIterator
|
| 52 |
+
:members:
|
| 53 |
+
.. autoclass:: fairseq.data.EpochBatchIterator
|
| 54 |
+
:members:
|
| 55 |
+
.. autoclass:: fairseq.data.GroupedIterator
|
| 56 |
+
:members:
|
| 57 |
+
.. autoclass:: fairseq.data.ShardedIterator
|
| 58 |
+
:members:
|
SimTranslation/code/unibert_waitk_0901_stack/docs/docutils.conf
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[writers]
|
| 2 |
+
option-limit=0
|
SimTranslation/code/unibert_waitk_0901_stack/docs/getting_started.rst
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Evaluating Pre-trained Models
|
| 2 |
+
=============================
|
| 3 |
+
|
| 4 |
+
First, download a pre-trained model along with its vocabularies:
|
| 5 |
+
|
| 6 |
+
.. code-block:: console
|
| 7 |
+
|
| 8 |
+
> curl https://dl.fbaipublicfiles.com/fairseq/models/wmt14.v2.en-fr.fconv-py.tar.bz2 | tar xvjf -
|
| 9 |
+
|
| 10 |
+
This model uses a `Byte Pair Encoding (BPE)
|
| 11 |
+
vocabulary <https://arxiv.org/abs/1508.07909>`__, so we'll have to apply
|
| 12 |
+
the encoding to the source text before it can be translated. This can be
|
| 13 |
+
done with the
|
| 14 |
+
`apply\_bpe.py <https://github.com/rsennrich/subword-nmt/blob/master/subword_nmt/apply_bpe.py>`__
|
| 15 |
+
script using the ``wmt14.en-fr.fconv-cuda/bpecodes`` file. ``@@`` is
|
| 16 |
+
used as a continuation marker and the original text can be easily
|
| 17 |
+
recovered with e.g. ``sed s/@@ //g`` or by passing the ``--remove-bpe``
|
| 18 |
+
flag to :ref:`fairseq-generate`. Prior to BPE, input text needs to be tokenized
|
| 19 |
+
using ``tokenizer.perl`` from
|
| 20 |
+
`mosesdecoder <https://github.com/moses-smt/mosesdecoder>`__.
|
| 21 |
+
|
| 22 |
+
Let's use :ref:`fairseq-interactive` to generate translations interactively.
|
| 23 |
+
Here, we use a beam size of 5 and preprocess the input with the Moses
|
| 24 |
+
tokenizer and the given Byte-Pair Encoding vocabulary. It will automatically
|
| 25 |
+
remove the BPE continuation markers and detokenize the output.
|
| 26 |
+
|
| 27 |
+
.. code-block:: console
|
| 28 |
+
|
| 29 |
+
> MODEL_DIR=wmt14.en-fr.fconv-py
|
| 30 |
+
> fairseq-interactive \
|
| 31 |
+
--path $MODEL_DIR/model.pt $MODEL_DIR \
|
| 32 |
+
--beam 5 --source-lang en --target-lang fr \
|
| 33 |
+
--tokenizer moses \
|
| 34 |
+
--bpe subword_nmt --bpe-codes $MODEL_DIR/bpecodes
|
| 35 |
+
| loading model(s) from wmt14.en-fr.fconv-py/model.pt
|
| 36 |
+
| [en] dictionary: 44206 types
|
| 37 |
+
| [fr] dictionary: 44463 types
|
| 38 |
+
| Type the input sentence and press return:
|
| 39 |
+
Why is it rare to discover new marine mammal species?
|
| 40 |
+
S-0 Why is it rare to discover new marine mam@@ mal species ?
|
| 41 |
+
H-0 -0.0643349438905716 Pourquoi est-il rare de découvrir de nouvelles espèces de mammifères marins?
|
| 42 |
+
P-0 -0.0763 -0.1849 -0.0956 -0.0946 -0.0735 -0.1150 -0.1301 -0.0042 -0.0321 -0.0171 -0.0052 -0.0062 -0.0015
|
| 43 |
+
|
| 44 |
+
This generation script produces three types of outputs: a line prefixed
|
| 45 |
+
with *O* is a copy of the original source sentence; *H* is the
|
| 46 |
+
hypothesis along with an average log-likelihood; and *P* is the
|
| 47 |
+
positional score per token position, including the
|
| 48 |
+
end-of-sentence marker which is omitted from the text.
|
| 49 |
+
|
| 50 |
+
See the `README <https://github.com/pytorch/fairseq#pre-trained-models>`__ for a
|
| 51 |
+
full list of pre-trained models available.
|
| 52 |
+
|
| 53 |
+
Training a New Model
|
| 54 |
+
====================
|
| 55 |
+
|
| 56 |
+
The following tutorial is for machine translation. For an example of how
|
| 57 |
+
to use Fairseq for other tasks, such as :ref:`language modeling`, please see the
|
| 58 |
+
``examples/`` directory.
|
| 59 |
+
|
| 60 |
+
Data Pre-processing
|
| 61 |
+
-------------------
|
| 62 |
+
|
| 63 |
+
Fairseq contains example pre-processing scripts for several translation
|
| 64 |
+
datasets: IWSLT 2014 (German-English), WMT 2014 (English-French) and WMT
|
| 65 |
+
2014 (English-German). To pre-process and binarize the IWSLT dataset:
|
| 66 |
+
|
| 67 |
+
.. code-block:: console
|
| 68 |
+
|
| 69 |
+
> cd examples/translation/
|
| 70 |
+
> bash prepare-iwslt14.sh
|
| 71 |
+
> cd ../..
|
| 72 |
+
> TEXT=examples/translation/iwslt14.tokenized.de-en
|
| 73 |
+
> fairseq-preprocess --source-lang de --target-lang en \
|
| 74 |
+
--trainpref $TEXT/train --validpref $TEXT/valid --testpref $TEXT/test \
|
| 75 |
+
--destdir data-bin/iwslt14.tokenized.de-en
|
| 76 |
+
|
| 77 |
+
This will write binarized data that can be used for model training to
|
| 78 |
+
``data-bin/iwslt14.tokenized.de-en``.
|
| 79 |
+
|
| 80 |
+
Training
|
| 81 |
+
--------
|
| 82 |
+
|
| 83 |
+
Use :ref:`fairseq-train` to train a new model. Here a few example settings that work
|
| 84 |
+
well for the IWSLT 2014 dataset:
|
| 85 |
+
|
| 86 |
+
.. code-block:: console
|
| 87 |
+
|
| 88 |
+
> mkdir -p checkpoints/fconv
|
| 89 |
+
> CUDA_VISIBLE_DEVICES=0 fairseq-train data-bin/iwslt14.tokenized.de-en \
|
| 90 |
+
--lr 0.25 --clip-norm 0.1 --dropout 0.2 --max-tokens 4000 \
|
| 91 |
+
--arch fconv_iwslt_de_en --save-dir checkpoints/fconv
|
| 92 |
+
|
| 93 |
+
By default, :ref:`fairseq-train` will use all available GPUs on your machine. Use the
|
| 94 |
+
``CUDA_VISIBLE_DEVICES`` environment variable to select specific GPUs and/or to
|
| 95 |
+
change the number of GPU devices that will be used.
|
| 96 |
+
|
| 97 |
+
Also note that the batch size is specified in terms of the maximum
|
| 98 |
+
number of tokens per batch (``--max-tokens``). You may need to use a
|
| 99 |
+
smaller value depending on the available GPU memory on your system.
|
| 100 |
+
|
| 101 |
+
Generation
|
| 102 |
+
----------
|
| 103 |
+
|
| 104 |
+
Once your model is trained, you can generate translations using
|
| 105 |
+
:ref:`fairseq-generate` **(for binarized data)** or
|
| 106 |
+
:ref:`fairseq-interactive` **(for raw text)**:
|
| 107 |
+
|
| 108 |
+
.. code-block:: console
|
| 109 |
+
|
| 110 |
+
> fairseq-generate data-bin/iwslt14.tokenized.de-en \
|
| 111 |
+
--path checkpoints/fconv/checkpoint_best.pt \
|
| 112 |
+
--batch-size 128 --beam 5
|
| 113 |
+
| [de] dictionary: 35475 types
|
| 114 |
+
| [en] dictionary: 24739 types
|
| 115 |
+
| data-bin/iwslt14.tokenized.de-en test 6750 examples
|
| 116 |
+
| model fconv
|
| 117 |
+
| loaded checkpoint trainings/fconv/checkpoint_best.pt
|
| 118 |
+
S-721 danke .
|
| 119 |
+
T-721 thank you .
|
| 120 |
+
...
|
| 121 |
+
|
| 122 |
+
To generate translations with only a CPU, use the ``--cpu`` flag. BPE
|
| 123 |
+
continuation markers can be removed with the ``--remove-bpe`` flag.
|
| 124 |
+
|
| 125 |
+
Advanced Training Options
|
| 126 |
+
=========================
|
| 127 |
+
|
| 128 |
+
Large mini-batch training with delayed updates
|
| 129 |
+
----------------------------------------------
|
| 130 |
+
|
| 131 |
+
The ``--update-freq`` option can be used to accumulate gradients from
|
| 132 |
+
multiple mini-batches and delay updating, creating a larger effective
|
| 133 |
+
batch size. Delayed updates can also improve training speed by reducing
|
| 134 |
+
inter-GPU communication costs and by saving idle time caused by variance
|
| 135 |
+
in workload across GPUs. See `Ott et al.
|
| 136 |
+
(2018) <https://arxiv.org/abs/1806.00187>`__ for more details.
|
| 137 |
+
|
| 138 |
+
To train on a single GPU with an effective batch size that is equivalent
|
| 139 |
+
to training on 8 GPUs:
|
| 140 |
+
|
| 141 |
+
.. code-block:: console
|
| 142 |
+
|
| 143 |
+
> CUDA_VISIBLE_DEVICES=0 fairseq-train --update-freq 8 (...)
|
| 144 |
+
|
| 145 |
+
Training with half precision floating point (FP16)
|
| 146 |
+
--------------------------------------------------
|
| 147 |
+
|
| 148 |
+
.. note::
|
| 149 |
+
|
| 150 |
+
FP16 training requires a Volta GPU and CUDA 9.1 or greater
|
| 151 |
+
|
| 152 |
+
Recent GPUs enable efficient half precision floating point computation,
|
| 153 |
+
e.g., using `Nvidia Tensor Cores
|
| 154 |
+
<https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html>`__.
|
| 155 |
+
Fairseq supports FP16 training with the ``--fp16`` flag:
|
| 156 |
+
|
| 157 |
+
.. code-block:: console
|
| 158 |
+
|
| 159 |
+
> fairseq-train --fp16 (...)
|
| 160 |
+
|
| 161 |
+
Distributed training
|
| 162 |
+
--------------------
|
| 163 |
+
|
| 164 |
+
Distributed training in fairseq is implemented on top of ``torch.distributed``.
|
| 165 |
+
The easiest way to launch jobs is with the `torch.distributed.launch
|
| 166 |
+
<https://pytorch.org/docs/stable/distributed.html#launch-utility>`__ tool.
|
| 167 |
+
|
| 168 |
+
For example, to train a large English-German Transformer model on 2 nodes each
|
| 169 |
+
with 8 GPUs (in total 16 GPUs), run the following command on each node,
|
| 170 |
+
replacing ``node_rank=0`` with ``node_rank=1`` on the second node:
|
| 171 |
+
|
| 172 |
+
.. code-block:: console
|
| 173 |
+
|
| 174 |
+
> python -m torch.distributed.launch --nproc_per_node=8 \
|
| 175 |
+
--nnodes=2 --node_rank=0 --master_addr="192.168.1.1" \
|
| 176 |
+
--master_port=1234 \
|
| 177 |
+
$(which fairseq-train) data-bin/wmt16_en_de_bpe32k \
|
| 178 |
+
--arch transformer_vaswani_wmt_en_de_big --share-all-embeddings \
|
| 179 |
+
--optimizer adam --adam-betas '(0.9, 0.98)' --clip-norm 0.0 \
|
| 180 |
+
--lr-scheduler inverse_sqrt --warmup-init-lr 1e-07 --warmup-updates 4000 \
|
| 181 |
+
--lr 0.0005 --min-lr 1e-09 \
|
| 182 |
+
--dropout 0.3 --weight-decay 0.0 --criterion label_smoothed_cross_entropy --label-smoothing 0.1 \
|
| 183 |
+
--max-tokens 3584 \
|
| 184 |
+
--fp16 --distributed-no-spawn
|
SimTranslation/code/unibert_waitk_0901_stack/docs/index.rst
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. fairseq documentation master file, created by
|
| 2 |
+
sphinx-quickstart on Fri Aug 17 21:45:30 2018.
|
| 3 |
+
You can adapt this file completely to your liking, but it should at least
|
| 4 |
+
contain the root `toctree` directive.
|
| 5 |
+
|
| 6 |
+
:github_url: https://github.com/pytorch/fairseq
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
fairseq documentation
|
| 10 |
+
=====================
|
| 11 |
+
|
| 12 |
+
Fairseq is a sequence modeling toolkit written in `PyTorch
|
| 13 |
+
<http://pytorch.org/>`_ that allows researchers and developers to
|
| 14 |
+
train custom models for translation, summarization, language modeling and other
|
| 15 |
+
text generation tasks.
|
| 16 |
+
|
| 17 |
+
.. toctree::
|
| 18 |
+
:maxdepth: 1
|
| 19 |
+
:caption: Getting Started
|
| 20 |
+
|
| 21 |
+
getting_started
|
| 22 |
+
command_line_tools
|
| 23 |
+
|
| 24 |
+
.. toctree::
|
| 25 |
+
:maxdepth: 1
|
| 26 |
+
:caption: Extending Fairseq
|
| 27 |
+
|
| 28 |
+
overview
|
| 29 |
+
tutorial_simple_lstm
|
| 30 |
+
tutorial_classifying_names
|
| 31 |
+
|
| 32 |
+
.. toctree::
|
| 33 |
+
:maxdepth: 2
|
| 34 |
+
:caption: Library Reference
|
| 35 |
+
|
| 36 |
+
tasks
|
| 37 |
+
models
|
| 38 |
+
criterions
|
| 39 |
+
optim
|
| 40 |
+
lr_scheduler
|
| 41 |
+
data
|
| 42 |
+
modules
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
Indices and tables
|
| 46 |
+
==================
|
| 47 |
+
|
| 48 |
+
* :ref:`genindex`
|
| 49 |
+
* :ref:`search`
|
SimTranslation/code/unibert_waitk_0901_stack/docs/lr_scheduler.rst
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. role:: hidden
|
| 2 |
+
:class: hidden-section
|
| 3 |
+
|
| 4 |
+
.. _Learning Rate Schedulers:
|
| 5 |
+
|
| 6 |
+
Learning Rate Schedulers
|
| 7 |
+
========================
|
| 8 |
+
|
| 9 |
+
Learning Rate Schedulers update the learning rate over the course of training.
|
| 10 |
+
Learning rates can be updated after each update via :func:`step_update` or at
|
| 11 |
+
epoch boundaries via :func:`step`.
|
| 12 |
+
|
| 13 |
+
.. automodule:: fairseq.optim.lr_scheduler
|
| 14 |
+
:members:
|
| 15 |
+
|
| 16 |
+
.. autoclass:: fairseq.optim.lr_scheduler.FairseqLRScheduler
|
| 17 |
+
:members:
|
| 18 |
+
:undoc-members:
|
| 19 |
+
|
| 20 |
+
.. autoclass:: fairseq.optim.lr_scheduler.cosine_lr_scheduler.CosineSchedule
|
| 21 |
+
:members:
|
| 22 |
+
:undoc-members:
|
| 23 |
+
.. autoclass:: fairseq.optim.lr_scheduler.fixed_schedule.FixedSchedule
|
| 24 |
+
:members:
|
| 25 |
+
:undoc-members:
|
| 26 |
+
.. autoclass:: fairseq.optim.lr_scheduler.inverse_square_root_schedule.InverseSquareRootSchedule
|
| 27 |
+
:members:
|
| 28 |
+
:undoc-members:
|
| 29 |
+
.. autoclass:: fairseq.optim.lr_scheduler.reduce_lr_on_plateau.ReduceLROnPlateau
|
| 30 |
+
:members:
|
| 31 |
+
:undoc-members:
|
| 32 |
+
.. autoclass:: fairseq.optim.lr_scheduler.triangular_lr_scheduler.TriangularSchedule
|
| 33 |
+
:members:
|
| 34 |
+
:undoc-members:
|
SimTranslation/code/unibert_waitk_0901_stack/docs/make.bat
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@ECHO OFF
|
| 2 |
+
|
| 3 |
+
pushd %~dp0
|
| 4 |
+
|
| 5 |
+
REM Command file for Sphinx documentation
|
| 6 |
+
|
| 7 |
+
if "%SPHINXBUILD%" == "" (
|
| 8 |
+
set SPHINXBUILD=python -msphinx
|
| 9 |
+
)
|
| 10 |
+
set SOURCEDIR=.
|
| 11 |
+
set BUILDDIR=_build
|
| 12 |
+
set SPHINXPROJ=fairseq
|
| 13 |
+
|
| 14 |
+
if "%1" == "" goto help
|
| 15 |
+
|
| 16 |
+
%SPHINXBUILD% >NUL 2>NUL
|
| 17 |
+
if errorlevel 9009 (
|
| 18 |
+
echo.
|
| 19 |
+
echo.The Sphinx module was not found. Make sure you have Sphinx installed,
|
| 20 |
+
echo.then set the SPHINXBUILD environment variable to point to the full
|
| 21 |
+
echo.path of the 'sphinx-build' executable. Alternatively you may add the
|
| 22 |
+
echo.Sphinx directory to PATH.
|
| 23 |
+
echo.
|
| 24 |
+
echo.If you don't have Sphinx installed, grab it from
|
| 25 |
+
echo.http://sphinx-doc.org/
|
| 26 |
+
exit /b 1
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
|
| 30 |
+
goto end
|
| 31 |
+
|
| 32 |
+
:help
|
| 33 |
+
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
|
| 34 |
+
|
| 35 |
+
:end
|
| 36 |
+
popd
|
SimTranslation/code/unibert_waitk_0901_stack/docs/models.rst
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. role:: hidden
|
| 2 |
+
:class: hidden-section
|
| 3 |
+
|
| 4 |
+
.. module:: fairseq.models
|
| 5 |
+
|
| 6 |
+
.. _Models:
|
| 7 |
+
|
| 8 |
+
Models
|
| 9 |
+
======
|
| 10 |
+
|
| 11 |
+
A Model defines the neural network's ``forward()`` method and encapsulates all
|
| 12 |
+
of the learnable parameters in the network. Each model also provides a set of
|
| 13 |
+
named *architectures* that define the precise network configuration (e.g.,
|
| 14 |
+
embedding dimension, number of layers, etc.).
|
| 15 |
+
|
| 16 |
+
Both the model type and architecture are selected via the ``--arch``
|
| 17 |
+
command-line argument. Once selected, a model may expose additional command-line
|
| 18 |
+
arguments for further configuration.
|
| 19 |
+
|
| 20 |
+
.. note::
|
| 21 |
+
|
| 22 |
+
All fairseq Models extend :class:`BaseFairseqModel`, which in turn extends
|
| 23 |
+
:class:`torch.nn.Module`. Thus any fairseq Model can be used as a
|
| 24 |
+
stand-alone Module in other PyTorch code.
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
Convolutional Neural Networks (CNN)
|
| 28 |
+
-----------------------------------
|
| 29 |
+
|
| 30 |
+
.. module:: fairseq.models.fconv
|
| 31 |
+
.. autoclass:: fairseq.models.fconv.FConvModel
|
| 32 |
+
:members:
|
| 33 |
+
.. autoclass:: fairseq.models.fconv.FConvEncoder
|
| 34 |
+
:members:
|
| 35 |
+
:undoc-members:
|
| 36 |
+
.. autoclass:: fairseq.models.fconv.FConvDecoder
|
| 37 |
+
:members:
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
Long Short-Term Memory (LSTM) networks
|
| 41 |
+
--------------------------------------
|
| 42 |
+
|
| 43 |
+
.. module:: fairseq.models.lstm
|
| 44 |
+
.. autoclass:: fairseq.models.lstm.LSTMModel
|
| 45 |
+
:members:
|
| 46 |
+
.. autoclass:: fairseq.models.lstm.LSTMEncoder
|
| 47 |
+
:members:
|
| 48 |
+
.. autoclass:: fairseq.models.lstm.LSTMDecoder
|
| 49 |
+
:members:
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
Transformer (self-attention) networks
|
| 53 |
+
-------------------------------------
|
| 54 |
+
|
| 55 |
+
.. module:: fairseq.models.transformer
|
| 56 |
+
.. autoclass:: fairseq.models.transformer.TransformerModel
|
| 57 |
+
:members:
|
| 58 |
+
.. autoclass:: fairseq.models.transformer.TransformerEncoder
|
| 59 |
+
:members:
|
| 60 |
+
.. autoclass:: fairseq.models.transformer.TransformerEncoderLayer
|
| 61 |
+
:members:
|
| 62 |
+
.. autoclass:: fairseq.models.transformer.TransformerDecoder
|
| 63 |
+
:members:
|
| 64 |
+
.. autoclass:: fairseq.models.transformer.TransformerDecoderLayer
|
| 65 |
+
:members:
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
Adding new models
|
| 69 |
+
-----------------
|
| 70 |
+
|
| 71 |
+
.. currentmodule:: fairseq.models
|
| 72 |
+
.. autofunction:: fairseq.models.register_model
|
| 73 |
+
.. autofunction:: fairseq.models.register_model_architecture
|
| 74 |
+
.. autoclass:: fairseq.models.BaseFairseqModel
|
| 75 |
+
:members:
|
| 76 |
+
:undoc-members:
|
| 77 |
+
.. autoclass:: fairseq.models.FairseqEncoderDecoderModel
|
| 78 |
+
:members:
|
| 79 |
+
:undoc-members:
|
| 80 |
+
.. autoclass:: fairseq.models.FairseqEncoderModel
|
| 81 |
+
:members:
|
| 82 |
+
:undoc-members:
|
| 83 |
+
.. autoclass:: fairseq.models.FairseqLanguageModel
|
| 84 |
+
:members:
|
| 85 |
+
:undoc-members:
|
| 86 |
+
.. autoclass:: fairseq.models.FairseqMultiModel
|
| 87 |
+
:members:
|
| 88 |
+
:undoc-members:
|
| 89 |
+
.. autoclass:: fairseq.models.FairseqEncoder
|
| 90 |
+
:members:
|
| 91 |
+
.. autoclass:: fairseq.models.CompositeEncoder
|
| 92 |
+
:members:
|
| 93 |
+
.. autoclass:: fairseq.models.FairseqDecoder
|
| 94 |
+
:members:
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
.. _Incremental decoding:
|
| 98 |
+
|
| 99 |
+
Incremental decoding
|
| 100 |
+
--------------------
|
| 101 |
+
|
| 102 |
+
.. autoclass:: fairseq.models.FairseqIncrementalDecoder
|
| 103 |
+
:members:
|
| 104 |
+
:undoc-members:
|
SimTranslation/code/unibert_waitk_0901_stack/docs/modules.rst
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Modules
|
| 2 |
+
=======
|
| 3 |
+
|
| 4 |
+
Fairseq provides several stand-alone :class:`torch.nn.Module` classes that may
|
| 5 |
+
be helpful when implementing a new :class:`~fairseq.models.BaseFairseqModel`.
|
| 6 |
+
|
| 7 |
+
.. automodule:: fairseq.modules
|
| 8 |
+
:members:
|
| 9 |
+
:undoc-members:
|
SimTranslation/code/unibert_waitk_0901_stack/docs/optim.rst
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. role:: hidden
|
| 2 |
+
:class: hidden-section
|
| 3 |
+
|
| 4 |
+
.. _optimizers:
|
| 5 |
+
|
| 6 |
+
Optimizers
|
| 7 |
+
==========
|
| 8 |
+
|
| 9 |
+
Optimizers update the Model parameters based on the gradients.
|
| 10 |
+
|
| 11 |
+
.. automodule:: fairseq.optim
|
| 12 |
+
:members:
|
| 13 |
+
|
| 14 |
+
.. autoclass:: fairseq.optim.FairseqOptimizer
|
| 15 |
+
:members:
|
| 16 |
+
:undoc-members:
|
| 17 |
+
|
| 18 |
+
.. autoclass:: fairseq.optim.adadelta.Adadelta
|
| 19 |
+
:members:
|
| 20 |
+
:undoc-members:
|
| 21 |
+
.. autoclass:: fairseq.optim.adagrad.Adagrad
|
| 22 |
+
:members:
|
| 23 |
+
:undoc-members:
|
| 24 |
+
.. autoclass:: fairseq.optim.adafactor.FairseqAdafactor
|
| 25 |
+
:members:
|
| 26 |
+
:undoc-members:
|
| 27 |
+
.. autoclass:: fairseq.optim.adam.FairseqAdam
|
| 28 |
+
:members:
|
| 29 |
+
:undoc-members:
|
| 30 |
+
.. autoclass:: fairseq.optim.fp16_optimizer.FP16Optimizer
|
| 31 |
+
:members:
|
| 32 |
+
:undoc-members:
|
| 33 |
+
.. autoclass:: fairseq.optim.nag.FairseqNAG
|
| 34 |
+
:members:
|
| 35 |
+
:undoc-members:
|
| 36 |
+
.. autoclass:: fairseq.optim.sgd.SGD
|
| 37 |
+
:members:
|
| 38 |
+
:undoc-members:
|
SimTranslation/code/unibert_waitk_0901_stack/docs/overview.rst
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Overview
|
| 2 |
+
========
|
| 3 |
+
|
| 4 |
+
Fairseq can be extended through user-supplied `plug-ins
|
| 5 |
+
<https://en.wikipedia.org/wiki/Plug-in_(computing)>`_. We support five kinds of
|
| 6 |
+
plug-ins:
|
| 7 |
+
|
| 8 |
+
- :ref:`Models` define the neural network architecture and encapsulate all of the
|
| 9 |
+
learnable parameters.
|
| 10 |
+
- :ref:`Criterions` compute the loss function given the model outputs and targets.
|
| 11 |
+
- :ref:`Tasks` store dictionaries and provide helpers for loading/iterating over
|
| 12 |
+
Datasets, initializing the Model/Criterion and calculating the loss.
|
| 13 |
+
- :ref:`Optimizers` update the Model parameters based on the gradients.
|
| 14 |
+
- :ref:`Learning Rate Schedulers` update the learning rate over the course of
|
| 15 |
+
training.
|
| 16 |
+
|
| 17 |
+
**Training Flow**
|
| 18 |
+
|
| 19 |
+
Given a ``model``, ``criterion``, ``task``, ``optimizer`` and ``lr_scheduler``,
|
| 20 |
+
fairseq implements the following high-level training flow::
|
| 21 |
+
|
| 22 |
+
for epoch in range(num_epochs):
|
| 23 |
+
itr = task.get_batch_iterator(task.dataset('train'))
|
| 24 |
+
for num_updates, batch in enumerate(itr):
|
| 25 |
+
task.train_step(batch, model, criterion, optimizer)
|
| 26 |
+
average_and_clip_gradients()
|
| 27 |
+
optimizer.step()
|
| 28 |
+
lr_scheduler.step_update(num_updates)
|
| 29 |
+
lr_scheduler.step(epoch)
|
| 30 |
+
|
| 31 |
+
where the default implementation for ``task.train_step`` is roughly::
|
| 32 |
+
|
| 33 |
+
def train_step(self, batch, model, criterion, optimizer, **unused):
|
| 34 |
+
loss = criterion(model, batch)
|
| 35 |
+
optimizer.backward(loss)
|
| 36 |
+
return loss
|
| 37 |
+
|
| 38 |
+
**Registering new plug-ins**
|
| 39 |
+
|
| 40 |
+
New plug-ins are *registered* through a set of ``@register`` function
|
| 41 |
+
decorators, for example::
|
| 42 |
+
|
| 43 |
+
@register_model('my_lstm')
|
| 44 |
+
class MyLSTM(FairseqEncoderDecoderModel):
|
| 45 |
+
(...)
|
| 46 |
+
|
| 47 |
+
Once registered, new plug-ins can be used with the existing :ref:`Command-line
|
| 48 |
+
Tools`. See the Tutorial sections for more detailed walkthroughs of how to add
|
| 49 |
+
new plug-ins.
|
| 50 |
+
|
| 51 |
+
**Loading plug-ins from another directory**
|
| 52 |
+
|
| 53 |
+
New plug-ins can be defined in a custom module stored in the user system. In
|
| 54 |
+
order to import the module, and make the plugin available to *fairseq*, the
|
| 55 |
+
command line supports the ``--user-dir`` flag that can be used to specify a
|
| 56 |
+
custom location for additional modules to load into *fairseq*.
|
| 57 |
+
|
| 58 |
+
For example, assuming this directory tree::
|
| 59 |
+
|
| 60 |
+
/home/user/my-module/
|
| 61 |
+
└── __init__.py
|
| 62 |
+
|
| 63 |
+
with ``__init__.py``::
|
| 64 |
+
|
| 65 |
+
from fairseq.models import register_model_architecture
|
| 66 |
+
from fairseq.models.transformer import transformer_vaswani_wmt_en_de_big
|
| 67 |
+
|
| 68 |
+
@register_model_architecture('transformer', 'my_transformer')
|
| 69 |
+
def transformer_mmt_big(args):
|
| 70 |
+
transformer_vaswani_wmt_en_de_big(args)
|
| 71 |
+
|
| 72 |
+
it is possible to invoke the :ref:`fairseq-train` script with the new architecture with::
|
| 73 |
+
|
| 74 |
+
fairseq-train ... --user-dir /home/user/my-module -a my_transformer --task translation
|
SimTranslation/code/unibert_waitk_0901_stack/docs/requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
sphinx<2.0
|
| 2 |
+
sphinx-argparse
|
SimTranslation/code/unibert_waitk_0901_stack/docs/tasks.rst
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. role:: hidden
|
| 2 |
+
:class: hidden-section
|
| 3 |
+
|
| 4 |
+
.. module:: fairseq.tasks
|
| 5 |
+
|
| 6 |
+
.. _Tasks:
|
| 7 |
+
|
| 8 |
+
Tasks
|
| 9 |
+
=====
|
| 10 |
+
|
| 11 |
+
Tasks store dictionaries and provide helpers for loading/iterating over
|
| 12 |
+
Datasets, initializing the Model/Criterion and calculating the loss.
|
| 13 |
+
|
| 14 |
+
Tasks can be selected via the ``--task`` command-line argument. Once selected, a
|
| 15 |
+
task may expose additional command-line arguments for further configuration.
|
| 16 |
+
|
| 17 |
+
Example usage::
|
| 18 |
+
|
| 19 |
+
# setup the task (e.g., load dictionaries)
|
| 20 |
+
task = fairseq.tasks.setup_task(args)
|
| 21 |
+
|
| 22 |
+
# build model and criterion
|
| 23 |
+
model = task.build_model(args)
|
| 24 |
+
criterion = task.build_criterion(args)
|
| 25 |
+
|
| 26 |
+
# load datasets
|
| 27 |
+
task.load_dataset('train')
|
| 28 |
+
task.load_dataset('valid')
|
| 29 |
+
|
| 30 |
+
# iterate over mini-batches of data
|
| 31 |
+
batch_itr = task.get_batch_iterator(
|
| 32 |
+
task.dataset('train'), max_tokens=4096,
|
| 33 |
+
)
|
| 34 |
+
for batch in batch_itr:
|
| 35 |
+
# compute the loss
|
| 36 |
+
loss, sample_size, logging_output = task.get_loss(
|
| 37 |
+
model, criterion, batch,
|
| 38 |
+
)
|
| 39 |
+
loss.backward()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
Translation
|
| 43 |
+
-----------
|
| 44 |
+
|
| 45 |
+
.. autoclass:: fairseq.tasks.translation.TranslationTask
|
| 46 |
+
|
| 47 |
+
.. _language modeling:
|
| 48 |
+
|
| 49 |
+
Language Modeling
|
| 50 |
+
-----------------
|
| 51 |
+
|
| 52 |
+
.. autoclass:: fairseq.tasks.language_modeling.LanguageModelingTask
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
Adding new tasks
|
| 56 |
+
----------------
|
| 57 |
+
|
| 58 |
+
.. autofunction:: fairseq.tasks.register_task
|
| 59 |
+
.. autoclass:: fairseq.tasks.FairseqTask
|
| 60 |
+
:members:
|
| 61 |
+
:undoc-members:
|
SimTranslation/code/unibert_waitk_0901_stack/docs/tutorial_classifying_names.rst
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Tutorial: Classifying Names with a Character-Level RNN
|
| 2 |
+
======================================================
|
| 3 |
+
|
| 4 |
+
In this tutorial we will extend fairseq to support *classification* tasks. In
|
| 5 |
+
particular we will re-implement the PyTorch tutorial for `Classifying Names with
|
| 6 |
+
a Character-Level RNN <https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html>`_
|
| 7 |
+
in fairseq. It is recommended to quickly skim that tutorial before beginning
|
| 8 |
+
this one.
|
| 9 |
+
|
| 10 |
+
This tutorial covers:
|
| 11 |
+
|
| 12 |
+
1. **Preprocessing the data** to create dictionaries.
|
| 13 |
+
2. **Registering a new Model** that encodes an input sentence with a simple RNN
|
| 14 |
+
and predicts the output label.
|
| 15 |
+
3. **Registering a new Task** that loads our dictionaries and dataset.
|
| 16 |
+
4. **Training the Model** using the existing command-line tools.
|
| 17 |
+
5. **Writing an evaluation script** that imports fairseq and allows us to
|
| 18 |
+
interactively evaluate our model on new inputs.
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
1. Preprocessing the data
|
| 22 |
+
-------------------------
|
| 23 |
+
|
| 24 |
+
The original tutorial provides raw data, but we'll work with a modified version
|
| 25 |
+
of the data that is already tokenized into characters and split into separate
|
| 26 |
+
train, valid and test sets.
|
| 27 |
+
|
| 28 |
+
Download and extract the data from here:
|
| 29 |
+
`tutorial_names.tar.gz <https://dl.fbaipublicfiles.com/fairseq/data/tutorial_names.tar.gz>`_
|
| 30 |
+
|
| 31 |
+
Once extracted, let's preprocess the data using the :ref:`fairseq-preprocess`
|
| 32 |
+
command-line tool to create the dictionaries. While this tool is primarily
|
| 33 |
+
intended for sequence-to-sequence problems, we're able to reuse it here by
|
| 34 |
+
treating the label as a "target" sequence of length 1. We'll also output the
|
| 35 |
+
preprocessed files in "raw" format using the ``--dataset-impl`` option to
|
| 36 |
+
enhance readability:
|
| 37 |
+
|
| 38 |
+
.. code-block:: console
|
| 39 |
+
|
| 40 |
+
> fairseq-preprocess \
|
| 41 |
+
--trainpref names/train --validpref names/valid --testpref names/test \
|
| 42 |
+
--source-lang input --target-lang label \
|
| 43 |
+
--destdir names-bin --dataset-impl raw
|
| 44 |
+
|
| 45 |
+
After running the above command you should see a new directory,
|
| 46 |
+
:file:`names-bin/`, containing the dictionaries for *inputs* and *labels*.
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
2. Registering a new Model
|
| 50 |
+
--------------------------
|
| 51 |
+
|
| 52 |
+
Next we'll register a new model in fairseq that will encode an input sentence
|
| 53 |
+
with a simple RNN and predict the output label. Compared to the original PyTorch
|
| 54 |
+
tutorial, our version will also work with batches of data and GPU Tensors.
|
| 55 |
+
|
| 56 |
+
First let's copy the simple RNN module implemented in the `PyTorch tutorial
|
| 57 |
+
<https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html#creating-the-network>`_.
|
| 58 |
+
Create a new file named :file:`fairseq/models/rnn_classifier.py` with the
|
| 59 |
+
following contents::
|
| 60 |
+
|
| 61 |
+
import torch
|
| 62 |
+
import torch.nn as nn
|
| 63 |
+
|
| 64 |
+
class RNN(nn.Module):
|
| 65 |
+
|
| 66 |
+
def __init__(self, input_size, hidden_size, output_size):
|
| 67 |
+
super(RNN, self).__init__()
|
| 68 |
+
|
| 69 |
+
self.hidden_size = hidden_size
|
| 70 |
+
|
| 71 |
+
self.i2h = nn.Linear(input_size + hidden_size, hidden_size)
|
| 72 |
+
self.i2o = nn.Linear(input_size + hidden_size, output_size)
|
| 73 |
+
self.softmax = nn.LogSoftmax(dim=1)
|
| 74 |
+
|
| 75 |
+
def forward(self, input, hidden):
|
| 76 |
+
combined = torch.cat((input, hidden), 1)
|
| 77 |
+
hidden = self.i2h(combined)
|
| 78 |
+
output = self.i2o(combined)
|
| 79 |
+
output = self.softmax(output)
|
| 80 |
+
return output, hidden
|
| 81 |
+
|
| 82 |
+
def initHidden(self):
|
| 83 |
+
return torch.zeros(1, self.hidden_size)
|
| 84 |
+
|
| 85 |
+
We must also *register* this model with fairseq using the
|
| 86 |
+
:func:`~fairseq.models.register_model` function decorator. Once the model is
|
| 87 |
+
registered we'll be able to use it with the existing :ref:`Command-line Tools`.
|
| 88 |
+
|
| 89 |
+
All registered models must implement the :class:`~fairseq.models.BaseFairseqModel`
|
| 90 |
+
interface, so we'll create a small wrapper class in the same file and register
|
| 91 |
+
it in fairseq with the name ``'rnn_classifier'``::
|
| 92 |
+
|
| 93 |
+
from fairseq.models import BaseFairseqModel, register_model
|
| 94 |
+
|
| 95 |
+
# Note: the register_model "decorator" should immediately precede the
|
| 96 |
+
# definition of the Model class.
|
| 97 |
+
|
| 98 |
+
@register_model('rnn_classifier')
|
| 99 |
+
class FairseqRNNClassifier(BaseFairseqModel):
|
| 100 |
+
|
| 101 |
+
@staticmethod
|
| 102 |
+
def add_args(parser):
|
| 103 |
+
# Models can override this method to add new command-line arguments.
|
| 104 |
+
# Here we'll add a new command-line argument to configure the
|
| 105 |
+
# dimensionality of the hidden state.
|
| 106 |
+
parser.add_argument(
|
| 107 |
+
'--hidden-dim', type=int, metavar='N',
|
| 108 |
+
help='dimensionality of the hidden state',
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
@classmethod
|
| 112 |
+
def build_model(cls, args, task):
|
| 113 |
+
# Fairseq initializes models by calling the ``build_model()``
|
| 114 |
+
# function. This provides more flexibility, since the returned model
|
| 115 |
+
# instance can be of a different type than the one that was called.
|
| 116 |
+
# In this case we'll just return a FairseqRNNClassifier instance.
|
| 117 |
+
|
| 118 |
+
# Initialize our RNN module
|
| 119 |
+
rnn = RNN(
|
| 120 |
+
# We'll define the Task in the next section, but for now just
|
| 121 |
+
# notice that the task holds the dictionaries for the "source"
|
| 122 |
+
# (i.e., the input sentence) and "target" (i.e., the label).
|
| 123 |
+
input_size=len(task.source_dictionary),
|
| 124 |
+
hidden_size=args.hidden_dim,
|
| 125 |
+
output_size=len(task.target_dictionary),
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
# Return the wrapped version of the module
|
| 129 |
+
return FairseqRNNClassifier(
|
| 130 |
+
rnn=rnn,
|
| 131 |
+
input_vocab=task.source_dictionary,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
def __init__(self, rnn, input_vocab):
|
| 135 |
+
super(FairseqRNNClassifier, self).__init__()
|
| 136 |
+
|
| 137 |
+
self.rnn = rnn
|
| 138 |
+
self.input_vocab = input_vocab
|
| 139 |
+
|
| 140 |
+
# The RNN module in the tutorial expects one-hot inputs, so we can
|
| 141 |
+
# precompute the identity matrix to help convert from indices to
|
| 142 |
+
# one-hot vectors. We register it as a buffer so that it is moved to
|
| 143 |
+
# the GPU when ``cuda()`` is called.
|
| 144 |
+
self.register_buffer('one_hot_inputs', torch.eye(len(input_vocab)))
|
| 145 |
+
|
| 146 |
+
def forward(self, src_tokens, src_lengths):
|
| 147 |
+
# The inputs to the ``forward()`` function are determined by the
|
| 148 |
+
# Task, and in particular the ``'net_input'`` key in each
|
| 149 |
+
# mini-batch. We'll define the Task in the next section, but for
|
| 150 |
+
# now just know that *src_tokens* has shape `(batch, src_len)` and
|
| 151 |
+
# *src_lengths* has shape `(batch)`.
|
| 152 |
+
bsz, max_src_len = src_tokens.size()
|
| 153 |
+
|
| 154 |
+
# Initialize the RNN hidden state. Compared to the original PyTorch
|
| 155 |
+
# tutorial we'll also handle batched inputs and work on the GPU.
|
| 156 |
+
hidden = self.rnn.initHidden()
|
| 157 |
+
hidden = hidden.repeat(bsz, 1) # expand for batched inputs
|
| 158 |
+
hidden = hidden.to(src_tokens.device) # move to GPU
|
| 159 |
+
|
| 160 |
+
for i in range(max_src_len):
|
| 161 |
+
# WARNING: The inputs have padding, so we should mask those
|
| 162 |
+
# elements here so that padding doesn't affect the results.
|
| 163 |
+
# This is left as an exercise for the reader. The padding symbol
|
| 164 |
+
# is given by ``self.input_vocab.pad()`` and the unpadded length
|
| 165 |
+
# of each input is given by *src_lengths*.
|
| 166 |
+
|
| 167 |
+
# One-hot encode a batch of input characters.
|
| 168 |
+
input = self.one_hot_inputs[src_tokens[:, i].long()]
|
| 169 |
+
|
| 170 |
+
# Feed the input to our RNN.
|
| 171 |
+
output, hidden = self.rnn(input, hidden)
|
| 172 |
+
|
| 173 |
+
# Return the final output state for making a prediction
|
| 174 |
+
return output
|
| 175 |
+
|
| 176 |
+
Finally let's define a *named architecture* with the configuration for our
|
| 177 |
+
model. This is done with the :func:`~fairseq.models.register_model_architecture`
|
| 178 |
+
function decorator. Thereafter this named architecture can be used with the
|
| 179 |
+
``--arch`` command-line argument, e.g., ``--arch pytorch_tutorial_rnn``::
|
| 180 |
+
|
| 181 |
+
from fairseq.models import register_model_architecture
|
| 182 |
+
|
| 183 |
+
# The first argument to ``register_model_architecture()`` should be the name
|
| 184 |
+
# of the model we registered above (i.e., 'rnn_classifier'). The function we
|
| 185 |
+
# register here should take a single argument *args* and modify it in-place
|
| 186 |
+
# to match the desired architecture.
|
| 187 |
+
|
| 188 |
+
@register_model_architecture('rnn_classifier', 'pytorch_tutorial_rnn')
|
| 189 |
+
def pytorch_tutorial_rnn(args):
|
| 190 |
+
# We use ``getattr()`` to prioritize arguments that are explicitly given
|
| 191 |
+
# on the command-line, so that the defaults defined below are only used
|
| 192 |
+
# when no other value has been specified.
|
| 193 |
+
args.hidden_dim = getattr(args, 'hidden_dim', 128)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
3. Registering a new Task
|
| 197 |
+
-------------------------
|
| 198 |
+
|
| 199 |
+
Now we'll register a new :class:`~fairseq.tasks.FairseqTask` that will load our
|
| 200 |
+
dictionaries and dataset. Tasks can also control how the data is batched into
|
| 201 |
+
mini-batches, but in this tutorial we'll reuse the batching provided by
|
| 202 |
+
:class:`fairseq.data.LanguagePairDataset`.
|
| 203 |
+
|
| 204 |
+
Create a new file named :file:`fairseq/tasks/simple_classification.py` with the
|
| 205 |
+
following contents::
|
| 206 |
+
|
| 207 |
+
import os
|
| 208 |
+
import torch
|
| 209 |
+
|
| 210 |
+
from fairseq.data import Dictionary, LanguagePairDataset
|
| 211 |
+
from fairseq.tasks import FairseqTask, register_task
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
@register_task('simple_classification')
|
| 215 |
+
class SimpleClassificationTask(FairseqTask):
|
| 216 |
+
|
| 217 |
+
@staticmethod
|
| 218 |
+
def add_args(parser):
|
| 219 |
+
# Add some command-line arguments for specifying where the data is
|
| 220 |
+
# located and the maximum supported input length.
|
| 221 |
+
parser.add_argument('data', metavar='FILE',
|
| 222 |
+
help='file prefix for data')
|
| 223 |
+
parser.add_argument('--max-positions', default=1024, type=int,
|
| 224 |
+
help='max input length')
|
| 225 |
+
|
| 226 |
+
@classmethod
|
| 227 |
+
def setup_task(cls, args, **kwargs):
|
| 228 |
+
# Here we can perform any setup required for the task. This may include
|
| 229 |
+
# loading Dictionaries, initializing shared Embedding layers, etc.
|
| 230 |
+
# In this case we'll just load the Dictionaries.
|
| 231 |
+
input_vocab = Dictionary.load(os.path.join(args.data, 'dict.input.txt'))
|
| 232 |
+
label_vocab = Dictionary.load(os.path.join(args.data, 'dict.label.txt'))
|
| 233 |
+
print('| [input] dictionary: {} types'.format(len(input_vocab)))
|
| 234 |
+
print('| [label] dictionary: {} types'.format(len(label_vocab)))
|
| 235 |
+
|
| 236 |
+
return SimpleClassificationTask(args, input_vocab, label_vocab)
|
| 237 |
+
|
| 238 |
+
def __init__(self, args, input_vocab, label_vocab):
|
| 239 |
+
super().__init__(args)
|
| 240 |
+
self.input_vocab = input_vocab
|
| 241 |
+
self.label_vocab = label_vocab
|
| 242 |
+
|
| 243 |
+
def load_dataset(self, split, **kwargs):
|
| 244 |
+
"""Load a given dataset split (e.g., train, valid, test)."""
|
| 245 |
+
|
| 246 |
+
prefix = os.path.join(self.args.data, '{}.input-label'.format(split))
|
| 247 |
+
|
| 248 |
+
# Read input sentences.
|
| 249 |
+
sentences, lengths = [], []
|
| 250 |
+
with open(prefix + '.input', encoding='utf-8') as file:
|
| 251 |
+
for line in file:
|
| 252 |
+
sentence = line.strip()
|
| 253 |
+
|
| 254 |
+
# Tokenize the sentence, splitting on spaces
|
| 255 |
+
tokens = self.input_vocab.encode_line(
|
| 256 |
+
sentence, add_if_not_exist=False,
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
sentences.append(tokens)
|
| 260 |
+
lengths.append(tokens.numel())
|
| 261 |
+
|
| 262 |
+
# Read labels.
|
| 263 |
+
labels = []
|
| 264 |
+
with open(prefix + '.label', encoding='utf-8') as file:
|
| 265 |
+
for line in file:
|
| 266 |
+
label = line.strip()
|
| 267 |
+
labels.append(
|
| 268 |
+
# Convert label to a numeric ID.
|
| 269 |
+
torch.LongTensor([self.label_vocab.add_symbol(label)])
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
assert len(sentences) == len(labels)
|
| 273 |
+
print('| {} {} {} examples'.format(self.args.data, split, len(sentences)))
|
| 274 |
+
|
| 275 |
+
# We reuse LanguagePairDataset since classification can be modeled as a
|
| 276 |
+
# sequence-to-sequence task where the target sequence has length 1.
|
| 277 |
+
self.datasets[split] = LanguagePairDataset(
|
| 278 |
+
src=sentences,
|
| 279 |
+
src_sizes=lengths,
|
| 280 |
+
src_dict=self.input_vocab,
|
| 281 |
+
tgt=labels,
|
| 282 |
+
tgt_sizes=torch.ones(len(labels)), # targets have length 1
|
| 283 |
+
tgt_dict=self.label_vocab,
|
| 284 |
+
left_pad_source=False,
|
| 285 |
+
max_source_positions=self.args.max_positions,
|
| 286 |
+
max_target_positions=1,
|
| 287 |
+
# Since our target is a single class label, there's no need for
|
| 288 |
+
# teacher forcing. If we set this to ``True`` then our Model's
|
| 289 |
+
# ``forward()`` method would receive an additional argument called
|
| 290 |
+
# *prev_output_tokens* that would contain a shifted version of the
|
| 291 |
+
# target sequence.
|
| 292 |
+
input_feeding=False,
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
def max_positions(self):
|
| 296 |
+
"""Return the max input length allowed by the task."""
|
| 297 |
+
# The source should be less than *args.max_positions* and the "target"
|
| 298 |
+
# has max length 1.
|
| 299 |
+
return (self.args.max_positions, 1)
|
| 300 |
+
|
| 301 |
+
@property
|
| 302 |
+
def source_dictionary(self):
|
| 303 |
+
"""Return the source :class:`~fairseq.data.Dictionary`."""
|
| 304 |
+
return self.input_vocab
|
| 305 |
+
|
| 306 |
+
@property
|
| 307 |
+
def target_dictionary(self):
|
| 308 |
+
"""Return the target :class:`~fairseq.data.Dictionary`."""
|
| 309 |
+
return self.label_vocab
|
| 310 |
+
|
| 311 |
+
# We could override this method if we wanted more control over how batches
|
| 312 |
+
# are constructed, but it's not necessary for this tutorial since we can
|
| 313 |
+
# reuse the batching provided by LanguagePairDataset.
|
| 314 |
+
#
|
| 315 |
+
# def get_batch_iterator(
|
| 316 |
+
# self, dataset, max_tokens=None, max_sentences=None, max_positions=None,
|
| 317 |
+
# ignore_invalid_inputs=False, required_batch_size_multiple=1,
|
| 318 |
+
# seed=1, num_shards=1, shard_id=0,
|
| 319 |
+
# ):
|
| 320 |
+
# (...)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
4. Training the Model
|
| 324 |
+
---------------------
|
| 325 |
+
|
| 326 |
+
Now we're ready to train the model. We can use the existing :ref:`fairseq-train`
|
| 327 |
+
command-line tool for this, making sure to specify our new Task (``--task
|
| 328 |
+
simple_classification``) and Model architecture (``--arch
|
| 329 |
+
pytorch_tutorial_rnn``):
|
| 330 |
+
|
| 331 |
+
.. note::
|
| 332 |
+
|
| 333 |
+
You can also configure the dimensionality of the hidden state by passing the
|
| 334 |
+
``--hidden-dim`` argument to :ref:`fairseq-train`.
|
| 335 |
+
|
| 336 |
+
.. code-block:: console
|
| 337 |
+
|
| 338 |
+
> fairseq-train names-bin \
|
| 339 |
+
--task simple_classification \
|
| 340 |
+
--arch pytorch_tutorial_rnn \
|
| 341 |
+
--optimizer adam --lr 0.001 --lr-shrink 0.5 \
|
| 342 |
+
--max-tokens 1000
|
| 343 |
+
(...)
|
| 344 |
+
| epoch 027 | loss 1.200 | ppl 2.30 | wps 15728 | ups 119.4 | wpb 116 | bsz 116 | num_updates 3726 | lr 1.5625e-05 | gnorm 1.290 | clip 0% | oom 0 | wall 32 | train_wall 21
|
| 345 |
+
| epoch 027 | valid on 'valid' subset | valid_loss 1.41304 | valid_ppl 2.66 | num_updates 3726 | best 1.41208
|
| 346 |
+
| done training in 31.6 seconds
|
| 347 |
+
|
| 348 |
+
The model files should appear in the :file:`checkpoints/` directory.
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
5. Writing an evaluation script
|
| 352 |
+
-------------------------------
|
| 353 |
+
|
| 354 |
+
Finally we can write a short script to evaluate our model on new inputs. Create
|
| 355 |
+
a new file named :file:`eval_classifier.py` with the following contents::
|
| 356 |
+
|
| 357 |
+
from fairseq import checkpoint_utils, data, options, tasks
|
| 358 |
+
|
| 359 |
+
# Parse command-line arguments for generation
|
| 360 |
+
parser = options.get_generation_parser(default_task='simple_classification')
|
| 361 |
+
args = options.parse_args_and_arch(parser)
|
| 362 |
+
|
| 363 |
+
# Setup task
|
| 364 |
+
task = tasks.setup_task(args)
|
| 365 |
+
|
| 366 |
+
# Load model
|
| 367 |
+
print('| loading model from {}'.format(args.path))
|
| 368 |
+
models, _model_args = checkpoint_utils.load_model_ensemble([args.path], task=task)
|
| 369 |
+
model = models[0]
|
| 370 |
+
|
| 371 |
+
while True:
|
| 372 |
+
sentence = input('\nInput: ')
|
| 373 |
+
|
| 374 |
+
# Tokenize into characters
|
| 375 |
+
chars = ' '.join(list(sentence.strip()))
|
| 376 |
+
tokens = task.source_dictionary.encode_line(
|
| 377 |
+
chars, add_if_not_exist=False,
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
# Build mini-batch to feed to the model
|
| 381 |
+
batch = data.language_pair_dataset.collate(
|
| 382 |
+
samples=[{'id': -1, 'source': tokens}], # bsz = 1
|
| 383 |
+
pad_idx=task.source_dictionary.pad(),
|
| 384 |
+
eos_idx=task.source_dictionary.eos(),
|
| 385 |
+
left_pad_source=False,
|
| 386 |
+
input_feeding=False,
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
# Feed batch to the model and get predictions
|
| 390 |
+
preds = model(**batch['net_input'])
|
| 391 |
+
|
| 392 |
+
# Print top 3 predictions and their log-probabilities
|
| 393 |
+
top_scores, top_labels = preds[0].topk(k=3)
|
| 394 |
+
for score, label_idx in zip(top_scores, top_labels):
|
| 395 |
+
label_name = task.target_dictionary.string([label_idx])
|
| 396 |
+
print('({:.2f})\t{}'.format(score, label_name))
|
| 397 |
+
|
| 398 |
+
Now we can evaluate our model interactively. Note that we have included the
|
| 399 |
+
original data path (:file:`names-bin/`) so that the dictionaries can be loaded:
|
| 400 |
+
|
| 401 |
+
.. code-block:: console
|
| 402 |
+
|
| 403 |
+
> python eval_classifier.py names-bin --path checkpoints/checkpoint_best.pt
|
| 404 |
+
| [input] dictionary: 64 types
|
| 405 |
+
| [label] dictionary: 24 types
|
| 406 |
+
| loading model from checkpoints/checkpoint_best.pt
|
| 407 |
+
|
| 408 |
+
Input: Satoshi
|
| 409 |
+
(-0.61) Japanese
|
| 410 |
+
(-1.20) Arabic
|
| 411 |
+
(-2.86) Italian
|
| 412 |
+
|
| 413 |
+
Input: Sinbad
|
| 414 |
+
(-0.30) Arabic
|
| 415 |
+
(-1.76) English
|
| 416 |
+
(-4.08) Russian
|
SimTranslation/code/unibert_waitk_0901_stack/docs/tutorial_simple_lstm.rst
ADDED
|
@@ -0,0 +1,517 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Tutorial: Simple LSTM
|
| 2 |
+
=====================
|
| 3 |
+
|
| 4 |
+
In this tutorial we will extend fairseq by adding a new
|
| 5 |
+
:class:`~fairseq.models.FairseqEncoderDecoderModel` that encodes a source
|
| 6 |
+
sentence with an LSTM and then passes the final hidden state to a second LSTM
|
| 7 |
+
that decodes the target sentence (without attention).
|
| 8 |
+
|
| 9 |
+
This tutorial covers:
|
| 10 |
+
|
| 11 |
+
1. **Writing an Encoder and Decoder** to encode/decode the source/target
|
| 12 |
+
sentence, respectively.
|
| 13 |
+
2. **Registering a new Model** so that it can be used with the existing
|
| 14 |
+
:ref:`Command-line tools`.
|
| 15 |
+
3. **Training the Model** using the existing command-line tools.
|
| 16 |
+
4. **Making generation faster** by modifying the Decoder to use
|
| 17 |
+
:ref:`Incremental decoding`.
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
1. Building an Encoder and Decoder
|
| 21 |
+
----------------------------------
|
| 22 |
+
|
| 23 |
+
In this section we'll define a simple LSTM Encoder and Decoder. All Encoders
|
| 24 |
+
should implement the :class:`~fairseq.models.FairseqEncoder` interface and
|
| 25 |
+
Decoders should implement the :class:`~fairseq.models.FairseqDecoder` interface.
|
| 26 |
+
These interfaces themselves extend :class:`torch.nn.Module`, so FairseqEncoders
|
| 27 |
+
and FairseqDecoders can be written and used in the same ways as ordinary PyTorch
|
| 28 |
+
Modules.
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
Encoder
|
| 32 |
+
~~~~~~~
|
| 33 |
+
|
| 34 |
+
Our Encoder will embed the tokens in the source sentence, feed them to a
|
| 35 |
+
:class:`torch.nn.LSTM` and return the final hidden state. To create our encoder
|
| 36 |
+
save the following in a new file named :file:`fairseq/models/simple_lstm.py`::
|
| 37 |
+
|
| 38 |
+
import torch.nn as nn
|
| 39 |
+
from fairseq import utils
|
| 40 |
+
from fairseq.models import FairseqEncoder
|
| 41 |
+
|
| 42 |
+
class SimpleLSTMEncoder(FairseqEncoder):
|
| 43 |
+
|
| 44 |
+
def __init__(
|
| 45 |
+
self, args, dictionary, embed_dim=128, hidden_dim=128, dropout=0.1,
|
| 46 |
+
):
|
| 47 |
+
super().__init__(dictionary)
|
| 48 |
+
self.args = args
|
| 49 |
+
|
| 50 |
+
# Our encoder will embed the inputs before feeding them to the LSTM.
|
| 51 |
+
self.embed_tokens = nn.Embedding(
|
| 52 |
+
num_embeddings=len(dictionary),
|
| 53 |
+
embedding_dim=embed_dim,
|
| 54 |
+
padding_idx=dictionary.pad(),
|
| 55 |
+
)
|
| 56 |
+
self.dropout = nn.Dropout(p=dropout)
|
| 57 |
+
|
| 58 |
+
# We'll use a single-layer, unidirectional LSTM for simplicity.
|
| 59 |
+
self.lstm = nn.LSTM(
|
| 60 |
+
input_size=embed_dim,
|
| 61 |
+
hidden_size=hidden_dim,
|
| 62 |
+
num_layers=1,
|
| 63 |
+
bidirectional=False,
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
def forward(self, src_tokens, src_lengths):
|
| 67 |
+
# The inputs to the ``forward()`` function are determined by the
|
| 68 |
+
# Task, and in particular the ``'net_input'`` key in each
|
| 69 |
+
# mini-batch. We discuss Tasks in the next tutorial, but for now just
|
| 70 |
+
# know that *src_tokens* has shape `(batch, src_len)` and *src_lengths*
|
| 71 |
+
# has shape `(batch)`.
|
| 72 |
+
|
| 73 |
+
# Note that the source is typically padded on the left. This can be
|
| 74 |
+
# configured by adding the `--left-pad-source "False"` command-line
|
| 75 |
+
# argument, but here we'll make the Encoder handle either kind of
|
| 76 |
+
# padding by converting everything to be right-padded.
|
| 77 |
+
if self.args.left_pad_source:
|
| 78 |
+
# Convert left-padding to right-padding.
|
| 79 |
+
src_tokens = utils.convert_padding_direction(
|
| 80 |
+
src_tokens,
|
| 81 |
+
padding_idx=self.dictionary.pad(),
|
| 82 |
+
left_to_right=True
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
# Embed the source.
|
| 86 |
+
x = self.embed_tokens(src_tokens)
|
| 87 |
+
|
| 88 |
+
# Apply dropout.
|
| 89 |
+
x = self.dropout(x)
|
| 90 |
+
|
| 91 |
+
# Pack the sequence into a PackedSequence object to feed to the LSTM.
|
| 92 |
+
x = nn.utils.rnn.pack_padded_sequence(x, src_lengths, batch_first=True)
|
| 93 |
+
|
| 94 |
+
# Get the output from the LSTM.
|
| 95 |
+
_outputs, (final_hidden, _final_cell) = self.lstm(x)
|
| 96 |
+
|
| 97 |
+
# Return the Encoder's output. This can be any object and will be
|
| 98 |
+
# passed directly to the Decoder.
|
| 99 |
+
return {
|
| 100 |
+
# this will have shape `(bsz, hidden_dim)`
|
| 101 |
+
'final_hidden': final_hidden.squeeze(0),
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
# Encoders are required to implement this method so that we can rearrange
|
| 105 |
+
# the order of the batch elements during inference (e.g., beam search).
|
| 106 |
+
def reorder_encoder_out(self, encoder_out, new_order):
|
| 107 |
+
"""
|
| 108 |
+
Reorder encoder output according to `new_order`.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
encoder_out: output from the ``forward()`` method
|
| 112 |
+
new_order (LongTensor): desired order
|
| 113 |
+
|
| 114 |
+
Returns:
|
| 115 |
+
`encoder_out` rearranged according to `new_order`
|
| 116 |
+
"""
|
| 117 |
+
final_hidden = encoder_out['final_hidden']
|
| 118 |
+
return {
|
| 119 |
+
'final_hidden': final_hidden.index_select(0, new_order),
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
Decoder
|
| 124 |
+
~~~~~~~
|
| 125 |
+
|
| 126 |
+
Our Decoder will predict the next word, conditioned on the Encoder's final
|
| 127 |
+
hidden state and an embedded representation of the previous target word -- which
|
| 128 |
+
is sometimes called *teacher forcing*. More specifically, we'll use a
|
| 129 |
+
:class:`torch.nn.LSTM` to produce a sequence of hidden states that we'll project
|
| 130 |
+
to the size of the output vocabulary to predict each target word.
|
| 131 |
+
|
| 132 |
+
::
|
| 133 |
+
|
| 134 |
+
import torch
|
| 135 |
+
from fairseq.models import FairseqDecoder
|
| 136 |
+
|
| 137 |
+
class SimpleLSTMDecoder(FairseqDecoder):
|
| 138 |
+
|
| 139 |
+
def __init__(
|
| 140 |
+
self, dictionary, encoder_hidden_dim=128, embed_dim=128, hidden_dim=128,
|
| 141 |
+
dropout=0.1,
|
| 142 |
+
):
|
| 143 |
+
super().__init__(dictionary)
|
| 144 |
+
|
| 145 |
+
# Our decoder will embed the inputs before feeding them to the LSTM.
|
| 146 |
+
self.embed_tokens = nn.Embedding(
|
| 147 |
+
num_embeddings=len(dictionary),
|
| 148 |
+
embedding_dim=embed_dim,
|
| 149 |
+
padding_idx=dictionary.pad(),
|
| 150 |
+
)
|
| 151 |
+
self.dropout = nn.Dropout(p=dropout)
|
| 152 |
+
|
| 153 |
+
# We'll use a single-layer, unidirectional LSTM for simplicity.
|
| 154 |
+
self.lstm = nn.LSTM(
|
| 155 |
+
# For the first layer we'll concatenate the Encoder's final hidden
|
| 156 |
+
# state with the embedded target tokens.
|
| 157 |
+
input_size=encoder_hidden_dim + embed_dim,
|
| 158 |
+
hidden_size=hidden_dim,
|
| 159 |
+
num_layers=1,
|
| 160 |
+
bidirectional=False,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
# Define the output projection.
|
| 164 |
+
self.output_projection = nn.Linear(hidden_dim, len(dictionary))
|
| 165 |
+
|
| 166 |
+
# During training Decoders are expected to take the entire target sequence
|
| 167 |
+
# (shifted right by one position) and produce logits over the vocabulary.
|
| 168 |
+
# The *prev_output_tokens* tensor begins with the end-of-sentence symbol,
|
| 169 |
+
# ``dictionary.eos()``, followed by the target sequence.
|
| 170 |
+
def forward(self, prev_output_tokens, encoder_out):
|
| 171 |
+
"""
|
| 172 |
+
Args:
|
| 173 |
+
prev_output_tokens (LongTensor): previous decoder outputs of shape
|
| 174 |
+
`(batch, tgt_len)`, for teacher forcing
|
| 175 |
+
encoder_out (Tensor, optional): output from the encoder, used for
|
| 176 |
+
encoder-side attention
|
| 177 |
+
|
| 178 |
+
Returns:
|
| 179 |
+
tuple:
|
| 180 |
+
- the last decoder layer's output of shape
|
| 181 |
+
`(batch, tgt_len, vocab)`
|
| 182 |
+
- the last decoder layer's attention weights of shape
|
| 183 |
+
`(batch, tgt_len, src_len)`
|
| 184 |
+
"""
|
| 185 |
+
bsz, tgt_len = prev_output_tokens.size()
|
| 186 |
+
|
| 187 |
+
# Extract the final hidden state from the Encoder.
|
| 188 |
+
final_encoder_hidden = encoder_out['final_hidden']
|
| 189 |
+
|
| 190 |
+
# Embed the target sequence, which has been shifted right by one
|
| 191 |
+
# position and now starts with the end-of-sentence symbol.
|
| 192 |
+
x = self.embed_tokens(prev_output_tokens)
|
| 193 |
+
|
| 194 |
+
# Apply dropout.
|
| 195 |
+
x = self.dropout(x)
|
| 196 |
+
|
| 197 |
+
# Concatenate the Encoder's final hidden state to *every* embedded
|
| 198 |
+
# target token.
|
| 199 |
+
x = torch.cat(
|
| 200 |
+
[x, final_encoder_hidden.unsqueeze(1).expand(bsz, tgt_len, -1)],
|
| 201 |
+
dim=2,
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
# Using PackedSequence objects in the Decoder is harder than in the
|
| 205 |
+
# Encoder, since the targets are not sorted in descending length order,
|
| 206 |
+
# which is a requirement of ``pack_padded_sequence()``. Instead we'll
|
| 207 |
+
# feed nn.LSTM directly.
|
| 208 |
+
initial_state = (
|
| 209 |
+
final_encoder_hidden.unsqueeze(0), # hidden
|
| 210 |
+
torch.zeros_like(final_encoder_hidden).unsqueeze(0), # cell
|
| 211 |
+
)
|
| 212 |
+
output, _ = self.lstm(
|
| 213 |
+
x.transpose(0, 1), # convert to shape `(tgt_len, bsz, dim)`
|
| 214 |
+
initial_state,
|
| 215 |
+
)
|
| 216 |
+
x = output.transpose(0, 1) # convert to shape `(bsz, tgt_len, hidden)`
|
| 217 |
+
|
| 218 |
+
# Project the outputs to the size of the vocabulary.
|
| 219 |
+
x = self.output_projection(x)
|
| 220 |
+
|
| 221 |
+
# Return the logits and ``None`` for the attention weights
|
| 222 |
+
return x, None
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
2. Registering the Model
|
| 226 |
+
------------------------
|
| 227 |
+
|
| 228 |
+
Now that we've defined our Encoder and Decoder we must *register* our model with
|
| 229 |
+
fairseq using the :func:`~fairseq.models.register_model` function decorator.
|
| 230 |
+
Once the model is registered we'll be able to use it with the existing
|
| 231 |
+
:ref:`Command-line Tools`.
|
| 232 |
+
|
| 233 |
+
All registered models must implement the
|
| 234 |
+
:class:`~fairseq.models.BaseFairseqModel` interface. For sequence-to-sequence
|
| 235 |
+
models (i.e., any model with a single Encoder and Decoder), we can instead
|
| 236 |
+
implement the :class:`~fairseq.models.FairseqEncoderDecoderModel` interface.
|
| 237 |
+
|
| 238 |
+
Create a small wrapper class in the same file and register it in fairseq with
|
| 239 |
+
the name ``'simple_lstm'``::
|
| 240 |
+
|
| 241 |
+
from fairseq.models import FairseqEncoderDecoderModel, register_model
|
| 242 |
+
|
| 243 |
+
# Note: the register_model "decorator" should immediately precede the
|
| 244 |
+
# definition of the Model class.
|
| 245 |
+
|
| 246 |
+
@register_model('simple_lstm')
|
| 247 |
+
class SimpleLSTMModel(FairseqEncoderDecoderModel):
|
| 248 |
+
|
| 249 |
+
@staticmethod
|
| 250 |
+
def add_args(parser):
|
| 251 |
+
# Models can override this method to add new command-line arguments.
|
| 252 |
+
# Here we'll add some new command-line arguments to configure dropout
|
| 253 |
+
# and the dimensionality of the embeddings and hidden states.
|
| 254 |
+
parser.add_argument(
|
| 255 |
+
'--encoder-embed-dim', type=int, metavar='N',
|
| 256 |
+
help='dimensionality of the encoder embeddings',
|
| 257 |
+
)
|
| 258 |
+
parser.add_argument(
|
| 259 |
+
'--encoder-hidden-dim', type=int, metavar='N',
|
| 260 |
+
help='dimensionality of the encoder hidden state',
|
| 261 |
+
)
|
| 262 |
+
parser.add_argument(
|
| 263 |
+
'--encoder-dropout', type=float, default=0.1,
|
| 264 |
+
help='encoder dropout probability',
|
| 265 |
+
)
|
| 266 |
+
parser.add_argument(
|
| 267 |
+
'--decoder-embed-dim', type=int, metavar='N',
|
| 268 |
+
help='dimensionality of the decoder embeddings',
|
| 269 |
+
)
|
| 270 |
+
parser.add_argument(
|
| 271 |
+
'--decoder-hidden-dim', type=int, metavar='N',
|
| 272 |
+
help='dimensionality of the decoder hidden state',
|
| 273 |
+
)
|
| 274 |
+
parser.add_argument(
|
| 275 |
+
'--decoder-dropout', type=float, default=0.1,
|
| 276 |
+
help='decoder dropout probability',
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
@classmethod
|
| 280 |
+
def build_model(cls, args, task):
|
| 281 |
+
# Fairseq initializes models by calling the ``build_model()``
|
| 282 |
+
# function. This provides more flexibility, since the returned model
|
| 283 |
+
# instance can be of a different type than the one that was called.
|
| 284 |
+
# In this case we'll just return a SimpleLSTMModel instance.
|
| 285 |
+
|
| 286 |
+
# Initialize our Encoder and Decoder.
|
| 287 |
+
encoder = SimpleLSTMEncoder(
|
| 288 |
+
args=args,
|
| 289 |
+
dictionary=task.source_dictionary,
|
| 290 |
+
embed_dim=args.encoder_embed_dim,
|
| 291 |
+
hidden_dim=args.encoder_hidden_dim,
|
| 292 |
+
dropout=args.encoder_dropout,
|
| 293 |
+
)
|
| 294 |
+
decoder = SimpleLSTMDecoder(
|
| 295 |
+
dictionary=task.target_dictionary,
|
| 296 |
+
encoder_hidden_dim=args.encoder_hidden_dim,
|
| 297 |
+
embed_dim=args.decoder_embed_dim,
|
| 298 |
+
hidden_dim=args.decoder_hidden_dim,
|
| 299 |
+
dropout=args.decoder_dropout,
|
| 300 |
+
)
|
| 301 |
+
model = SimpleLSTMModel(encoder, decoder)
|
| 302 |
+
|
| 303 |
+
# Print the model architecture.
|
| 304 |
+
print(model)
|
| 305 |
+
|
| 306 |
+
return model
|
| 307 |
+
|
| 308 |
+
# We could override the ``forward()`` if we wanted more control over how
|
| 309 |
+
# the encoder and decoder interact, but it's not necessary for this
|
| 310 |
+
# tutorial since we can inherit the default implementation provided by
|
| 311 |
+
# the FairseqEncoderDecoderModel base class, which looks like:
|
| 312 |
+
#
|
| 313 |
+
# def forward(self, src_tokens, src_lengths, prev_output_tokens):
|
| 314 |
+
# encoder_out = self.encoder(src_tokens, src_lengths)
|
| 315 |
+
# decoder_out = self.decoder(prev_output_tokens, encoder_out)
|
| 316 |
+
# return decoder_out
|
| 317 |
+
|
| 318 |
+
Finally let's define a *named architecture* with the configuration for our
|
| 319 |
+
model. This is done with the :func:`~fairseq.models.register_model_architecture`
|
| 320 |
+
function decorator. Thereafter this named architecture can be used with the
|
| 321 |
+
``--arch`` command-line argument, e.g., ``--arch tutorial_simple_lstm``::
|
| 322 |
+
|
| 323 |
+
from fairseq.models import register_model_architecture
|
| 324 |
+
|
| 325 |
+
# The first argument to ``register_model_architecture()`` should be the name
|
| 326 |
+
# of the model we registered above (i.e., 'simple_lstm'). The function we
|
| 327 |
+
# register here should take a single argument *args* and modify it in-place
|
| 328 |
+
# to match the desired architecture.
|
| 329 |
+
|
| 330 |
+
@register_model_architecture('simple_lstm', 'tutorial_simple_lstm')
|
| 331 |
+
def tutorial_simple_lstm(args):
|
| 332 |
+
# We use ``getattr()`` to prioritize arguments that are explicitly given
|
| 333 |
+
# on the command-line, so that the defaults defined below are only used
|
| 334 |
+
# when no other value has been specified.
|
| 335 |
+
args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 256)
|
| 336 |
+
args.encoder_hidden_dim = getattr(args, 'encoder_hidden_dim', 256)
|
| 337 |
+
args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 256)
|
| 338 |
+
args.decoder_hidden_dim = getattr(args, 'decoder_hidden_dim', 256)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
3. Training the Model
|
| 342 |
+
---------------------
|
| 343 |
+
|
| 344 |
+
Now we're ready to train the model. We can use the existing :ref:`fairseq-train`
|
| 345 |
+
command-line tool for this, making sure to specify our new Model architecture
|
| 346 |
+
(``--arch tutorial_simple_lstm``).
|
| 347 |
+
|
| 348 |
+
.. note::
|
| 349 |
+
|
| 350 |
+
Make sure you've already preprocessed the data from the IWSLT example in the
|
| 351 |
+
:file:`examples/translation/` directory.
|
| 352 |
+
|
| 353 |
+
.. code-block:: console
|
| 354 |
+
|
| 355 |
+
> fairseq-train data-bin/iwslt14.tokenized.de-en \
|
| 356 |
+
--arch tutorial_simple_lstm \
|
| 357 |
+
--encoder-dropout 0.2 --decoder-dropout 0.2 \
|
| 358 |
+
--optimizer adam --lr 0.005 --lr-shrink 0.5 \
|
| 359 |
+
--max-tokens 12000
|
| 360 |
+
(...)
|
| 361 |
+
| epoch 052 | loss 4.027 | ppl 16.30 | wps 420805 | ups 39.7 | wpb 9841 | bsz 400 | num_updates 20852 | lr 1.95313e-05 | gnorm 0.218 | clip 0% | oom 0 | wall 529 | train_wall 396
|
| 362 |
+
| epoch 052 | valid on 'valid' subset | valid_loss 4.74989 | valid_ppl 26.91 | num_updates 20852 | best 4.74954
|
| 363 |
+
|
| 364 |
+
The model files should appear in the :file:`checkpoints/` directory. While this
|
| 365 |
+
model architecture is not very good, we can use the :ref:`fairseq-generate` script to
|
| 366 |
+
generate translations and compute our BLEU score over the test set:
|
| 367 |
+
|
| 368 |
+
.. code-block:: console
|
| 369 |
+
|
| 370 |
+
> fairseq-generate data-bin/iwslt14.tokenized.de-en \
|
| 371 |
+
--path checkpoints/checkpoint_best.pt \
|
| 372 |
+
--beam 5 \
|
| 373 |
+
--remove-bpe
|
| 374 |
+
(...)
|
| 375 |
+
| Translated 6750 sentences (153132 tokens) in 17.3s (389.12 sentences/s, 8827.68 tokens/s)
|
| 376 |
+
| Generate test with beam=5: BLEU4 = 8.18, 38.8/12.1/4.7/2.0 (BP=1.000, ratio=1.066, syslen=139865, reflen=131146)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
4. Making generation faster
|
| 380 |
+
---------------------------
|
| 381 |
+
|
| 382 |
+
While autoregressive generation from sequence-to-sequence models is inherently
|
| 383 |
+
slow, our implementation above is especially slow because it recomputes the
|
| 384 |
+
entire sequence of Decoder hidden states for every output token (i.e., it is
|
| 385 |
+
``O(n^2)``). We can make this significantly faster by instead caching the
|
| 386 |
+
previous hidden states.
|
| 387 |
+
|
| 388 |
+
In fairseq this is called :ref:`Incremental decoding`. Incremental decoding is a
|
| 389 |
+
special mode at inference time where the Model only receives a single timestep
|
| 390 |
+
of input corresponding to the immediately previous output token (for teacher
|
| 391 |
+
forcing) and must produce the next output incrementally. Thus the model must
|
| 392 |
+
cache any long-term state that is needed about the sequence, e.g., hidden
|
| 393 |
+
states, convolutional states, etc.
|
| 394 |
+
|
| 395 |
+
To implement incremental decoding we will modify our model to implement the
|
| 396 |
+
:class:`~fairseq.models.FairseqIncrementalDecoder` interface. Compared to the
|
| 397 |
+
standard :class:`~fairseq.models.FairseqDecoder` interface, the incremental
|
| 398 |
+
decoder interface allows ``forward()`` methods to take an extra keyword argument
|
| 399 |
+
(*incremental_state*) that can be used to cache state across time-steps.
|
| 400 |
+
|
| 401 |
+
Let's replace our ``SimpleLSTMDecoder`` with an incremental one::
|
| 402 |
+
|
| 403 |
+
import torch
|
| 404 |
+
from fairseq.models import FairseqIncrementalDecoder
|
| 405 |
+
|
| 406 |
+
class SimpleLSTMDecoder(FairseqIncrementalDecoder):
|
| 407 |
+
|
| 408 |
+
def __init__(
|
| 409 |
+
self, dictionary, encoder_hidden_dim=128, embed_dim=128, hidden_dim=128,
|
| 410 |
+
dropout=0.1,
|
| 411 |
+
):
|
| 412 |
+
# This remains the same as before.
|
| 413 |
+
super().__init__(dictionary)
|
| 414 |
+
self.embed_tokens = nn.Embedding(
|
| 415 |
+
num_embeddings=len(dictionary),
|
| 416 |
+
embedding_dim=embed_dim,
|
| 417 |
+
padding_idx=dictionary.pad(),
|
| 418 |
+
)
|
| 419 |
+
self.dropout = nn.Dropout(p=dropout)
|
| 420 |
+
self.lstm = nn.LSTM(
|
| 421 |
+
input_size=encoder_hidden_dim + embed_dim,
|
| 422 |
+
hidden_size=hidden_dim,
|
| 423 |
+
num_layers=1,
|
| 424 |
+
bidirectional=False,
|
| 425 |
+
)
|
| 426 |
+
self.output_projection = nn.Linear(hidden_dim, len(dictionary))
|
| 427 |
+
|
| 428 |
+
# We now take an additional kwarg (*incremental_state*) for caching the
|
| 429 |
+
# previous hidden and cell states.
|
| 430 |
+
def forward(self, prev_output_tokens, encoder_out, incremental_state=None):
|
| 431 |
+
if incremental_state is not None:
|
| 432 |
+
# If the *incremental_state* argument is not ``None`` then we are
|
| 433 |
+
# in incremental inference mode. While *prev_output_tokens* will
|
| 434 |
+
# still contain the entire decoded prefix, we will only use the
|
| 435 |
+
# last step and assume that the rest of the state is cached.
|
| 436 |
+
prev_output_tokens = prev_output_tokens[:, -1:]
|
| 437 |
+
|
| 438 |
+
# This remains the same as before.
|
| 439 |
+
bsz, tgt_len = prev_output_tokens.size()
|
| 440 |
+
final_encoder_hidden = encoder_out['final_hidden']
|
| 441 |
+
x = self.embed_tokens(prev_output_tokens)
|
| 442 |
+
x = self.dropout(x)
|
| 443 |
+
x = torch.cat(
|
| 444 |
+
[x, final_encoder_hidden.unsqueeze(1).expand(bsz, tgt_len, -1)],
|
| 445 |
+
dim=2,
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
# We will now check the cache and load the cached previous hidden and
|
| 449 |
+
# cell states, if they exist, otherwise we will initialize them to
|
| 450 |
+
# zeros (as before). We will use the ``utils.get_incremental_state()``
|
| 451 |
+
# and ``utils.set_incremental_state()`` helpers.
|
| 452 |
+
initial_state = utils.get_incremental_state(
|
| 453 |
+
self, incremental_state, 'prev_state',
|
| 454 |
+
)
|
| 455 |
+
if initial_state is None:
|
| 456 |
+
# first time initialization, same as the original version
|
| 457 |
+
initial_state = (
|
| 458 |
+
final_encoder_hidden.unsqueeze(0), # hidden
|
| 459 |
+
torch.zeros_like(final_encoder_hidden).unsqueeze(0), # cell
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
# Run one step of our LSTM.
|
| 463 |
+
output, latest_state = self.lstm(x.transpose(0, 1), initial_state)
|
| 464 |
+
|
| 465 |
+
# Update the cache with the latest hidden and cell states.
|
| 466 |
+
utils.set_incremental_state(
|
| 467 |
+
self, incremental_state, 'prev_state', latest_state,
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
# This remains the same as before
|
| 471 |
+
x = output.transpose(0, 1)
|
| 472 |
+
x = self.output_projection(x)
|
| 473 |
+
return x, None
|
| 474 |
+
|
| 475 |
+
# The ``FairseqIncrementalDecoder`` interface also requires implementing a
|
| 476 |
+
# ``reorder_incremental_state()`` method, which is used during beam search
|
| 477 |
+
# to select and reorder the incremental state.
|
| 478 |
+
def reorder_incremental_state(self, incremental_state, new_order):
|
| 479 |
+
# Load the cached state.
|
| 480 |
+
prev_state = utils.get_incremental_state(
|
| 481 |
+
self, incremental_state, 'prev_state',
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
# Reorder batches according to *new_order*.
|
| 485 |
+
reordered_state = (
|
| 486 |
+
prev_state[0].index_select(1, new_order), # hidden
|
| 487 |
+
prev_state[1].index_select(1, new_order), # cell
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
# Update the cached state.
|
| 491 |
+
utils.set_incremental_state(
|
| 492 |
+
self, incremental_state, 'prev_state', reordered_state,
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
Finally, we can rerun generation and observe the speedup:
|
| 496 |
+
|
| 497 |
+
.. code-block:: console
|
| 498 |
+
|
| 499 |
+
# Before
|
| 500 |
+
|
| 501 |
+
> fairseq-generate data-bin/iwslt14.tokenized.de-en \
|
| 502 |
+
--path checkpoints/checkpoint_best.pt \
|
| 503 |
+
--beam 5 \
|
| 504 |
+
--remove-bpe
|
| 505 |
+
(...)
|
| 506 |
+
| Translated 6750 sentences (153132 tokens) in 17.3s (389.12 sentences/s, 8827.68 tokens/s)
|
| 507 |
+
| Generate test with beam=5: BLEU4 = 8.18, 38.8/12.1/4.7/2.0 (BP=1.000, ratio=1.066, syslen=139865, reflen=131146)
|
| 508 |
+
|
| 509 |
+
# After
|
| 510 |
+
|
| 511 |
+
> fairseq-generate data-bin/iwslt14.tokenized.de-en \
|
| 512 |
+
--path checkpoints/checkpoint_best.pt \
|
| 513 |
+
--beam 5 \
|
| 514 |
+
--remove-bpe
|
| 515 |
+
(...)
|
| 516 |
+
| Translated 6750 sentences (153132 tokens) in 5.5s (1225.54 sentences/s, 27802.94 tokens/s)
|
| 517 |
+
| Generate test with beam=5: BLEU4 = 8.18, 38.8/12.1/4.7/2.0 (BP=1.000, ratio=1.066, syslen=139865, reflen=131146)
|
SimTranslation/code/unibert_waitk_0901_stack/eval_lm.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3 -u
|
| 2 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the MIT license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
from fairseq_cli.eval_lm import cli_main
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
if __name__ == '__main__':
|
| 11 |
+
cli_main()
|
SimTranslation/code/unibert_waitk_0901_stack/examples/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the MIT license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
__version__ = '0.9.0'
|
SimTranslation/code/unibert_waitk_0901_stack/examples/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (238 Bytes). View file
|
|
|
SimTranslation/code/unibert_waitk_0901_stack/examples/waitk/README.md
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Wait-k decoding with Transformer models
|
| 2 |
+
|
| 3 |
+
<p align="center">
|
| 4 |
+
<img src="waitk.png" width="75%">
|
| 5 |
+
</p>
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
### Training for IWSLT'14 De-En:
|
| 9 |
+
|
| 10 |
+
#### Download and pre-process the dataset:
|
| 11 |
+
|
| 12 |
+
```shell
|
| 13 |
+
# Download and prepare the data
|
| 14 |
+
cd examples/translation/
|
| 15 |
+
bash prepare-iwslt14.sh
|
| 16 |
+
cd ../..
|
| 17 |
+
|
| 18 |
+
# Preprocess/binarize the data
|
| 19 |
+
TEXT=examples/translation/iwslt14_deen_bpe10k
|
| 20 |
+
fairseq-preprocess --source-lang de --target-lang en \
|
| 21 |
+
--trainpref $TEXT/train --validpref $TEXT/valid --testpref $TEXT/test \
|
| 22 |
+
--destdir data-bin/iwslt14.tokenized.de-en \
|
| 23 |
+
--workers 20
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
#### Train wait-k on the pre-processed data:
|
| 27 |
+
|
| 28 |
+
```shell
|
| 29 |
+
k=7
|
| 30 |
+
MODEL=tf_wait${k}_iwslt_deen
|
| 31 |
+
mkdir -p checkpoints/$MODEL
|
| 32 |
+
mkdir -p logs
|
| 33 |
+
CUDA_VISIBLE_DEVICES=0 python train.py data-bin/iwslt14.tokenized.de-en -s de -t en --left-pad-source False \
|
| 34 |
+
--user-dir examples/waitk --arch waitk_transformer_small \
|
| 35 |
+
--save-dir checkpoints/$MODEL --tensorboard-logdir logs/$MODEL \
|
| 36 |
+
--seed 1 --no-epoch-checkpoints --no-progress-bar --log-interval 10 \
|
| 37 |
+
--optimizer adam --adam-betas '(0.9, 0.98)' --weight-decay 0.0001 \
|
| 38 |
+
--max-tokens 4000 --update-freq 2 --max-update 50000 \
|
| 39 |
+
--lr-scheduler inverse_sqrt --warmup-updates 4000 --warmup-init-lr '1e-07' --lr 0.002 \
|
| 40 |
+
--min-lr '1e-9' --criterion label_smoothed_cross_entropy --label-smoothing 0.1 \
|
| 41 |
+
--share-decoder-input-output-embed --waitk $k
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
#### Train multi-path on the pre-processed data:
|
| 46 |
+
|
| 47 |
+
```shell
|
| 48 |
+
MODEL=tf_multipath_iwslt_deen
|
| 49 |
+
mkdir -p checkpoints/$MODEL
|
| 50 |
+
mkdir -p logs
|
| 51 |
+
CUDA_VISIBLE_DEVICES=0 python train.py data-bin/iwslt14.tokenized.de-en -s de -t en --left-pad-source False \
|
| 52 |
+
--user-dir examples/waitk --arch waitk_transformer_small \
|
| 53 |
+
--save-dir checkpoints/$MODEL --tensorboard-logdir logs/$MODEL \
|
| 54 |
+
--seed 1 --no-epoch-checkpoints --no-progress-bar --log-interval 10 \
|
| 55 |
+
--optimizer adam --adam-betas '(0.9, 0.98)' --weight-decay 0.0001 \
|
| 56 |
+
--max-tokens 4000 --update-freq 2 --max-update 50000 \
|
| 57 |
+
--lr-scheduler inverse_sqrt --warmup-updates 4000 --warmup-init-lr '1e-07' --lr 0.002 \
|
| 58 |
+
--min-lr '1e-9' --criterion label_smoothed_cross_entropy --label-smoothing 0.1 \
|
| 59 |
+
--share-decoder-input-output-embed --multi-waitk
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
#### Evaluate on the test set:
|
| 64 |
+
|
| 65 |
+
```shell
|
| 66 |
+
k=5 # Evaluation time k
|
| 67 |
+
CUDA_VISIBLE_DEVICES=0 python generate.py data-bin/iwslt14.tokenized.de-en \
|
| 68 |
+
-s de -t en --gen-subset test \
|
| 69 |
+
--path checkpoints/pa_wait7_iwslt_deen/checkpoint_best.pt --task waitk_translation --eval-waitk $k \
|
| 70 |
+
--model-overrides "{'max_source_positions': 1024, 'max_target_positions': 1024}" --left-pad-source False \
|
| 71 |
+
--user-dir examples/waitk --no-progress-bar \
|
| 72 |
+
--max-tokens 8000 --remove-bpe --beam 1
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
### Download pre-trained models
|
| 76 |
+
|
| 77 |
+
Description | Dataset | Model
|
| 78 |
+
:---:|:---:|:---:
|
| 79 |
+
IWSLT'14 De-En | [binary data](https://drive.google.com/file/d/14LqJjPoxJ1VJqJdRpjsXHrfG72SY8M2V/view?usp=sharing) | [model.pt](https://drive.google.com/file/d/1hY9JMbSh66KgHQxRfDjRaqr49x-jZ5qZ/view?usp=sharing)
|
| 80 |
+
|
| 81 |
+
**Evaluate with:**
|
| 82 |
+
|
| 83 |
+
```shell
|
| 84 |
+
tar xzf iwslt14_de_en.tar.gz
|
| 85 |
+
tar xzf tf_waitk_model.tar.gz
|
| 86 |
+
|
| 87 |
+
k=5 # Evaluation time k
|
| 88 |
+
output=wait$k.log
|
| 89 |
+
CUDA_VISIBLE_DEVICES=0 python generate.py PATH_to_data_directory \
|
| 90 |
+
-s de -t en --gen-subset test \
|
| 91 |
+
--path PATH_to_model.pt --task waitk_translation --eval-waitk $k \
|
| 92 |
+
--model-overrides "{'max_source_positions': 1024, 'max_target_positions': 1024}" --left-pad-source False \
|
| 93 |
+
--user-dir examples/waitk --no-progress-bar \
|
| 94 |
+
--max-tokens 8000 --remove-bpe --beam 1 2>&1 | tee -a $output
|
| 95 |
+
python PATH_to_examples/waitk/eval_delay.py $output
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
```bibtex
|
| 100 |
+
@article{elbayad20waitk,
|
| 101 |
+
title={Efficient Wait-k Models for Simultaneous Machine Translation},
|
| 102 |
+
author={Elbayad, Maha and Besacier, Laurent and Verbeek, Jakob},
|
| 103 |
+
journal={arXiv preprint arXiv:2005.08595},
|
| 104 |
+
year={2020}
|
| 105 |
+
}
|
| 106 |
+
```
|
| 107 |
+
|
SimTranslation/code/unibert_waitk_0901_stack/examples/waitk/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from . import models, tasks
|
SimTranslation/code/unibert_waitk_0901_stack/examples/waitk/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (270 Bytes). View file
|
|
|
SimTranslation/code/unibert_waitk_0901_stack/examples/waitk/eval_delay.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os.path as osp
|
| 2 |
+
import numpy as np
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def get_dal(ctxs, src_len):
|
| 7 |
+
# tau = arg min_t {g(t) = src_len}
|
| 8 |
+
prev_gtbis = 0
|
| 9 |
+
dal = 0
|
| 10 |
+
hyp_len = len(ctxs)
|
| 11 |
+
gamma = hyp_len / src_len
|
| 12 |
+
for t, gt in enumerate(ctxs):
|
| 13 |
+
if t:
|
| 14 |
+
gtbis = max(gt, prev_gtbis + 1/gamma)
|
| 15 |
+
else:
|
| 16 |
+
gtbis = gt
|
| 17 |
+
dal += gtbis - t / gamma
|
| 18 |
+
prev_gtbis = gtbis
|
| 19 |
+
return dal / len(ctxs)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_al(ctxs, src_len):
|
| 23 |
+
hyp_len = len(ctxs)
|
| 24 |
+
gamma = hyp_len / src_len
|
| 25 |
+
als = []
|
| 26 |
+
tg = []
|
| 27 |
+
for t, c in enumerate(ctxs):
|
| 28 |
+
if c < src_len:
|
| 29 |
+
als.append(c - t / gamma)
|
| 30 |
+
tg.append(t/gamma)
|
| 31 |
+
else:
|
| 32 |
+
als.append(c - t / gamma)
|
| 33 |
+
tg.append(t/gamma)
|
| 34 |
+
break
|
| 35 |
+
return sum(als)/float(len(als))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def get_delays(res, shift=1, delta=1, catchup=1):
|
| 39 |
+
src_lengths = {}
|
| 40 |
+
trg_lengths = {}
|
| 41 |
+
hyp_lengths = {}
|
| 42 |
+
reads = {}
|
| 43 |
+
contexts = {}
|
| 44 |
+
if osp.exists(res):
|
| 45 |
+
with open(res, 'r') as f:
|
| 46 |
+
for line in f:
|
| 47 |
+
if line.startswith('S-'):
|
| 48 |
+
line = line.split('S-')[-1]
|
| 49 |
+
line = line.split()
|
| 50 |
+
sid = line[0]
|
| 51 |
+
src_lengths[sid] = len(line) - 1
|
| 52 |
+
elif line.startswith('T-'):
|
| 53 |
+
line = line.split('T-')[-1]
|
| 54 |
+
line = line.split()
|
| 55 |
+
sid = line[0]
|
| 56 |
+
trg_lengths[sid] = len(line) - 1
|
| 57 |
+
elif line.startswith('H-'):
|
| 58 |
+
line = line.split('H-')[-1]
|
| 59 |
+
line = line.split()
|
| 60 |
+
sid = line[0]
|
| 61 |
+
hyp_lengths[sid] = len(line) - 2 # Id and score
|
| 62 |
+
elif line.startswith('E-'):
|
| 63 |
+
line = line.split('E-')[-1]
|
| 64 |
+
line = line.split()
|
| 65 |
+
sid = line[0]
|
| 66 |
+
reads[sid] = [int(x) for x in line[1:]]
|
| 67 |
+
elif line.startswith('C-'):
|
| 68 |
+
line = line.split('C-')[-1]
|
| 69 |
+
line = line.split()
|
| 70 |
+
sid = line[0]
|
| 71 |
+
blank_list = []
|
| 72 |
+
for idx, x in enumerate(line[1:]):
|
| 73 |
+
try:
|
| 74 |
+
blank_list.append(int(x))
|
| 75 |
+
except BaseException:
|
| 76 |
+
continue
|
| 77 |
+
#print(line[idx])
|
| 78 |
+
contexts[sid] = blank_list
|
| 79 |
+
#contexts[sid] = [int(x) for x in line[1:]]
|
| 80 |
+
|
| 81 |
+
elif 'BLEU' in line:
|
| 82 |
+
match = re.search(r'BLEU4 = (\S+)', line)
|
| 83 |
+
if match:
|
| 84 |
+
bleu = float(match.group(1)[:-1])
|
| 85 |
+
match = re.search(r'ratio=(\S+)', line)
|
| 86 |
+
if match:
|
| 87 |
+
ratio = float(match.group(1)[:-1])
|
| 88 |
+
|
| 89 |
+
delays = {}
|
| 90 |
+
lagging = {}
|
| 91 |
+
diff_lagging = {}
|
| 92 |
+
|
| 93 |
+
if contexts:
|
| 94 |
+
for k in contexts:
|
| 95 |
+
try:
|
| 96 |
+
ctxs = [min(c, src_lengths[k]) for c in contexts[k]] # error in formatting the contexts at early runs
|
| 97 |
+
except BaseException:
|
| 98 |
+
continue
|
| 99 |
+
# Assert length of contexts is equal to length of hyp:
|
| 100 |
+
if len(ctxs) < hyp_lengths[k]:
|
| 101 |
+
ctxs = ctxs + [ctxs[-1]] * (hyp_lengths[k] - len(ctxs))
|
| 102 |
+
else:
|
| 103 |
+
ctxs = ctxs[:hyp_lengths[k]]
|
| 104 |
+
assert len(ctxs) == hyp_lengths[k], 'There should be as many contexts as there are tokens in the hypothesis'
|
| 105 |
+
assert max(ctxs) <= src_lengths[k], 'Contexts should be less or equal than the source lenght!'
|
| 106 |
+
d = sum(ctxs) / len(ctxs) / src_lengths[k]
|
| 107 |
+
delays[k] = d
|
| 108 |
+
lagging[k] = get_al(ctxs, src_lengths[k])
|
| 109 |
+
diff_lagging[k] = get_dal(ctxs, src_lengths[k])
|
| 110 |
+
|
| 111 |
+
ap = np.mean(np.array(list(delays.values())))
|
| 112 |
+
sap = np.std(np.array(list(delays.values())))
|
| 113 |
+
al = np.mean(np.array(list(lagging.values())))
|
| 114 |
+
sal = np.std(np.array(list(lagging.values())))
|
| 115 |
+
dal = np.mean(np.array(list(diff_lagging.values())))
|
| 116 |
+
sdal = np.std(np.array(list(diff_lagging.values())))
|
| 117 |
+
else:
|
| 118 |
+
for k, hyp_len in hyp_lengths.items():
|
| 119 |
+
src_len = src_lengths[k]
|
| 120 |
+
ctx_0 = min(shift, src_len)
|
| 121 |
+
ctxs = [ctx_0]
|
| 122 |
+
for t in range(1, hyp_len):
|
| 123 |
+
ctx = min(shift + (t // catchup) * delta, src_len)
|
| 124 |
+
ctxs.append(ctx)
|
| 125 |
+
d = sum(ctxs) / len(ctxs) / src_len
|
| 126 |
+
delays[k] = d
|
| 127 |
+
lagging[k] = get_al(ctxs, src_len)
|
| 128 |
+
diff_lagging[k] = get_dal(ctxs, src_len)
|
| 129 |
+
|
| 130 |
+
ap = np.mean(np.array(list(delays.values())))
|
| 131 |
+
sap = np.std(np.array(list(delays.values())))
|
| 132 |
+
al = np.mean(np.array(list(lagging.values())))
|
| 133 |
+
sal = np.std(np.array(list(lagging.values())))
|
| 134 |
+
dal = np.mean(np.array(list(diff_lagging.values())))
|
| 135 |
+
sdal = np.std(np.array(list(diff_lagging.values())))
|
| 136 |
+
|
| 137 |
+
return (bleu, ratio, al, sal, ap, sap, dal, sdal)
|
| 138 |
+
return None
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
if __name__ == "__main__":
|
| 142 |
+
import argparse
|
| 143 |
+
|
| 144 |
+
parser = argparse.ArgumentParser()
|
| 145 |
+
parser.add_argument('--shift', '-w', default=1, type=int)
|
| 146 |
+
parser.add_argument('--delta', '-d', default=1, type=int)
|
| 147 |
+
parser.add_argument('--catchup', '-c', default=1, type=int)
|
| 148 |
+
|
| 149 |
+
parser.add_argument('model')
|
| 150 |
+
args = parser.parse_args()
|
| 151 |
+
res = args.model
|
| 152 |
+
results = get_delays(res, args.shift, args.delta, args.catchup)
|
| 153 |
+
#if results is not None:
|
| 154 |
+
# B, ratio, al, sal, ap, sap, dal, sdal = results
|
| 155 |
+
# print('%.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f' % (B, ratio, ap, sap, al, sal, dal, sdal))
|
| 156 |
+
if results is not None:
|
| 157 |
+
B, ratio, al, sal, ap, sap, dal, sdal = results
|
| 158 |
+
print('B: %.2f, ratio: %.2f, ap: %.2f, sap: %.2f, al: %.2f, sal: %.2f, dal: %.2f, sdal: %.2f' % (B, ratio, ap, sap, al, sal, dal, sdal))
|
| 159 |
+
else:
|
| 160 |
+
print('Missing results')
|
SimTranslation/code/unibert_waitk_0901_stack/examples/waitk/generators/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
for file in os.listdir(os.path.dirname(__file__)):
|
| 5 |
+
if file.endswith('.py') and not file.startswith('_'):
|
| 6 |
+
generator_name = file[:file.find('.py')]
|
| 7 |
+
importlib.import_module('examples.waitk.generators.' + generator_name)
|