Comparing TF and PT models.ipynb 51 KB
Newer Older
1
2
3
4
5
6
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
VictorSanh's avatar
VictorSanh committed
7
8
    "# Comparing TensorFlow (original) and PyTorch models\n",
    "\n",
9
    "You can use this small notebook to check the conversion of the model's weights from the TensorFlow model to the PyTorch model. In the following, we compare the weights of the last layer on a simple example (in `input.txt`) but both models returns all the hidden layers so you can check every stage of the model.\n",
VictorSanh's avatar
VictorSanh committed
10
    "\n",
11
12
13
14
15
    "To run this notebook, follow these instructions:\n",
    "- make sure that your Python environment has both TensorFlow and PyTorch installed,\n",
    "- download the original TensorFlow implementation,\n",
    "- download a pre-trained TensorFlow model as indicaded in the TensorFlow implementation readme,\n",
    "- run the script `convert_tf_checkpoint_to_pytorch.py` as indicated in the `README` to convert the pre-trained TensorFlow model to PyTorch.\n",
VictorSanh's avatar
VictorSanh committed
16
    "\n",
17
    "If needed change the relative paths indicated in this notebook (at the beggining of Sections 1 and 2) to point to the relevent models and code."
VictorSanh's avatar
VictorSanh committed
18
19
20
21
22
23
24
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1/ TensorFlow code"
25
26
27
28
29
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
30
31
32
33
34
35
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-11-05T09:34:49.025081Z",
     "start_time": "2018-11-05T09:34:49.012403Z"
    }
   },
VictorSanh's avatar
VictorSanh committed
36
37
   "outputs": [],
   "source": [
38
39
    "original_tf_inplem_dir = \"./tensorflow_code/\"\n",
    "model_dir = \"../google_models/uncased_L-12_H-768_A-12/\"\n",
VictorSanh's avatar
VictorSanh committed
40
41
42
43
44
    "\n",
    "vocab_file = model_dir + \"vocab.txt\"\n",
    "bert_config_file = model_dir + \"bert_config.json\"\n",
    "init_checkpoint = model_dir + \"bert_model.ckpt\"\n",
    "\n",
45
    "input_file = \"./samples/input.txt\"\n",
VictorSanh's avatar
VictorSanh committed
46
47
48
49
50
51
    "max_seq_length = 128"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
52
53
   "metadata": {
    "ExecuteTime": {
54
55
     "end_time": "2018-11-05T09:34:50.216833Z",
     "start_time": "2018-11-05T09:34:49.027270Z"
56
57
    }
   },
58
   "outputs": [],
59
   "source": [
60
    "import importlib.util\n",
VictorSanh's avatar
VictorSanh committed
61
62
    "import sys\n",
    "\n",
63
64
65
66
67
68
    "spec = importlib.util.spec_from_file_location('*', original_tf_inplem_dir + '/extract_features.py')\n",
    "module = importlib.util.module_from_spec(spec)\n",
    "spec.loader.exec_module(module)\n",
    "sys.modules['extract_features_tensorflow'] = module\n",
    "\n",
    "from extract_features_tensorflow import *"
69
70
71
72
   ]
  },
  {
   "cell_type": "code",
VictorSanh's avatar
VictorSanh committed
73
   "execution_count": 3,
74
75
   "metadata": {
    "ExecuteTime": {
76
77
     "end_time": "2018-11-05T09:34:50.338711Z",
     "start_time": "2018-11-05T09:34:50.218734Z"
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:*** Example ***\n",
      "INFO:tensorflow:unique_id: 0\n",
      "INFO:tensorflow:tokens: [CLS] who was jim henson ? [SEP] jim henson was a puppet ##eer [SEP]\n",
      "INFO:tensorflow:input_ids: 101 2040 2001 3958 27227 1029 102 3958 27227 2001 1037 13997 11510 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "INFO:tensorflow:input_mask: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "INFO:tensorflow:input_type_ids: 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n"
     ]
    }
   ],
   "source": [
thomwolf's avatar
thomwolf committed
95
    "layer_indexes = list(range(12))\n",
96
97
98
99
100
101
102
103
104
105
106
107
108
109
    "bert_config = modeling.BertConfig.from_json_file(bert_config_file)\n",
    "tokenizer = tokenization.FullTokenizer(\n",
    "    vocab_file=vocab_file, do_lower_case=True)\n",
    "examples = read_examples(input_file)\n",
    "\n",
    "features = convert_examples_to_features(\n",
    "    examples=examples, seq_length=max_seq_length, tokenizer=tokenizer)\n",
    "unique_id_to_feature = {}\n",
    "for feature in features:\n",
    "    unique_id_to_feature[feature.unique_id] = feature"
   ]
  },
  {
   "cell_type": "code",
VictorSanh's avatar
VictorSanh committed
110
   "execution_count": 4,
111
112
   "metadata": {
    "ExecuteTime": {
113
114
     "end_time": "2018-11-05T09:34:53.784740Z",
     "start_time": "2018-11-05T09:34:50.342200Z"
115
116
117
118
119
120
121
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
122
123
124
      "WARNING:tensorflow:Estimator's model_fn (<function model_fn_builder.<locals>.model_fn at 0x11d0419d8>) includes params argument, but params are not passed to Estimator.\n",
      "WARNING:tensorflow:Using temporary folder as model directory: /var/folders/yx/cw8n_njx3js5jksyw_qlp8p00000gn/T/tmpt4nhctcg\n",
      "INFO:tensorflow:Using config: {'_model_dir': '/var/folders/yx/cw8n_njx3js5jksyw_qlp8p00000gn/T/tmpt4nhctcg', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true\n",
125
126
127
128
129
      "graph_options {\n",
      "  rewrite_options {\n",
      "    meta_optimizer_iterations: ONE\n",
      "  }\n",
      "}\n",
130
      ", '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x1200ccb70>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=2, num_shards=1, num_cores_per_replica=None, per_host_input_for_training=3, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None), '_cluster': None}\n",
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
      "WARNING:tensorflow:Setting TPUConfig.num_shards==1 is an unsupported behavior. Please fix as soon as possible (leaving num_shards as None.\n",
      "INFO:tensorflow:_TPUContext: eval_on_tpu True\n",
      "WARNING:tensorflow:eval_on_tpu ignored because use_tpu is False.\n"
     ]
    }
   ],
   "source": [
    "is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2\n",
    "run_config = tf.contrib.tpu.RunConfig(\n",
    "    master=None,\n",
    "    tpu_config=tf.contrib.tpu.TPUConfig(\n",
    "        num_shards=1,\n",
    "        per_host_input_for_training=is_per_host))\n",
    "\n",
    "model_fn = model_fn_builder(\n",
    "    bert_config=bert_config,\n",
    "    init_checkpoint=init_checkpoint,\n",
    "    layer_indexes=layer_indexes,\n",
    "    use_tpu=False,\n",
    "    use_one_hot_embeddings=False)\n",
    "\n",
    "# If TPU is not available, this will fall back to normal Estimator on CPU\n",
    "# or GPU.\n",
    "estimator = tf.contrib.tpu.TPUEstimator(\n",
    "    use_tpu=False,\n",
    "    model_fn=model_fn,\n",
    "    config=run_config,\n",
    "    predict_batch_size=1)\n",
    "\n",
    "input_fn = input_fn_builder(\n",
    "    features=features, seq_length=max_seq_length)"
   ]
  },
  {
   "cell_type": "code",
VictorSanh's avatar
VictorSanh committed
166
   "execution_count": 5,
167
168
   "metadata": {
    "ExecuteTime": {
169
170
     "end_time": "2018-11-05T09:34:58.695496Z",
     "start_time": "2018-11-05T09:34:53.787465Z"
171
172
173
174
175
176
177
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
178
      "INFO:tensorflow:Could not find trained model in model_dir: /var/folders/yx/cw8n_njx3js5jksyw_qlp8p00000gn/T/tmpt4nhctcg, running initialization to predict.\n",
179
180
181
182
183
184
      "INFO:tensorflow:Calling model_fn.\n",
      "INFO:tensorflow:Running infer on CPU\n",
      "INFO:tensorflow:Done calling model_fn.\n",
      "INFO:tensorflow:Graph was finalized.\n",
      "INFO:tensorflow:Running local_init_op.\n",
      "INFO:tensorflow:Done running local_init_op.\n",
thomwolf's avatar
thomwolf committed
185
186
187
188
189
190
191
192
193
194
195
196
      "extracting layer 0\n",
      "extracting layer 1\n",
      "extracting layer 2\n",
      "extracting layer 3\n",
      "extracting layer 4\n",
      "extracting layer 5\n",
      "extracting layer 6\n",
      "extracting layer 7\n",
      "extracting layer 8\n",
      "extracting layer 9\n",
      "extracting layer 10\n",
      "extracting layer 11\n",
197
198
199
200
201
202
      "INFO:tensorflow:prediction_loop marked as finished\n",
      "INFO:tensorflow:prediction_loop marked as finished\n"
     ]
    }
   ],
   "source": [
thomwolf's avatar
thomwolf committed
203
    "tensorflow_all_out = []\n",
204
205
206
207
208
    "for result in estimator.predict(input_fn, yield_single_examples=True):\n",
    "    unique_id = int(result[\"unique_id\"])\n",
    "    feature = unique_id_to_feature[unique_id]\n",
    "    output_json = collections.OrderedDict()\n",
    "    output_json[\"linex_index\"] = unique_id\n",
thomwolf's avatar
thomwolf committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
    "    tensorflow_all_out_features = []\n",
    "    # for (i, token) in enumerate(feature.tokens):\n",
    "    all_layers = []\n",
    "    for (j, layer_index) in enumerate(layer_indexes):\n",
    "        print(\"extracting layer {}\".format(j))\n",
    "        layer_output = result[\"layer_output_%d\" % j]\n",
    "        layers = collections.OrderedDict()\n",
    "        layers[\"index\"] = layer_index\n",
    "        layers[\"values\"] = layer_output\n",
    "        all_layers.append(layers)\n",
    "    tensorflow_out_features = collections.OrderedDict()\n",
    "    tensorflow_out_features[\"layers\"] = all_layers\n",
    "    tensorflow_all_out_features.append(tensorflow_out_features)\n",
    "\n",
    "    output_json[\"features\"] = tensorflow_all_out_features\n",
    "    tensorflow_all_out.append(output_json)"
225
226
227
228
   ]
  },
  {
   "cell_type": "code",
VictorSanh's avatar
VictorSanh committed
229
   "execution_count": 6,
thomwolf's avatar
thomwolf committed
230
231
   "metadata": {
    "ExecuteTime": {
232
233
     "end_time": "2018-11-05T09:34:58.741194Z",
     "start_time": "2018-11-05T09:34:58.697190Z"
thomwolf's avatar
thomwolf committed
234
235
236
237
238
239
240
241
242
243
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "odict_keys(['linex_index', 'features'])\n",
thomwolf's avatar
thomwolf committed
244
245
      "number of tokens 1\n",
      "number of layers 12\n"
thomwolf's avatar
thomwolf committed
246
     ]
thomwolf's avatar
thomwolf committed
247
248
249
250
251
252
253
    },
    {
     "data": {
      "text/plain": [
       "(128, 768)"
      ]
     },
VictorSanh's avatar
VictorSanh committed
254
     "execution_count": 6,
thomwolf's avatar
thomwolf committed
255
256
     "metadata": {},
     "output_type": "execute_result"
thomwolf's avatar
thomwolf committed
257
258
259
    }
   ],
   "source": [
thomwolf's avatar
thomwolf committed
260
261
262
263
264
265
    "print(len(tensorflow_all_out))\n",
    "print(len(tensorflow_all_out[0]))\n",
    "print(tensorflow_all_out[0].keys())\n",
    "print(\"number of tokens\", len(tensorflow_all_out[0]['features']))\n",
    "print(\"number of layers\", len(tensorflow_all_out[0]['features'][0]['layers']))\n",
    "tensorflow_all_out[0]['features'][0]['layers'][0]['values'].shape"
thomwolf's avatar
thomwolf committed
266
267
268
269
   ]
  },
  {
   "cell_type": "code",
VictorSanh's avatar
VictorSanh committed
270
   "execution_count": 7,
271
272
   "metadata": {
    "ExecuteTime": {
273
274
     "end_time": "2018-11-05T09:34:58.779046Z",
     "start_time": "2018-11-05T09:34:58.743861Z"
275
276
    }
   },
thomwolf's avatar
thomwolf committed
277
   "outputs": [],
278
   "source": [
thomwolf's avatar
thomwolf committed
279
    "tensorflow_outputs = list(tensorflow_all_out[0]['features'][0]['layers'][t]['values'] for t in layer_indexes)"
thomwolf's avatar
thomwolf committed
280
281
282
283
284
285
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
VictorSanh's avatar
VictorSanh committed
286
    "## 2/ PyTorch code"
287
288
289
290
   ]
  },
  {
   "cell_type": "code",
VictorSanh's avatar
VictorSanh committed
291
   "execution_count": 8,
292
293
   "metadata": {
    "ExecuteTime": {
294
295
     "end_time": "2018-11-05T09:34:58.934535Z",
     "start_time": "2018-11-05T09:34:58.781393Z"
296
297
298
299
    }
   },
   "outputs": [],
   "source": [
300
301
    "import extract_features\n",
    "from extract_features import *"
302
303
304
   ]
  },
  {
thomwolf's avatar
thomwolf committed
305
   "cell_type": "code",
306
307
308
309
310
311
312
   "execution_count": 32,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-11-05T09:41:23.922979Z",
     "start_time": "2018-11-05T09:41:23.890277Z"
    }
   },
VictorSanh's avatar
VictorSanh committed
313
314
   "outputs": [],
   "source": [
315
    "init_checkpoint_pt = \"../google_models/uncased_L-12_H-768_A-12/pytorch_model.bin\""
VictorSanh's avatar
VictorSanh committed
316
317
318
319
   ]
  },
  {
   "cell_type": "code",
320
   "execution_count": 11,
thomwolf's avatar
thomwolf committed
321
322
   "metadata": {
    "ExecuteTime": {
323
324
     "end_time": "2018-11-05T09:35:00.435355Z",
     "start_time": "2018-11-05T09:34:59.269985Z"
VictorSanh's avatar
VictorSanh committed
325
326
    },
    "scrolled": true
thomwolf's avatar
thomwolf committed
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "BertModel(\n",
       "  (embeddings): BERTEmbeddings(\n",
       "    (word_embeddings): Embedding(30522, 768)\n",
       "    (position_embeddings): Embedding(512, 768)\n",
       "    (token_type_embeddings): Embedding(2, 768)\n",
       "    (LayerNorm): BERTLayerNorm()\n",
       "    (dropout): Dropout(p=0.1)\n",
       "  )\n",
       "  (encoder): BERTEncoder(\n",
       "    (layer): ModuleList(\n",
       "      (0): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (1): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (2): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (3): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (4): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (5): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (6): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (7): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (8): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (9): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (10): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (11): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "    )\n",
       "  )\n",
       "  (pooler): BERTPooler(\n",
       "    (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "    (activation): Tanh()\n",
       "  )\n",
       ")"
      ]
     },
627
     "execution_count": 11,
thomwolf's avatar
thomwolf committed
628
629
630
631
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
632
   "source": [
thomwolf's avatar
thomwolf committed
633
    "device = torch.device(\"cpu\")\n",
634
    "model = extract_features.BertModel(bert_config)\n",
thomwolf's avatar
thomwolf committed
635
636
637
638
639
640
    "model.load_state_dict(torch.load(init_checkpoint_pt, map_location='cpu'))\n",
    "model.to(device)"
   ]
  },
  {
   "cell_type": "code",
641
   "execution_count": 12,
thomwolf's avatar
thomwolf committed
642
643
   "metadata": {
    "ExecuteTime": {
644
645
     "end_time": "2018-11-05T09:35:00.476576Z",
     "start_time": "2018-11-05T09:35:00.436902Z"
thomwolf's avatar
thomwolf committed
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
    },
    "code_folding": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "BertModel(\n",
       "  (embeddings): BERTEmbeddings(\n",
       "    (word_embeddings): Embedding(30522, 768)\n",
       "    (position_embeddings): Embedding(512, 768)\n",
       "    (token_type_embeddings): Embedding(2, 768)\n",
       "    (LayerNorm): BERTLayerNorm()\n",
       "    (dropout): Dropout(p=0.1)\n",
       "  )\n",
       "  (encoder): BERTEncoder(\n",
       "    (layer): ModuleList(\n",
       "      (0): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (1): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (2): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (3): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (4): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (5): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (6): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (7): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (8): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (9): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (10): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "      (11): BERTLayer(\n",
       "        (attention): BERTAttention(\n",
       "          (self): BERTSelfAttention(\n",
       "            (query): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (key): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (value): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "          (output): BERTSelfOutput(\n",
       "            (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (LayerNorm): BERTLayerNorm()\n",
       "            (dropout): Dropout(p=0.1)\n",
       "          )\n",
       "        )\n",
       "        (intermediate): BERTIntermediate(\n",
       "          (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
       "        )\n",
       "        (output): BERTOutput(\n",
       "          (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
       "          (LayerNorm): BERTLayerNorm()\n",
       "          (dropout): Dropout(p=0.1)\n",
       "        )\n",
       "      )\n",
       "    )\n",
       "  )\n",
       "  (pooler): BERTPooler(\n",
       "    (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "    (activation): Tanh()\n",
       "  )\n",
       ")"
      ]
     },
948
     "execution_count": 12,
thomwolf's avatar
thomwolf committed
949
950
951
952
953
954
955
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)\n",
    "all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long)\n",
thomwolf's avatar
thomwolf committed
956
    "all_input_type_ids = torch.tensor([f.input_type_ids for f in features], dtype=torch.long)\n",
thomwolf's avatar
thomwolf committed
957
958
    "all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long)\n",
    "\n",
thomwolf's avatar
thomwolf committed
959
    "eval_data = TensorDataset(all_input_ids, all_input_mask, all_input_type_ids, all_example_index)\n",
thomwolf's avatar
thomwolf committed
960
961
962
963
    "eval_sampler = SequentialSampler(eval_data)\n",
    "eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=1)\n",
    "\n",
    "model.eval()"
964
965
966
967
   ]
  },
  {
   "cell_type": "code",
968
   "execution_count": 13,
969
970
   "metadata": {
    "ExecuteTime": {
971
972
     "end_time": "2018-11-05T09:35:00.938199Z",
     "start_time": "2018-11-05T09:35:00.478338Z"
973
974
    }
   },
thomwolf's avatar
thomwolf committed
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[  101,  2040,  2001,  3958, 27227,  1029,   102,  3958, 27227,  2001,\n",
      "          1037, 13997, 11510,   102,     0,     0,     0,     0,     0,     0,\n",
      "             0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n",
      "             0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n",
      "             0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n",
      "             0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n",
      "             0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n",
      "             0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n",
      "             0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n",
      "             0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n",
      "             0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n",
      "             0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n",
      "             0,     0,     0,     0,     0,     0,     0,     0]])\n",
      "tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
      "         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
      "         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
      "         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
      "         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
      "         0, 0, 0, 0, 0, 0, 0, 0]])\n",
      "tensor([0])\n",
      "layer 0 0\n",
      "layer 1 1\n",
      "layer 2 2\n",
      "layer 3 3\n",
      "layer 4 4\n",
      "layer 5 5\n",
      "layer 6 6\n",
      "layer 7 7\n",
      "layer 8 8\n",
      "layer 9 9\n",
      "layer 10 10\n",
      "layer 11 11\n"
     ]
    }
   ],
1015
   "source": [
thomwolf's avatar
thomwolf committed
1016
1017
    "layer_indexes = list(range(12))\n",
    "\n",
thomwolf's avatar
thomwolf committed
1018
    "pytorch_all_out = []\n",
thomwolf's avatar
thomwolf committed
1019
1020
1021
1022
    "for input_ids, input_mask, input_type_ids, example_indices in eval_dataloader:\n",
    "    print(input_ids)\n",
    "    print(input_mask)\n",
    "    print(example_indices)\n",
thomwolf's avatar
thomwolf committed
1023
    "    input_ids = input_ids.to(device)\n",
thomwolf's avatar
thomwolf committed
1024
    "    input_mask = input_mask.to(device)\n",
thomwolf's avatar
thomwolf committed
1025
    "\n",
thomwolf's avatar
thomwolf committed
1026
    "    all_encoder_layers, _ = model(input_ids, token_type_ids=input_type_ids, attention_mask=input_mask)\n",
thomwolf's avatar
thomwolf committed
1027
    "\n",
thomwolf's avatar
thomwolf committed
1028
    "    for b, example_index in enumerate(example_indices):\n",
thomwolf's avatar
thomwolf committed
1029
1030
1031
1032
1033
1034
    "        feature = features[example_index.item()]\n",
    "        unique_id = int(feature.unique_id)\n",
    "        # feature = unique_id_to_feature[unique_id]\n",
    "        output_json = collections.OrderedDict()\n",
    "        output_json[\"linex_index\"] = unique_id\n",
    "        all_out_features = []\n",
thomwolf's avatar
thomwolf committed
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
    "        # for (i, token) in enumerate(feature.tokens):\n",
    "        all_layers = []\n",
    "        for (j, layer_index) in enumerate(layer_indexes):\n",
    "            print(\"layer\", j, layer_index)\n",
    "            layer_output = all_encoder_layers[int(layer_index)].detach().cpu().numpy()\n",
    "            layer_output = layer_output[b]\n",
    "            layers = collections.OrderedDict()\n",
    "            layers[\"index\"] = layer_index\n",
    "            layer_output = layer_output\n",
    "            layers[\"values\"] = layer_output if not isinstance(layer_output, (int, float)) else [layer_output]\n",
    "            all_layers.append(layers)\n",
    "\n",
thomwolf's avatar
thomwolf committed
1047
1048
1049
1050
1051
1052
1053
1054
1055
    "            out_features = collections.OrderedDict()\n",
    "            out_features[\"layers\"] = all_layers\n",
    "            all_out_features.append(out_features)\n",
    "        output_json[\"features\"] = all_out_features\n",
    "        pytorch_all_out.append(output_json)"
   ]
  },
  {
   "cell_type": "code",
1056
   "execution_count": 14,
thomwolf's avatar
thomwolf committed
1057
1058
   "metadata": {
    "ExecuteTime": {
1059
1060
     "end_time": "2018-11-05T09:35:00.986964Z",
     "start_time": "2018-11-05T09:35:00.941625Z"
thomwolf's avatar
thomwolf committed
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "odict_keys(['linex_index', 'features'])\n",
thomwolf's avatar
thomwolf committed
1071
1072
1073
      "number of tokens 1\n",
      "number of layers 12\n",
      "hidden_size 128\n"
thomwolf's avatar
thomwolf committed
1074
     ]
thomwolf's avatar
thomwolf committed
1075
1076
1077
1078
1079
1080
1081
    },
    {
     "data": {
      "text/plain": [
       "(128, 768)"
      ]
     },
1082
     "execution_count": 14,
thomwolf's avatar
thomwolf committed
1083
1084
     "metadata": {},
     "output_type": "execute_result"
thomwolf's avatar
thomwolf committed
1085
1086
1087
1088
1089
1090
    }
   ],
   "source": [
    "print(len(pytorch_all_out))\n",
    "print(len(pytorch_all_out[0]))\n",
    "print(pytorch_all_out[0].keys())\n",
thomwolf's avatar
thomwolf committed
1091
1092
1093
1094
    "print(\"number of tokens\", len(pytorch_all_out))\n",
    "print(\"number of layers\", len(pytorch_all_out[0]['features'][0]['layers']))\n",
    "print(\"hidden_size\", len(pytorch_all_out[0]['features'][0]['layers'][0]['values']))\n",
    "pytorch_all_out[0]['features'][0]['layers'][0]['values'].shape"
thomwolf's avatar
thomwolf committed
1095
1096
1097
1098
   ]
  },
  {
   "cell_type": "code",
1099
   "execution_count": 15,
thomwolf's avatar
thomwolf committed
1100
1101
   "metadata": {
    "ExecuteTime": {
1102
1103
     "end_time": "2018-11-05T09:35:01.026420Z",
     "start_time": "2018-11-05T09:35:00.988377Z"
thomwolf's avatar
thomwolf committed
1104
1105
1106
1107
    }
   },
   "outputs": [
    {
thomwolf's avatar
thomwolf committed
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(128, 768)\n",
      "(128, 768)\n"
     ]
    }
   ],
   "source": [
    "pytorch_outputs = list(pytorch_all_out[0]['features'][0]['layers'][t]['values'] for t in layer_indexes)\n",
    "print(pytorch_outputs[0].shape)\n",
    "print(pytorch_outputs[1].shape)"
   ]
  },
  {
   "cell_type": "code",
1124
   "execution_count": 16,
thomwolf's avatar
thomwolf committed
1125
1126
   "metadata": {
    "ExecuteTime": {
1127
1128
     "end_time": "2018-11-05T09:35:01.065912Z",
     "start_time": "2018-11-05T09:35:01.028986Z"
thomwolf's avatar
thomwolf committed
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(128, 768)\n",
      "(128, 768)\n"
     ]
thomwolf's avatar
thomwolf committed
1139
1140
1141
    }
   ],
   "source": [
thomwolf's avatar
thomwolf committed
1142
1143
    "print(tensorflow_outputs[0].shape)\n",
    "print(tensorflow_outputs[1].shape)"
thomwolf's avatar
thomwolf committed
1144
1145
   ]
  },
VictorSanh's avatar
VictorSanh committed
1146
1147
1148
1149
1150
1151
1152
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3/ Comparing the standard deviation on the last layer of both models"
   ]
  },
thomwolf's avatar
thomwolf committed
1153
1154
  {
   "cell_type": "code",
1155
   "execution_count": 17,
thomwolf's avatar
thomwolf committed
1156
1157
   "metadata": {
    "ExecuteTime": {
1158
1159
     "end_time": "2018-11-05T09:35:01.105895Z",
     "start_time": "2018-11-05T09:35:01.067712Z"
thomwolf's avatar
thomwolf committed
1160
1161
1162
1163
1164
1165
1166
1167
1168
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
1169
   "execution_count": 31,
thomwolf's avatar
thomwolf committed
1170
1171
   "metadata": {
    "ExecuteTime": {
1172
1173
     "end_time": "2018-11-05T09:38:17.626158Z",
     "start_time": "2018-11-05T09:38:17.589346Z"
thomwolf's avatar
thomwolf committed
1174
1175
1176
    }
   },
   "outputs": [
thomwolf's avatar
thomwolf committed
1177
1178
1179
1180
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
      "shape tensorflow layer, shape pytorch layer, standard deviation\n",
      "((128, 768), (128, 768), 1.5258875e-07)\n",
      "((128, 768), (128, 768), 2.342731e-07)\n",
      "((128, 768), (128, 768), 2.801949e-07)\n",
      "((128, 768), (128, 768), 3.5904986e-07)\n",
      "((128, 768), (128, 768), 4.2842768e-07)\n",
      "((128, 768), (128, 768), 5.127951e-07)\n",
      "((128, 768), (128, 768), 6.14668e-07)\n",
      "((128, 768), (128, 768), 7.063922e-07)\n",
      "((128, 768), (128, 768), 7.906173e-07)\n",
      "((128, 768), (128, 768), 8.475192e-07)\n",
      "((128, 768), (128, 768), 8.975489e-07)\n",
      "((128, 768), (128, 768), 4.1671223e-07)\n"
thomwolf's avatar
thomwolf committed
1194
     ]
thomwolf's avatar
thomwolf committed
1195
1196
1197
    }
   ],
   "source": [
1198
1199
1200
1201
    "print('shape tensorflow layer, shape pytorch layer, standard deviation')\n",
    "print('\\n'.join(list(str((np.array(tensorflow_outputs[i]).shape,\n",
    "                          np.array(pytorch_outputs[i]).shape, \n",
    "                          np.sqrt(np.mean((np.array(tensorflow_outputs[i]) - np.array(pytorch_outputs[i]))**2.0)))) for i in range(12))))"
1202
   ]
1203
1204
1205
1206
1207
1208
1209
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
1210
1211
1212
1213
1214
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
1215
   "display_name": "Python [default]",
1216
   "language": "python",
VictorSanh's avatar
VictorSanh committed
1217
   "name": "python3"
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
1229
   "version": "3.6.7"
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
  },
  "toc": {
   "colors": {
    "hover_highlight": "#DAA520",
    "running_highlight": "#FF0000",
    "selected_highlight": "#FFD700"
   },
   "moveMenuLeft": true,
   "nav_menu": {
    "height": "48px",
    "width": "252px"
   },
   "navigate_menu": true,
   "number_sections": true,
   "sideBar": true,
   "threshold": 4,
   "toc_cell": false,
   "toc_section_display": "block",
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}