{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
},
"accelerator": "GPU",
"gpuClass": "standard",
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"f432c0297e88426383f09f7bae595113": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HBoxModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HBoxModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HBoxView",
"box_style": "",
"children": [
"IPY_MODEL_8033cf3d0c77455e85dd93ce557f3a47",
"IPY_MODEL_71b3980870624b51b844ae4a1d80fe33",
"IPY_MODEL_b538c74275f74978afa1a2d5505e3f02"
],
"layout": "IPY_MODEL_c47ad738ff014c48934616b94a7a8c89"
}
},
"8033cf3d0c77455e85dd93ce557f3a47": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_27a907429c4749ccbeded0d43f163073",
"placeholder": "",
"style": "IPY_MODEL_bfe8870956384bb5a4ace0799e5ad81a",
"value": "Downloading: 100%"
}
},
"71b3980870624b51b844ae4a1d80fe33": {
"model_module": "@jupyter-widgets/controls",
"model_name": "FloatProgressModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "FloatProgressModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "ProgressView",
"bar_style": "success",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_1049de934dac494fb706f640234531a7",
"max": 231508,
"min": 0,
"orientation": "horizontal",
"style": "IPY_MODEL_ea3d9b1afa544e5b95737e030ec00ff6",
"value": 231508
}
},
"b538c74275f74978afa1a2d5505e3f02": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_15eae03f81054df4a00fdc70d88f64e9",
"placeholder": "",
"style": "IPY_MODEL_328a39e21dee4124bb48139e13018bc3",
"value": " 232k/232k [00:00<00:00, 512kB/s]"
}
},
"c47ad738ff014c48934616b94a7a8c89": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"27a907429c4749ccbeded0d43f163073": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"bfe8870956384bb5a4ace0799e5ad81a": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "DescriptionStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"description_width": ""
}
},
"1049de934dac494fb706f640234531a7": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"ea3d9b1afa544e5b95737e030ec00ff6": {
"model_module": "@jupyter-widgets/controls",
"model_name": "ProgressStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "ProgressStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"bar_color": null,
"description_width": ""
}
},
"15eae03f81054df4a00fdc70d88f64e9": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"328a39e21dee4124bb48139e13018bc3": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "DescriptionStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"description_width": ""
}
},
"ad79509d9b3a40db83e0ce44a5c53694": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HBoxModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HBoxModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HBoxView",
"box_style": "",
"children": [
"IPY_MODEL_c081050c962b485399fc141a729488a8",
"IPY_MODEL_3cff83b2be294022a67717324814abe6",
"IPY_MODEL_55e67e1d64f54fe3aca368ea04bb8395"
],
"layout": "IPY_MODEL_8dc90379815a4382ac98df8b1695c786"
}
},
"c081050c962b485399fc141a729488a8": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_020a819c0ac645cb9cf56c19bae4e970",
"placeholder": "",
"style": "IPY_MODEL_b7c87f8eea3b45cebb2bdf3b63ab5324",
"value": "Downloading: 100%"
}
},
"3cff83b2be294022a67717324814abe6": {
"model_module": "@jupyter-widgets/controls",
"model_name": "FloatProgressModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "FloatProgressModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "ProgressView",
"bar_style": "success",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_32a6c8a9546e41c98ea7470f0c30bb4f",
"max": 28,
"min": 0,
"orientation": "horizontal",
"style": "IPY_MODEL_474dd89ec5d64f69999c2523de8fae73",
"value": 28
}
},
"55e67e1d64f54fe3aca368ea04bb8395": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_842dbfacfa4f4b5db790d5d61cf1aa9d",
"placeholder": "",
"style": "IPY_MODEL_c68f38e06f634d839aa045266a387cb3",
"value": " 28.0/28.0 [00:00<00:00, 869B/s]"
}
},
"8dc90379815a4382ac98df8b1695c786": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"020a819c0ac645cb9cf56c19bae4e970": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"b7c87f8eea3b45cebb2bdf3b63ab5324": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "DescriptionStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"description_width": ""
}
},
"32a6c8a9546e41c98ea7470f0c30bb4f": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"474dd89ec5d64f69999c2523de8fae73": {
"model_module": "@jupyter-widgets/controls",
"model_name": "ProgressStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "ProgressStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"bar_color": null,
"description_width": ""
}
},
"842dbfacfa4f4b5db790d5d61cf1aa9d": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"c68f38e06f634d839aa045266a387cb3": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "DescriptionStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"description_width": ""
}
},
"09fe51578bbd4e519f19cdd907fa5756": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HBoxModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HBoxModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HBoxView",
"box_style": "",
"children": [
"IPY_MODEL_0cc94dfcb1554178b123dfc8aef9ccd0",
"IPY_MODEL_621aa8f0986b4911acbaaca968f8d135",
"IPY_MODEL_63293d158d594f66bf507594921613c9"
],
"layout": "IPY_MODEL_da190ae0e13c44a5879be61cc4d39adf"
}
},
"0cc94dfcb1554178b123dfc8aef9ccd0": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_3bf2db7d6e42421b9f78c6a829c992d3",
"placeholder": "",
"style": "IPY_MODEL_daab42a11339499caed6d020564cdfc2",
"value": "Downloading: 100%"
}
},
"621aa8f0986b4911acbaaca968f8d135": {
"model_module": "@jupyter-widgets/controls",
"model_name": "FloatProgressModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "FloatProgressModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "ProgressView",
"bar_style": "success",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_32681d3415a34fb9b584f27066c274fc",
"max": 570,
"min": 0,
"orientation": "horizontal",
"style": "IPY_MODEL_a8004d5259de45b2af58f8e8667aaa32",
"value": 570
}
},
"63293d158d594f66bf507594921613c9": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_667288a3c4524630acec3fc4bff3ddd1",
"placeholder": "",
"style": "IPY_MODEL_57d78ed10c3c42cfa493665392fbef1d",
"value": " 570/570 [00:00<00:00, 20.4kB/s]"
}
},
"da190ae0e13c44a5879be61cc4d39adf": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"3bf2db7d6e42421b9f78c6a829c992d3": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"daab42a11339499caed6d020564cdfc2": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "DescriptionStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"description_width": ""
}
},
"32681d3415a34fb9b584f27066c274fc": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"a8004d5259de45b2af58f8e8667aaa32": {
"model_module": "@jupyter-widgets/controls",
"model_name": "ProgressStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "ProgressStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"bar_color": null,
"description_width": ""
}
},
"667288a3c4524630acec3fc4bff3ddd1": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"57d78ed10c3c42cfa493665392fbef1d": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "DescriptionStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"description_width": ""
}
},
"9461cf3cbbbe4c48b9df42acb7f30447": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HBoxModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HBoxModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HBoxView",
"box_style": "",
"children": [
"IPY_MODEL_204b1c8fcca94ce8ac76a91191351a47",
"IPY_MODEL_9e9f5c2bc07d429fbf71461b7eb09c0f",
"IPY_MODEL_4af454a573b94e37aa921fa8e7eef1d6"
],
"layout": "IPY_MODEL_899e11edc2554148bc0892bb88fe5efd"
}
},
"204b1c8fcca94ce8ac76a91191351a47": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_0a4c713fb85543a2a353752b3b1862c8",
"placeholder": "",
"style": "IPY_MODEL_37dceb5c674c47e5aee2155b987f9318",
"value": "Downloading: 100%"
}
},
"9e9f5c2bc07d429fbf71461b7eb09c0f": {
"model_module": "@jupyter-widgets/controls",
"model_name": "FloatProgressModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "FloatProgressModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "ProgressView",
"bar_style": "success",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_c2fbaf79f20c4818bd85e0fdea624623",
"max": 440473133,
"min": 0,
"orientation": "horizontal",
"style": "IPY_MODEL_22f6d4854e944840b2384e900da2c7e7",
"value": 440473133
}
},
"4af454a573b94e37aa921fa8e7eef1d6": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_0b77eaf02c6642b283ef34bb2b74dc30",
"placeholder": "",
"style": "IPY_MODEL_c4840f396f0948e089554b89a5f4cbee",
"value": " 440M/440M [00:09<00:00, 72.2MB/s]"
}
},
"899e11edc2554148bc0892bb88fe5efd": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"0a4c713fb85543a2a353752b3b1862c8": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"37dceb5c674c47e5aee2155b987f9318": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "DescriptionStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"description_width": ""
}
},
"c2fbaf79f20c4818bd85e0fdea624623": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"22f6d4854e944840b2384e900da2c7e7": {
"model_module": "@jupyter-widgets/controls",
"model_name": "ProgressStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "ProgressStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"bar_color": null,
"description_width": ""
}
},
"0b77eaf02c6642b283ef34bb2b74dc30": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"c4840f396f0948e089554b89a5f4cbee": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "DescriptionStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"description_width": ""
}
}
}
}
},
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Xxu7h8e4Cm9u",
"outputId": "59aa2415-df15-46d1-fa63-74a5baf49116"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
"Collecting torchdata==0.4.1\n",
" Downloading torchdata-0.4.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.4 MB)\n",
"\u001b[K |████████████████████████████████| 4.4 MB 13.6 MB/s \n",
"\u001b[?25hRequirement already satisfied: torch==1.12.1 in /usr/local/lib/python3.8/dist-packages (from torchdata==0.4.1) (1.12.1+cu113)\n",
"Collecting portalocker>=2.0.0\n",
" Downloading portalocker-2.6.0-py2.py3-none-any.whl (15 kB)\n",
"Collecting urllib3>=1.25\n",
" Downloading urllib3-1.26.13-py2.py3-none-any.whl (140 kB)\n",
"\u001b[K |████████████████████████████████| 140 kB 70.4 MB/s \n",
"\u001b[?25hRequirement already satisfied: requests in /usr/local/lib/python3.8/dist-packages (from torchdata==0.4.1) (2.23.0)\n",
"Requirement already satisfied: typing-extensions in /usr/local/lib/python3.8/dist-packages (from torch==1.12.1->torchdata==0.4.1) (4.1.1)\n",
"Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.8/dist-packages (from requests->torchdata==0.4.1) (3.0.4)\n",
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.8/dist-packages (from requests->torchdata==0.4.1) (2022.9.24)\n",
" Downloading urllib3-1.25.11-py2.py3-none-any.whl (127 kB)\n",
"\u001b[K |████████████████████████████████| 127 kB 78.0 MB/s \n",
"\u001b[?25hRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.8/dist-packages (from requests->torchdata==0.4.1) (2.10)\n",
"Installing collected packages: urllib3, portalocker, torchdata\n",
" Attempting uninstall: urllib3\n",
" Found existing installation: urllib3 1.24.3\n",
" Uninstalling urllib3-1.24.3:\n",
" Successfully uninstalled urllib3-1.24.3\n",
"Successfully installed portalocker-2.6.0 torchdata-0.4.1 urllib3-1.25.11\n",
"Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
"Requirement already satisfied: torch==1.12.1 in /usr/local/lib/python3.8/dist-packages (1.12.1+cu113)\n",
"Requirement already satisfied: typing-extensions in /usr/local/lib/python3.8/dist-packages (from torch==1.12.1) (4.1.1)\n",
"Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
"Collecting transformers\n",
" Downloading transformers-4.25.1-py3-none-any.whl (5.8 MB)\n",
"\u001b[K |████████████████████████████████| 5.8 MB 14.8 MB/s \n",
"\u001b[?25hCollecting tokenizers!=0.11.3,<0.14,>=0.11.1\n",
" Downloading tokenizers-0.13.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (7.6 MB)\n",
"\u001b[K |████████████████████████████████| 7.6 MB 58.4 MB/s \n",
"\u001b[?25hRequirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.8/dist-packages (from transformers) (6.0)\n",
"Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.8/dist-packages (from transformers) (21.3)\n",
"Requirement already satisfied: filelock in /usr/local/lib/python3.8/dist-packages (from transformers) (3.8.0)\n",
"Requirement already satisfied: requests in /usr/local/lib/python3.8/dist-packages (from transformers) (2.23.0)\n",
"Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.8/dist-packages (from transformers) (1.21.6)\n",
"Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.8/dist-packages (from transformers) (4.64.1)\n",
"Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.8/dist-packages (from transformers) (2022.6.2)\n",
"Collecting huggingface-hub<1.0,>=0.10.0\n",
" Downloading huggingface_hub-0.11.1-py3-none-any.whl (182 kB)\n",
"\u001b[K |████████████████████████████████| 182 kB 72.3 MB/s \n",
"\u001b[?25hRequirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.8/dist-packages (from huggingface-hub<1.0,>=0.10.0->transformers) (4.1.1)\n",
"Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.8/dist-packages (from packaging>=20.0->transformers) (3.0.9)\n",
"Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.8/dist-packages (from requests->transformers) (2.10)\n",
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.8/dist-packages (from requests->transformers) (2022.9.24)\n",
"Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.8/dist-packages (from requests->transformers) (1.25.11)\n",
"Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.8/dist-packages (from requests->transformers) (3.0.4)\n",
"Installing collected packages: tokenizers, huggingface-hub, transformers\n",
"Successfully installed huggingface-hub-0.11.1 tokenizers-0.13.2 transformers-4.25.1\n"
]
}
],
"source": [
"# Install miscellaneous libraries.\n",
"!pip install torchdata==0.4.1\n",
"!pip install torch==1.12.1 \n",
"!pip install transformers"
]
},
{
"cell_type": "code",
"source": [
"# Import libraries used throughout - if you need other libraries, \n",
"# you are free to import them.\n",
"import functools\n",
"import random\n",
"from typing import Any\n",
"\n",
"import numpy as np\n",
"import torch\n",
"import torchtext\n",
"import torchtext.functional as F\n",
"import torchtext.transforms\n",
"from torch import nn\n",
"from torch.utils.data import DataLoader\n",
"from torchtext.datasets import UDPOS\n",
"from torchtext.vocab import build_vocab_from_iterator\n",
"from transformers import BertModel, BertTokenizer\n",
"\n",
"# My imports\n",
"from queue import PriorityQueue"
],
"metadata": {
"id": "5fQf34J3cJY-"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Constants and hyperparameters - you are free to change these for\n",
"# the bonus question.\n",
"SEED = 42\n",
"BATCH_SIZE = 32\n",
"EPOCHS = 3\n",
"LR = 2e-5\n",
"TRANSFORMER = \"bert-base-uncased\"\n",
"\n",
"# My constant - GPU/CPU\n",
"device = torch.device('cpu')"
],
"metadata": {
"id": "F4OW-ryOCwbG"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Reproducibility.\n",
"torch.manual_seed(SEED)\n",
"random.seed(SEED)\n",
"np.random.seed(SEED)\n",
"torch.use_deterministic_algorithms(True)"
],
"metadata": {
"id": "lYinc-SdCzdZ"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Setting up dataloaders for training.\n",
"tokenizer = BertTokenizer.from_pretrained(TRANSFORMER)\n",
"init_token = tokenizer.cls_token\n",
"pad_token = tokenizer.pad_token\n",
"unk_token = tokenizer.unk_token\n",
"sep_token = tokenizer.sep_token\n",
"init_token_idx = tokenizer.convert_tokens_to_ids(init_token)\n",
"pad_token_idx = tokenizer.convert_tokens_to_ids(pad_token)\n",
"unk_token_idx = tokenizer.convert_tokens_to_ids(unk_token)\n",
"sep_token_idx = tokenizer.convert_tokens_to_ids(sep_token)\n",
"max_input_length = tokenizer.max_model_input_sizes[TRANSFORMER]\n",
"\n",
"train_datapipe = UDPOS(split=\"train\")\n",
"valid_datapipe = UDPOS(split=\"valid\")\n",
"pos_vocab = build_vocab_from_iterator(\n",
" [i[1] for i in list(train_datapipe)],\n",
" specials=[init_token, pad_token, sep_token],\n",
")\n",
"\n",
"\n",
"def prepare_words(tokens, tokenizer, max_input_length, init_token, sep_token):\n",
" \"\"\"Preprocesses words such that they may be passed into BERT.\n",
"\n",
" Parameters\n",
" ---\n",
" tokens : List\n",
" List of strings, each of which corresponds to one token in a sequence.\n",
" tokenizer : transformers.models.bert.tokenization_bert.BertTokenizer\n",
" Tokenizer to be used for transforming word strings into word indices\n",
" to be used with BERT.\n",
" max_input_length : int\n",
" Maximum input length of each sequence as expected by our version of BERT.\n",
" init_token : str\n",
" String representation of the beginning of sentence marker for our tokenizer.\n",
" sep_token : str\n",
" String representation of the end of sentence marker for our tokenizer.\n",
"\n",
" Returns\n",
" ---\n",
" tokens : List\n",
" List of preprocessed tokens.\n",
" \"\"\"\n",
" # Append beginning of sentence and end of sentence markers\n",
" # lowercase each token and cut them to the maximum length\n",
" # (minus two to account for beginning and end of sentence).\n",
" tokens = (\n",
" [init_token]\n",
" + [i.lower() for i in tokens[: max_input_length - 2]]\n",
" + [sep_token]\n",
" )\n",
" # Convert word strings to indices.\n",
" tokens = tokenizer.convert_tokens_to_ids(tokens)\n",
" return tokens\n",
"\n",
"\n",
"def prepare_tags(tokens, max_input_length, init_token, sep_token):\n",
" \"\"\"Convert tag strings into indices for use with torch. For symmetry, we perform\n",
" identical preprocessing as on our words, even though we do not need beginning\n",
" of sentence and end of sentence markers for our tags.\n",
"\n",
" Parameters\n",
" ---\n",
" tokens : List\n",
" List of strings, each of which corresponds to one token in a sequence.\n",
" max_input_length : int\n",
" Maximum input length of each sequence as expected by our version of BERT.\n",
" init_token : str\n",
" String representation of the beginning of sentence marker for our tokenizer.\n",
" sep_token : str\n",
" String representation of the end of sentence marker for our tokenizer.\n",
"\n",
" Returns\n",
" ---\n",
" tokens : List\n",
" List of preprocessed tags.\n",
" \"\"\"\n",
" # Append beginning of sentence and end of sentence markers\n",
" # cut the tagging sequence to the maximum length (minus two to account for beginning and end of sentence).\n",
" tokens = [init_token] + tokens[: max_input_length - 2] + [sep_token]\n",
" # Convert tag strings to indices.\n",
" tokens = torchtext.transforms.VocabTransform(pos_vocab)(tokens)\n",
" return tokens\n",
"\n",
"\n",
"text_preprocessor = functools.partial(\n",
" prepare_words,\n",
" tokenizer=tokenizer,\n",
" max_input_length=max_input_length,\n",
" init_token=init_token,\n",
" sep_token=sep_token,\n",
")\n",
"\n",
"tag_preprocessor = functools.partial(\n",
" prepare_tags,\n",
" max_input_length=max_input_length,\n",
" init_token=init_token,\n",
" sep_token=sep_token,\n",
")\n",
"\n",
"\n",
"def apply_transform(x):\n",
" return text_preprocessor(x[0]), tag_preprocessor(x[1])"
],
"metadata": {
"id": "YrTZG0UHC1YU",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 113,
"referenced_widgets": [
"f432c0297e88426383f09f7bae595113",
"8033cf3d0c77455e85dd93ce557f3a47",
"71b3980870624b51b844ae4a1d80fe33",
"b538c74275f74978afa1a2d5505e3f02",
"c47ad738ff014c48934616b94a7a8c89",
"27a907429c4749ccbeded0d43f163073",
"bfe8870956384bb5a4ace0799e5ad81a",
"1049de934dac494fb706f640234531a7",
"ea3d9b1afa544e5b95737e030ec00ff6",
"15eae03f81054df4a00fdc70d88f64e9",
"328a39e21dee4124bb48139e13018bc3",
"ad79509d9b3a40db83e0ce44a5c53694",
"c081050c962b485399fc141a729488a8",
"3cff83b2be294022a67717324814abe6",
"55e67e1d64f54fe3aca368ea04bb8395",
"8dc90379815a4382ac98df8b1695c786",
"020a819c0ac645cb9cf56c19bae4e970",
"b7c87f8eea3b45cebb2bdf3b63ab5324",
"32a6c8a9546e41c98ea7470f0c30bb4f",
"474dd89ec5d64f69999c2523de8fae73",
"842dbfacfa4f4b5db790d5d61cf1aa9d",
"c68f38e06f634d839aa045266a387cb3",
"09fe51578bbd4e519f19cdd907fa5756",
"0cc94dfcb1554178b123dfc8aef9ccd0",
"621aa8f0986b4911acbaaca968f8d135",
"63293d158d594f66bf507594921613c9",
"da190ae0e13c44a5879be61cc4d39adf",
"3bf2db7d6e42421b9f78c6a829c992d3",
"daab42a11339499caed6d020564cdfc2",
"32681d3415a34fb9b584f27066c274fc",
"a8004d5259de45b2af58f8e8667aaa32",
"667288a3c4524630acec3fc4bff3ddd1",
"57d78ed10c3c42cfa493665392fbef1d"
]
},
"outputId": "6cabffd8-a5dc-4bca-dea9-f8da5d0e4ccd"
},
"execution_count": null,
"outputs": [
{
"output_type": "display_data",
"data": {
"text/plain": [
"Downloading: 0%| | 0.00/232k [00:00<?, ?B/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "f432c0297e88426383f09f7bae595113"
}
},
"metadata": {}
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"Downloading: 0%| | 0.00/28.0 [00:00<?, ?B/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "ad79509d9b3a40db83e0ce44a5c53694"
}
},
"metadata": {}
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"Downloading: 0%| | 0.00/570 [00:00<?, ?B/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "09fe51578bbd4e519f19cdd907fa5756"
}
},
"metadata": {}
}
]
},
{
"cell_type": "code",
"source": [
"train_datapipe = (\n",
" train_datapipe.map(apply_transform)\n",
" .batch(BATCH_SIZE)\n",
" .rows2columnar([\"words\", \"pos\"])\n",
")\n",
"train_dataloader = DataLoader(train_datapipe, batch_size=None, shuffle=False)\n",
"valid_datapipe = (\n",
" valid_datapipe.map(apply_transform)\n",
" .batch(BATCH_SIZE)\n",
" .rows2columnar([\"words\", \"pos\"])\n",
")\n",
"valid_dataloader = DataLoader(valid_datapipe, batch_size=None, shuffle=False)"
],
"metadata": {
"id": "ikF2VKvqC2DS"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"class TagLSTM(nn.Module):\n",
" \"\"\"Models an LSTM on top of a transformer to predict POS in a Neural CRF.\"\"\"\n",
"\n",
" def __init__(self, nb_labels, emb_dim, hidden_dim=256):\n",
" \"\"\"Constructor.\n",
"\n",
" Parameters\n",
" ---\n",
" nb_labels : int\n",
" Number of POS tags to be considered.\n",
"\n",
" emb_dim : int\n",
" Input_size of the LSTM - effectively embedding dimension of our pretrained transformer.\n",
"\n",
" hidden_dim : int\n",
" Hidden dimension of the LSTM.\n",
" \"\"\"\n",
" super().__init__()\n",
" self.hidden_dim = hidden_dim\n",
" self.lstm = nn.LSTM(\n",
" emb_dim, hidden_dim // 2, bidirectional=True, batch_first=True\n",
" )\n",
" self.tag = nn.Linear(hidden_dim, nb_labels)\n",
" self.hidden = None\n",
"\n",
" def init_hidden(self, batch_size):\n",
" return (\n",
" torch.randn(2, batch_size, self.hidden_dim // 2, device = device),\n",
" torch.randn(2, batch_size, self.hidden_dim // 2, device = device),\n",
" )\n",
"\n",
" def forward(self, x):\n",
" self.hidden = self.init_hidden(x.shape[0])\n",
" x, self.hidden = self.lstm(x, self.hidden)\n",
" x = self.tag(x)\n",
" return x\n",
"\n",
"\n",
"class NeuralCRF(nn.Module):\n",
" \"\"\"Class modeling a neural CRF for POS tagging.\n",
" We model tag-tag dependencies with a weight for each transition\n",
" and word-tag influence through an LSTM on top of a pretrained transformer.\n",
" \"\"\"\n",
"\n",
" def __init__(\n",
" self,\n",
" pad_idx_word,\n",
" pad_idx_pos,\n",
" bos_idx,\n",
" eos_idx,\n",
" bot_idx,\n",
" eot_idx,\n",
" t_cal,\n",
" transformer,\n",
" lstm_hidden_dim=64,\n",
" beta=0,\n",
" ):\n",
" \"\"\"Constructor.\n",
"\n",
" Parameters\n",
" ---\n",
" pad_idx_word : int\n",
" Index corresponding to padding in the word sequences.\n",
" pad_idx_pos : int\n",
" Index corresponding to padding in the tag sequences.\n",
" bos_idx : int\n",
" Index corresponding to beginning of speech marker in the word sequences.\n",
" eos_idx : int\n",
" Index corresponding to end of speech marker in the word sequences.\n",
" bot_idx : int\n",
" Index corresponding to beginning of tag marker in the tag sequences.\n",
" eot_idx : int\n",
" Index corresponding to end of tag marker in the tag sequences.\n",
" t_cal : List[int]\n",
" List containing all indices corresponding to tags in the tag sequences.\n",
" transformer : BertModel\n",
" Pretrained transformer used to embed sentences before feeding them\n",
" into the LSTM.\n",
" lstm_hiden_dim : int\n",
" Hidden dimension of the LSTM used for POS tagging. Note that\n",
" since we are bidirectional, the effective hidden dimension\n",
" is half of this number.\n",
" beta : float\n",
" Regularization hyperparameter of the entropy regularizer.\n",
" Entropy regularization is only applied for \\beta > 0.\n",
" \"\"\"\n",
" super().__init__()\n",
" self.pad_idx_word = pad_idx_word\n",
" self.pad_idx_pos = pad_idx_pos\n",
" self.bos_idx = bos_idx\n",
" self.eos_idx = eos_idx\n",
" self.bot_idx = bot_idx\n",
" self.eot_idx = eot_idx\n",
" self.t_cal = t_cal\n",
" self.transformer = transformer\n",
" self.lstm_hidden_dim = lstm_hidden_dim\n",
" self.beta = beta\n",
" self.transitions = nn.Parameter(torch.empty(len(t_cal), len(t_cal)))#.to(device)\n",
" self.emissions = TagLSTM(\n",
" len(t_cal),\n",
" transformer.config.to_dict()[\"hidden_size\"],\n",
" lstm_hidden_dim,\n",
" )#.to(device)\n",
" self.init_weights()\n",
"\n",
" def init_weights(self):\n",
" nn.init.uniform_(self.transitions, -0.1, 0.1)\n",
"\n",
" def forward(self, W):\n",
" \"\"\"Decode each sentence within W and return predicted tagging.\n",
"\n",
" Parameters\n",
" ---\n",
" W : torch.tensor\n",
" Word sequences of dimension batch size x max sentence length within batch + 2.\n",
"\n",
" Returns\n",
" ---\n",
" sequences : list\n",
" List of tensors, each of which contains the predicted tag indices for a particular\n",
" word sequence.\n",
" \"\"\"\n",
" # Calculate scores.\n",
" emissions = self.calculate_emissions(W)\n",
" # Run viterbi sentence by sentence.\n",
" sequences = []\n",
" for sentence in range(W.shape[0]):\n",
" # Exclude beginning and end markers from each word sequence.\n",
" scores, backpointers = self.backward_viterbi_log(\n",
" W[sentence, 1:], emissions[sentence, :]\n",
" )\n",
" sequences += [self.get_viterbi(backpointers)]\n",
" return sequences\n",
"\n",
" def calculate_emissions(self, W):\n",
" \"\"\"Calculate emissions (i.e., scores for each word and batch).\n",
"\n",
" Parameters\n",
" ---\n",
" W : torch.tensor\n",
" Word sequences of dimension batch size x max sentence\n",
" length within batch + 2.\n",
"\n",
" Returns\n",
" ---\n",
" emissions : torch.tensor\n",
" Word level scores for each tag of dimension batch_size x max\n",
" sentence length within batch + 1 x |T|.\n",
" The scores for the initial BOS index are already removed here\n",
" since we only needed it for the transformer.\n",
" \"\"\"\n",
" # Directly exclude emissions for the initial word in each sentence\n",
" # since these correspond to the BOS indices that we only need\n",
" # for BERT.\n",
" return self.emissions(self.transformer(W)[0])[:, 1:, :]\n",
"\n",
" def loss(self, T, W):\n",
" \"\"\"Calculate the loss for a batch.\n",
"\n",
" Parameters\n",
" ---\n",
" T : torch.tensor\n",
" True taggings for each sequence within the batch.\n",
" Of dimension batch size x longest sequence within batch + 2.\n",
" Note the paddings, EOS and BOS that have been added to T\n",
" for symmetry with W which needs this for BERT.\n",
" W : torch.tensor\n",
" Words for each sequence within the batch.\n",
" Of dimension batch size x longest sequence within batch + 2.\n",
" Note the paddings, EOS and BOS that have been added to W\n",
" for usage with BERT.\n",
"\n",
" Returns\n",
" ---\n",
" torch.tensor\n",
" Mean loss for the batch.\n",
" \"\"\"\n",
" emissions = self.calculate_emissions(W)\n",
" # Note that we have to handle paddings and EOS within the score\n",
" # and backward functions, but we can already skip the BOS tokens\n",
" # here.\n",
" scores = self.score(emissions, W[:, 1:], T[:, 1:])\n",
" log_normalizer = self.backward_log_Z(W[:, 1:], emissions)\n",
" # NB: If you don't calculate your normaliser in log-space,\n",
" # you may have issues with normalisers being too large. \n",
" # Since this occurs very rarely, you can just skip those \n",
" # batches with a high pseudo normaliser (comment out the code below).\n",
"\n",
" #if torch.any(torch.isinf(log_normalizer)) or torch.any(torch.isnan(log_normalizer)):\n",
" # log_normalizer = torch.clone(torch.log(torch.tensor(1e+200, dtype=torch.float64)))\n",
" loss = torch.negative(torch.mean(scores - log_normalizer))\n",
" if self.beta > 0.0:\n",
" unnormalized_entropy = self.backward_entropy(\n",
" W[:, 1:], emissions\n",
" )\n",
" entropy = (\n",
" (unnormalized_entropy / torch.exp(log_normalizer))\n",
" + log_normalizer\n",
" )\n",
" if torch.isinf(torch.max(torch.exp(log_normalizer))):\n",
" return loss\n",
" else:\n",
" return loss + torch.negative(self.beta * torch.mean(entropy))\n",
" else:\n",
" return loss\n",
"\n",
" def score(self, emissions, W, T):\n",
" \"\"\"Calculate scores for specified taggings and word sequences.\n",
"\n",
" Parameters\n",
" ---\n",
" emissions : torch.tensor\n",
" T : torch.tensor\n",
" Taggings for each sequence within the batch.\n",
" Of dimension batch size x longest sequence within batch + 1.\n",
" Note the paddings, EOS and BOS that have been added to T\n",
" for symmetry with W which needs this for BERT.\n",
" We expect T to already have the initial BOT tag indices removed\n",
" (see `loss` for details).\n",
" W : torch.tensor\n",
" Words for each sequence within the batch.\n",
" Of dimension batch size x longest sequence within batch + 1.\n",
" Note the paddings, EOS and BOS that have been added to W\n",
" for usage with BERT so we mask them out here. We expect\n",
" W to already have the initial BOS word indices taken out\n",
" (see `loss` for details).\n",
"\n",
" Returns\n",
" ---\n",
" scores : torch.tensor\n",
" score(T, W) for all samples in W.\n",
" \"\"\"\n",
" scores = (\n",
" emissions[:, 0].gather(1, (T[:, 0]).unsqueeze(1)).squeeze()\n",
" + self.transitions[self.bot_idx, T[:, 0]]\n",
" )\n",
" for word in range(1, emissions.shape[1]):\n",
" mask = torch.where(\n",
" W[:, word] == self.pad_idx_word, 0, 1\n",
" ) * torch.where(W[:, word] == self.eos_idx, 0, 1)\n",
" scores += mask * (\n",
" emissions[:, word]\n",
" .gather(1, (T[:, word]).unsqueeze(1))\n",
" .squeeze()\n",
" + self.transitions[T[:, word - 1], T[:, word]]\n",
" )\n",
" return scores\n",
"\n",
" def viterbi_naive(self, W, emissions):\n",
" \"\"\"Calculate best tagging naively and return both the best score and best tagging in log space.\n",
"\n",
" NB: This naive version is not vectorized over samples.\n",
"\n",
" Parameters\n",
" ---\n",
" W : torch.tensor\n",
" Of dimension longest sequence within batch + 2 or less.\n",
" Note the paddings, EOS and BOS that have been added to W\n",
" for usage with BERT so we manually remove them here if present.\n",
" emissions : torch.tensor\n",
" Word level scores for each tag of dimension max\n",
" sentence length within batch + 1 x |T| (we assume scores for the BOT\n",
" initial tag have already been removed since BOT/BOS is\n",
" only needed for the transformer).\n",
"\n",
" Returns\n",
" ---\n",
" Tuple[torch.tensor, torch.tensor]\n",
" Tuple containing the log-score of the best tagging and the\n",
" indices of the best tagging for W.\n",
" \"\"\"\n",
" T = self.t_cal\n",
" # Remove padding.\n",
" if torch.any(W == self.pad_idx_word):\n",
" W = W[torch.where(W != self.pad_idx_word)[0]]\n",
" # Remove EOS and BOS if present.\n",
" if torch.any(W == self.eos_idx):\n",
" W = W[:-1]\n",
" if torch.any(W == self.bos_idx):\n",
" W = W[1:]\n",
" T_abs = len(T)\n",
" combinations = torch.combinations(\n",
" T, r=W.shape[0], with_replacement=True\n",
" )\n",
" combinations = torch.cartesian_prod(*[T for ix in range(W.shape[0])])\n",
" best_score = torch.tensor(0.0, dtype=torch.float64)\n",
" best_tag = torch.tensor([])\n",
" for ix, combination in enumerate(combinations):\n",
" if W.shape[0] == 1:\n",
" current_score = (\n",
" emissions[0, combination]\n",
" + self.transitions[self.bot_idx, combination]\n",
" )\n",
" else:\n",
" current_score = (\n",
" emissions[0, combination[0]]\n",
" + self.transitions[self.bot_idx, combination[0]]\n",
" )\n",
" for qx in range(1, combination.shape[0]):\n",
" current_score += (\n",
" emissions[qx, combination[qx]]\n",
" + self.transitions[\n",
" combination[qx - 1], combination[qx]\n",
" ]\n",
" )\n",
"\n",
" if (current_score) > best_score:\n",
" best_score = current_score.double()\n",
" best_tag = combination\n",
" return best_score, best_tag\n",
"\n",
" def log_Z_naive(self, W, emissions):\n",
" \"\"\"Calculate log Z naively.\n",
"\n",
" NB: This naive version is not vectorized over samples.\n",
"\n",
" Parameters\n",
" ---\n",
" W : torch.tensor\n",
" Of dimension longest sequence within batch + 2 or less.\n",
" Note the paddings, EOS and BOS that have been added to W\n",
" for usage with BERT so we manually remove them here if present.\n",
" emissions : torch.tensor\n",
" Word level scores for each tag of dimension max\n",
" sentence length within batch + 1 x |T| (we assume scores for the BOT\n",
" initial tag have already been removed since BOT/BOS is\n",
" only needed for the transformer).\n",
"\n",
" Returns\n",
" ---\n",
" torch.tensor\n",
" Log Z for W.\n",
" \"\"\"\n",
" T = self.t_cal\n",
" # Remove padding\n",
" W = W[torch.where(W != self.pad_idx_word)[0]]\n",
" # Remove EOS and BOS if present\n",
" if torch.any(W == self.eos_idx):\n",
" W = W[:-1]\n",
" if torch.any(W == self.bos_idx):\n",
" W = W[1:]\n",
" T_abs = len(T)\n",
" \n",
" # Generate \\mathcal{T}^N.\n",
" combinations = torch.cartesian_prod(*[T for ix in range(W.shape[0])]).to(device) # my addition\n",
" log_normalizer = torch.zeros(\n",
" combinations.shape[0], dtype=torch.float64, device = device\n",
" )\n",
" # Loop over all possible combinations naively.\n",
" # NB: This is essentially line one on Slide 50.\n",
" for ix, combination in enumerate(combinations):\n",
" # Kludge since indexing is slightly different for one-dim\n",
" # tensors vs two tensors.\n",
" if W.shape[0] == 1:\n",
" # Calculate score as the sum of emissions (i.e., how well\n",
" # does a word match a tag based on BERT embeddings) and\n",
" # transitions (globally, how likely is a transition\n",
" # from the previous tag to the current tag).\n",
" # NB: For the first word, the initial tag is always BOT.\n",
" # NB 2: Since we are in log-space, the exp\n",
" # of the score goes away.\n",
" log_normalizer[ix] = (\n",
" emissions[0, combination]\n",
" + self.transitions[self.bot_idx, combination]\n",
" )\n",
"\n",
" else:\n",
" # Initial score is identical to above.\n",
" log_normalizer[ix] = (\n",
" emissions[0, combination[0]]\n",
" + self.transitions[self.bot_idx, combination[0]]\n",
" )\n",
" for qx in range(1, combination.shape[0]):\n",
" # Score within each potential tagging\n",
" # is calculated the same as above except that we now \n",
" # actually use the previous tag instead of always\n",
" # BOT.\n",
" log_normalizer[ix] += (\n",
" emissions[qx, combination[qx]]\n",
" + self.transitions[\n",
" combination[qx - 1], combination[qx]\n",
" ]\n",
" )\n",
" # Calculate logsumexp numerically stable\n",
" # since we are in log-space.\n",
" return torch.logsumexp(log_normalizer, 0)\n",
"\n",
"\n",
" def entropy_naive(self, W, emissions):\n",
" \"\"\"Calculate the unnormalized entropy naively.\n",
"\n",
" NB: This naive version is not vectorized over samples.\n",
"\n",
" Parameters\n",
" ---\n",
" W : torch.tensor\n",
" Words for each sequence within the batch.\n",
" Of dimension longest sequence within batch + 2 or less.\n",
" Note the paddings, EOS and BOS that have been added to W\n",
" for usage with BERT so we manually remove them here if present.\n",
" emissions : torch.tensor\n",
" Word level scores for each tag of dimension max\n",
" sentence length within batch + 1 x |T| (we assume scores for the BOT\n",
" initial tag have already been removed since BOT/BOS is\n",
" only needed for the transformer).\n",
"\n",
" Returns\n",
" ---\n",
" torch.tensor\n",
" Log Z for W.\n",
" \"\"\"\n",
" T = self.t_cal\n",
" # Remove padding\n",
" W = W[torch.where(W != self.pad_idx_word)[0]]\n",
" # Remove EOS and BOS if present\n",
" if torch.any(W == self.eos_idx):\n",
" W = W[:-1]\n",
" if torch.any(W == self.bos_idx):\n",
" W = W[1:]\n",
" T_abs = len(T)\n",
" combinations = torch.combinations(\n",
" T, r=W.shape[0], with_replacement=True\n",
" )\n",
" combinations = torch.cartesian_prod(T, T)\n",
" combinations = torch.cartesian_prod(*[T for ix in range(W.shape[0])])\n",
" entropy = torch.zeros(1, dtype=torch.float64, device = device)\n",
" for ix, combination in enumerate(combinations):\n",
" if W.shape[0] == 1:\n",
" entropy -= torch.exp((\n",
" emissions[0, combination]\n",
" + self.transitions[self.bot_idx, combination]\n",
" )) * (\n",
" emissions[0, combination]\n",
" + self.transitions[self.bot_idx, combination]\n",
" )\n",
"\n",
" else:\n",
" local_score = (\n",
" emissions[0, combination[0]]\n",
" + self.transitions[self.bot_idx, combination[0]]\n",
" )\n",
" for qx in range(1, combination.shape[0]):\n",
" local_score += (\n",
" emissions[qx, combination[qx]]\n",
" + self.transitions[\n",
" combination[qx - 1], combination[qx]\n",
" ]\n",
" )\n",
" entropy -= torch.exp(local_score) * local_score\n",
" return entropy\n",
"\n",
" def get_viterbi(self, backpointer_matrix):\n",
" \"\"\"Return the best tagging based on a backpointer matrix.\n",
"\n",
" Parameters\n",
" ---\n",
" backpointer_matrix : torch.tensor\n",
" Backpointer matrix from Viterbi indicating which\n",
" tag is the highest scoring for each element in the sequence.\n",
"\n",
" Returns\n",
" ---\n",
" torch.tensor\n",
" Indices of the best tagging based on `backpointer_matrix`.\n",
" \"\"\"\n",
" tagging = torch.zeros(backpointer_matrix.shape[1], device = device)\n",
"\n",
" # First column of backpointer_matrix is the same for all rows - because they correspond to only one word: BOS\n",
" next_idx = backpointer_matrix[0,0]\n",
" tagging[0] = next_idx\n",
"\n",
" # Processing the rest of the words - starting from the first word onwards (index 1 in backpointer matrix)\n",
" for n in range(1, backpointer_matrix.shape[1]):\n",
" next_idx = backpointer_matrix[next_idx,n]\n",
" tagging[n] = next_idx\n",
" \n",
" return tagging\n",
"\n",
" def backward_log_Z(self, W, emissions):\n",
" \"\"\"Calculate log Z using the backward algorithm.\n",
"\n",
" NB: You do need to vectorize this over samples.\n",
"\n",
" Parameters\n",
" ---\n",
" W : torch.tensor\n",
" Words for each sequence within the batch.\n",
" Of dimension batch size x longest sequence within batch + 1.\n",
" Note the paddings, EOS and BOS that have been added to W\n",
" for usage with BERT so we mask them out here. We expect\n",
" W to already have the initial BOS word indices taken out.\n",
" emissions : torch.tensor\n",
" Word level scores for each tag of dimension batch_size x max\n",
" sentence length within batch + 1 x |T| (scores for the BOS\n",
" initial tag have already been removed since BOS is\n",
" only needed for the transformer).\n",
"\n",
" Returns\n",
" ---\n",
" torch.tensor\n",
" Log Z for each sample in W.\n",
" \"\"\"\n",
" T = self.t_cal\n",
" batch_size, seq_len = W.shape\n",
" T_size = len(T)\n",
"\n",
" M = torch.where((W != self.pad_idx_word) & (W != self.eos_idx), 1, 0) # places 1 where words are, 0 where the paddings and EOS are. Of dimensions batch_size x seq_len\n",
"\n",
" # Initial gamma value for the first word (index 0)\n",
" gamma = torch.zeros(batch_size, T_size, dtype=torch.float64, device = device)\n",
"\n",
" # All other words (index >= 1)\n",
" for n in range(seq_len-2, -1, -1):\n",
" gamma = torch.logsumexp( torch.stack(batch_size*[self.transitions]) + torch.stack( T_size*[emissions[:, n+1, :] + gamma] , 1), 2) * torch.stack(T_size*[M[:,n+1]], 1) \\\n",
" + gamma * torch.stack(T_size*[1-M[:,n+1]], 1)\n",
" \n",
" log_z = torch.logsumexp(gamma + torch.stack(batch_size*[self.transitions[self.bot_idx]]) + emissions[:, 0, :], 1)\n",
" \n",
" return log_z\n",
"\n",
" def forward_log_Z(self, W, emissions):\n",
" \"\"\"Calculate log Z using the forward algorithm.\n",
"\n",
" NB: You do need to vectorize this over samples.\n",
"\n",
" Parameters\n",
" ---\n",
" W : torch.tensor\n",
" Words for each sequence within the batch.\n",
" Of dimension batch size x longest sequence within batch + 1.\n",
" Note the paddings, EOS and BOS that have been added to W\n",
" for usage with BERT so we mask them out here. We expect\n",
" W to already have the initial BOS word indices taken out.\n",
" emissions : torch.tensor\n",
" Word level scores for each tag of dimension batch_size x max\n",
" sentence length within batch + 1 x |T| (scores for the BOS\n",
" initial tag have already been removed since BOS is\n",
" only needed for the transformer).\n",
"\n",
" Returns\n",
" ---\n",
" torch.tensor\n",
" Log Z for each sample in W.\n",
" \"\"\"\n",
" T = self.t_cal\n",
" batch_size, seq_len = W.shape\n",
" T_size = len(T)\n",
"\n",
" M = torch.where((W != self.pad_idx_word) & (W != self.eos_idx), 1, 0) # places 1 where words are, 0 where the paddings and EOS are. Of dimensions batch_size x seq_len\n",
"\n",
" # Initial gamma value for the first word (index 0)\n",
" gamma = torch.zeros(batch_size, T_size, dtype=torch.float64) + torch.stack(batch_size*[self.transitions[0, :]]) + emissions[:,0,:]\n",
"\n",
" # All other words (index >= 1)\n",
" for n in range(1, seq_len):\n",
" gamma = (torch.logsumexp( torch.stack(batch_size*[self.transitions]) + torch.stack(T_size*[emissions[:, n, :]], 1) + torch.stack(T_size*[gamma], 2), 1) )*torch.column_stack(T_size*[M[:,n]]) + gamma*torch.column_stack(T_size*[1-M[:,n]])\n",
" \n",
" log_z = torch.logsumexp(gamma,1)\n",
"\n",
" return log_z\n",
"\n",
" def backward_entropy(self, W, emissions):\n",
" \"\"\"Calculate the unnormalized entropy using the backward algorithm.\n",
"\n",
" NB: You do need to vectorize this over samples.\n",
"\n",
" Parameters\n",
" ---\n",
" W : torch.tensor\n",
" Words for each sequence within the batch.\n",
" Of dimension batch size x longest sequence within batch + 1.\n",
" Note the paddings, EOS and BOS that have been added to W\n",
" for usage with BERT so we mask them out here. We expect\n",
" W to already have the initial BOS word indices taken out.\n",
" emissions : torch.tensor\n",
" Word level scores for each tag of dimension batch_size x max\n",
" sentence length within batch + 1 x |T| (scores for the EOS\n",
" initial tag have already been removed since EOS is\n",
" only needed for the transformer).\n",
"\n",
" Returns\n",
" ---\n",
" torch.tensor\n",
" Unnormalized entropy for each sample in W.\n",
" \"\"\"\n",
" T = self.t_cal\n",
" batch_size, seq_len = W.shape\n",
" T_size = len(T)\n",
"\n",
" M = torch.where((W != self.pad_idx_word) & (W != self.eos_idx), 1, 0) # places 1 where words are, 0 where the paddings and EOS are. Of dimensions batch_size x seq_len\n",
"\n",
" # Initial gamma value for the last word (index seq_len)\n",
" beta_1 = torch.zeros((batch_size, T_size), dtype=torch.float64, device = device)\n",
" beta_2 = torch.zeros((batch_size, T_size), dtype=torch.float64, device = device)\n",
"\n",
" # All other words (index <= seq_len-1)\n",
" for n in range(seq_len-2, -1, -1):\n",
" score = torch.stack(batch_size*[self.transitions]) + torch.stack(T_size*[emissions[:, n+1, :]], 1)\n",
"\n",
" beta_2 = torch.sum( torch.exp(score)*(torch.stack(T_size*[beta_2], 1) - score*torch.stack(T_size*[torch.exp(beta_1)], 1)), 2) * torch.stack(T_size*[M[:,n+1]], 1) \\\n",
" + torch.exp(beta_1) * torch.stack(T_size*[1-M[:,n+1]], 1)\n",
"\n",
" beta_1 = torch.logsumexp( score + torch.stack(T_size*[beta_1], 1), 2) * torch.stack(T_size*[M[:,n+1]], 1) \\\n",
" + beta_1 * torch.stack(T_size*[1-M[:,n+1]], 1)\n",
" \n",
" score_bot = torch.stack(batch_size*[self.transitions[self.bot_idx]]) + emissions[:, 0, :]\n",
" Hu = torch.sum(torch.exp(score_bot)*(beta_2 - score_bot*torch.exp(beta_1)), 1)\n",
"\n",
" return Hu\n",
"\n",
" def backward_viterbi_log(self, W, emissions):\n",
" \"\"\"Calculate the best tagging using the backward algorithm and return\n",
" both the scoring matrix in log-space and the backpointer matrix.\n",
"\n",
" NB: You do not need to vectorize this over samples.\n",
"\n",
" Parameters\n",
" ---\n",
" W : torch.tensor\n",
" Of dimension longest sequence within batch + 2 or less.\n",
" Note the paddings, EOS and BOS that have been added to W\n",
" for usage with BERT so we manually remove them here if present.\n",
" emissions : torch.tensor\n",
" Word level scores for each tag of dimension max\n",
" sentence length within batch + 1 x |T| (we assume scores for the BOT\n",
" initial tag have already been removed since BOT/BOS is\n",
" only needed for the transformer).\n",
"\n",
" Returns\n",
" ---\n",
" Tuple[torch.tensor, torch.tensor]\n",
" Tuple containing the scoring matrix in log-space and the\n",
" backpointer matrix for recovering the best tagging.\n",
" \"\"\"\n",
" # Remove padding\n",
" W = W[torch.where(W != self.pad_idx_word)[0]]\n",
" # Remove EOS and BOS if present\n",
" if torch.any(W == self.eos_idx):\n",
" W = W[:-1]\n",
" if torch.any(W == self.bos_idx):\n",
" W = W[1:]\n",
"\n",
" # Rest of the function\n",
" T = self.t_cal\n",
" T_size = len(T)\n",
" seq_len = len(W) # -1 because both EOS and BOS are present\n",
"\n",
" score_bot = self.transitions[self.bot_idx] + emissions[0,:]\n",
" score_matrix = torch.zeros((T_size, seq_len+1), dtype = torch.float64, device = device)\n",
" idx = torch.zeros((T_size, seq_len), dtype = torch.long, device = device)\n",
"\n",
" # Loop through all the words, starting from the last word (one before EOS)\n",
" gamma = torch.zeros(T_size, dtype=torch.float64, device = device)\n",
" score_matrix[:,seq_len] = gamma\n",
" for n in range(seq_len-2, -1, -1): # Element with index seq_len-1 is EOS, and first word is at index seq_len-2 (seq_len >= 2)\n",
" gamma = torch.max(self.transitions + emissions[n+1, :] + gamma, 1)\n",
" score_matrix[:,n+1] = gamma.values\n",
" idx[:, n+1] = gamma.indices\n",
" gamma = gamma.values\n",
"\n",
" # Manually do the BOS part\n",
" gamma, index = torch.max(score_bot + gamma,0)\n",
" score_matrix[:,0] = torch.tensor(T_size*[gamma])\n",
" idx[:,0] = torch.tensor(T_size*[index])\n",
" gamma = gamma.values\n",
"\n",
" return (score_matrix, idx)\n",
"\n",
" def dijkstra_viterbi_log(self, W, emissions):\n",
" \"\"\"Calculate the best tagging using Dijsktra's algorithm and return\n",
" both the best score and best tagging in log space.\n",
"\n",
" NB: You do not need to vectorize this over samples.\n",
"\n",
" Parameters\n",
" ---\n",
" W : torch.tensor\n",
" Of dimension longest sequence within batch + 2 or less.\n",
" Note the paddings, EOS and BOS that have been added to W\n",
" for usage with BERT so we manually remove them here if present.\n",
" emissions : torch.tensor\n",
" Word level scores for each tag of dimension max\n",
" sentence length within batch + 1 x |T| (we assume scores for the BOT\n",
" initial tag have already been removed since BOT/BOS is\n",
" only needed for the transformer).\n",
"\n",
"\n",
" Returns\n",
" ---\n",
" Tuple[torch.tensor, None, log_Z]\n",
" Tuple containing the log-score of the best tagging. \n",
" NB: Since there were some changes in the assignment,\n",
" we don't expect you to return the backpointer matrix\n",
" this year.\n",
" NB 2: We return log_Z if we already use it within the method\n",
" to calculate probabilities, such that we don't have to\n",
" \"\"\"\n",
" # Remove BOS:\n",
" if torch.any(W == self.bos_idx):\n",
" W = W[1:]\n",
"\n",
" log_z = self.forward_log_Z(W.unsqueeze(0), emissions.unsqueeze(0))\n",
"\n",
" # Remove padding and EOS if present\n",
" W = W[torch.where(W != self.pad_idx_word)[0]]\n",
" if torch.any(W == self.eos_idx):\n",
" W = W[:-1]\n",
"\n",
" # Initialization\n",
" T = self.t_cal\n",
" w_len = len(W)\n",
" T_size = len(T)\n",
"\n",
" queue = PriorityQueue()\n",
" popped = {}\n",
" gamma = torch.zeros((T_size, w_len + 1), dtype=torch.float64)\n",
"\n",
" queue.put((0, (0,self.bot_idx))) # first zero is the value (called 'the key') of the tuple which will be used in queue to detemrine what comes first, and the second tuple is the value\n",
"\n",
" # Main loop\n",
" while not queue.empty():\n",
" score, popped_nt = queue.get() # returns min element\n",
" n, t = popped_nt\n",
"\n",
" # if popped_nt not in popped:\n",
" popped[popped_nt] = 1\n",
" gamma[t,n] = -score\n",
"\n",
" if n == w_len: # early stopping\n",
" break\n",
" elif n < w_len:\n",
" for tag in T:\n",
" if ((n+1, tag) not in popped):\n",
" queue.put((-(gamma[t,n] + self.transitions[t, tag] + emissions[n, tag] - log_z), (n+1, tag)))\n",
" \n",
" best_score = torch.min(gamma[:,-1])\n",
"\n",
" return best_score, None, log_z"
],
"metadata": {
"id": "8AgCIq_AC7K5"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"for i, data in enumerate(train_dataloader):\n",
" W_train = F.to_tensor(data[\"words\"], padding_value=pad_token_idx).to(device)\n",
" T_train = F.to_tensor(data[\"pos\"], padding_value=pos_vocab[pad_token]).to(device)\n",
" if i == 0:\n",
" break\n",
"\n",
"bert = BertModel.from_pretrained(TRANSFORMER)#.to(device)\n",
"T_CAL = torch.tensor([i for i in range(pos_vocab.__len__())]).to(device)\n",
"crf = NeuralCRF(\n",
" pad_idx_word=pad_token_idx,\n",
" pad_idx_pos=pos_vocab[pad_token],\n",
" bos_idx=init_token_idx,\n",
" eos_idx=sep_token_idx,\n",
" bot_idx=pos_vocab[init_token],\n",
" eot_idx=pos_vocab[sep_token],\n",
" t_cal=T_CAL,\n",
" transformer=bert,\n",
").to(device)\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 121,
"referenced_widgets": [
"9461cf3cbbbe4c48b9df42acb7f30447",
"204b1c8fcca94ce8ac76a91191351a47",
"9e9f5c2bc07d429fbf71461b7eb09c0f",
"4af454a573b94e37aa921fa8e7eef1d6",
"899e11edc2554148bc0892bb88fe5efd",
"0a4c713fb85543a2a353752b3b1862c8",
"37dceb5c674c47e5aee2155b987f9318",
"c2fbaf79f20c4818bd85e0fdea624623",
"22f6d4854e944840b2384e900da2c7e7",
"0b77eaf02c6642b283ef34bb2b74dc30",
"c4840f396f0948e089554b89a5f4cbee"
]
},
"id": "quoz0jBNb26e",
"outputId": "680309f2-b7d3-4970-bc20-5588c999918d"
},
"execution_count": null,
"outputs": [
{
"output_type": "display_data",
"data": {
"text/plain": [
"Downloading: 0%| | 0.00/440M [00:00<?, ?B/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "9461cf3cbbbe4c48b9df42acb7f30447"
}
},
"metadata": {}
},
{
"output_type": "stream",
"name": "stderr",
"text": [
"Some weights of the model checkpoint at bert-base-uncased were not used when initializing BertModel: ['cls.predictions.decoder.weight', 'cls.seq_relationship.weight', 'cls.predictions.bias', 'cls.seq_relationship.bias', 'cls.predictions.transform.LayerNorm.bias', 'cls.predictions.transform.dense.bias', 'cls.predictions.transform.dense.weight', 'cls.predictions.transform.LayerNorm.weight']\n",
"- This IS expected if you are initializing BertModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n",
"- This IS NOT expected if you are initializing BertModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"## Q3a)"
],
"metadata": {
"id": "bl-a_j9oemGI"
}
},
{
"cell_type": "code",
"source": [
"emissions = crf.calculate_emissions(W_train)\n",
"\n",
"for sentence in range(W_train.shape[0]):\n",
" for word_index in [2, 3, 4]:\n",
" assert torch.isclose(\n",
" crf.log_Z_naive(\n",
" W_train[sentence, :word_index],\n",
" emissions[\n",
" sentence,\n",
" ],\n",
" ),\n",
" crf.backward_log_Z(W_train[:, 1:word_index], emissions)[sentence],\n",
" )\n"
],
"metadata": {
"id": "_MqYdBcMeko3"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# NB: THIS TEST IS NOT GRADED! It is just to help you double check \n",
"# your implementation of backward since the above test cases do not \n",
"# contain instances of EOT/PAD.\n",
"torch.manual_seed(SEED)\n",
"random.seed(SEED)\n",
"np.random.seed(SEED)\n",
"\n",
"crf = NeuralCRF(\n",
" pad_idx_word=pad_token_idx,\n",
" pad_idx_pos=pos_vocab[pad_token],\n",
" bos_idx=init_token_idx,\n",
" eos_idx=sep_token_idx,\n",
" bot_idx=pos_vocab[init_token],\n",
" eot_idx=pos_vocab[sep_token],\n",
" t_cal=T_CAL,\n",
" transformer=bert,\n",
").to(device)\n",
"emissions = crf.calculate_emissions(W_train)\n",
"assert torch.all(torch.isclose(crf.backward_log_Z(W_train[:, 1:], emissions), \n",
" \n",
" torch.tensor([ 88.3197, 54.9441, 51.8413, 49.4724, 110.4930, 40.2174, 40.0351,\n",
" 49.2687, 107.3545, 60.9668, 58.0769, 89.1132, 57.9029, 51.7252,\n",
" 83.1715, 79.5805, 82.7579, 33.7521, 61.2349, 27.4993, 45.7138,\n",
" 49.2352, 52.6344, 122.5854, 150.2306, 156.5732, 40.0482, 30.7149,\n",
" 27.3859, 92.0778, 61.3652, 80.0837], dtype=torch.float64, device = device)))"
],
"metadata": {
"id": "jfi7hVAKNfRF"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Q3b)"
],
"metadata": {
"id": "BdHg2VJUt5VY"
}
},
{
"cell_type": "code",
"source": [
"emissions = crf.calculate_emissions(W_train)\n",
"assert torch.all(\n",
" torch.isclose(\n",
" crf.backward_log_Z(W_train[:, 1:], emissions),\n",
" crf.forward_log_Z(W_train[:, 1:], emissions),\n",
" )\n",
")\n"
],
"metadata": {
"id": "b9RkH9-4eqw2"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Q3c)"
],
"metadata": {
"id": "BoqeybSRvDyC"
}
},
{
"cell_type": "code",
"source": [
"emissions = crf.calculate_emissions(W_train)\n",
"\n",
"for sentence in range(W_train.shape[0]):\n",
" for word_index in [2, 3, 4]:\n",
" score_naive, sequence_naive = crf.viterbi_naive(\n",
" W_train[sentence, :word_index],\n",
" emissions[\n",
" sentence,\n",
" ],\n",
" )\n",
" score_viterbi, backpointers_viterbi = crf.backward_viterbi_log(\n",
" W_train[sentence, :word_index],\n",
" emissions[\n",
" sentence,\n",
" ],\n",
" )\n",
" sequence_viterbi = crf.get_viterbi(backpointers_viterbi)\n",
" assert torch.isclose(score_viterbi[0, 0], score_naive)\n",
" assert torch.all(sequence_viterbi == sequence_naive)\n"
],
"metadata": {
"id": "HPHQf7ksetu8"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# NB: THIS TEST IS NOT GRADED! It is just to help you double check \n",
"# your implementation of Viterbi since the above test cases do not \n",
"# contain instances of EOT/PAD.\n",
"# NB2: Our evaluation expects Viterbi to only predict tags for actual \n",
"# words, thus Viterbi (or get_viterbi) is supposed to remove instances\n",
"# of EOS/BOS/PAD. Example: If Viterbi is asked to predict the sequence \n",
"# [\"BOS\", \"I\", \"like\" \"dogs\", \"EOS\", \"PAD\", \"PAD\"], it should return a tagging \n",
"# of length 3 (one for each valid word in the input).\n",
"torch.manual_seed(SEED)\n",
"random.seed(SEED)\n",
"np.random.seed(SEED)\n",
"\n",
"crf = NeuralCRF(\n",
" pad_idx_word=pad_token_idx,\n",
" pad_idx_pos=pos_vocab[pad_token],\n",
" bos_idx=init_token_idx,\n",
" eos_idx=sep_token_idx,\n",
" bot_idx=pos_vocab[init_token],\n",
" eot_idx=pos_vocab[sep_token],\n",
" t_cal=T_CAL,\n",
" transformer=bert,\n",
")\n",
"emissions = crf.calculate_emissions(W_train)\n",
"sequences_overall = []\n",
"first_batch_sequences_test = [torch.tensor([10, 13, 10, 4, 13, 10, 10, 0, 0, 10, 10, 0, 10, 5, 4, 1, 5, 6,\n",
" 10, 4, 0, 10, 0, 10, 0, 10, 0, 19, 15]),\n",
" torch.tensor([10, 10, 4, 8, 15, 14, 4, 14, 10, 4, 14, 10, 4, 14, 4, 4, 5, 5]),\n",
" torch.tensor([10, 4, 13, 10, 4, 13, 10, 4, 13, 10, 4, 10, 4, 10, 4, 13, 10]),\n",
" torch.tensor([10, 10, 5, 10, 4, 9, 4, 10, 4, 15, 10, 1, 6, 10, 6, 10]),\n",
" torch.tensor([10, 10, 10, 13, 10, 4, 10, 6, 10, 13, 5, 10, 12, 10, 12, 14, 14, 6,\n",
" 6, 6, 10, 10, 10, 6, 10, 6, 10, 10, 6, 10, 7, 6, 10, 6, 18, 10]),\n",
" torch.tensor([10, 4, 19, 15, 4, 15, 4, 15, 10, 0, 10, 4, 5]),\n",
" torch.tensor([ 5, 5, 10, 10, 10, 6, 8, 15, 15, 10, 5, 10, 5]),\n",
" torch.tensor([10, 4, 15, 14, 10, 4, 4, 15, 8, 10, 9, 4, 5, 5, 5, 5]),\n",
" torch.tensor([10, 6, 10, 0, 10, 0, 10, 0, 10, 4, 0, 15, 10, 10, 0, 15, 5, 6,\n",
" 10, 4, 15, 14, 10, 10, 6, 10, 10, 10, 10, 6, 10, 0, 10, 0, 10]),\n",
" torch.tensor([10, 10, 10, 12, 10, 4, 2, 15, 8, 15, 14, 10, 6, 10, 6, 10, 6, 10,\n",
" 4, 5]),\n",
" torch.tensor([10, 13, 10, 4, 13, 10, 10, 5, 10, 6, 10, 4, 5, 5, 10, 5, 5, 10,\n",
" 5]),\n",
" torch.tensor([14, 13, 4, 15, 8, 15, 8, 10, 4, 4, 5, 10, 4, 5, 10, 5, 10, 6,\n",
" 10, 17, 5, 5, 10, 4, 4, 19, 15, 0, 10]),\n",
" torch.tensor([10, 4, 4, 15, 10, 4, 5, 10, 4, 5, 10, 4, 5, 10, 4, 4, 5, 5,\n",
" 5]),\n",
" torch.tensor([10, 8, 15, 14, 4, 5, 10, 4, 15, 8, 10, 4, 4, 15, 15, 15, 8]),\n",
" torch.tensor([14, 10, 10, 10, 4, 17, 5, 10, 15, 14, 10, 0, 14, 4, 14, 10, 4, 4,\n",
" 13, 15, 15, 10, 6, 8, 15, 8, 15]),\n",
" torch.tensor([10, 10, 4, 1, 14, 10, 10, 4, 10, 4, 10, 4, 19, 19, 14, 4, 10, 4,\n",
" 10, 4, 4, 4, 5, 10, 4, 15]),\n",
" torch.tensor([15, 13, 10, 6, 8, 10, 4, 2, 15, 1, 15, 15, 10, 1, 14, 4, 15, 14,\n",
" 5, 10, 10, 10, 10, 1, 7, 0, 15]),\n",
" torch.tensor([10, 4, 0, 10, 10, 0, 10, 4, 13, 10, 10]),\n",
" torch.tensor([10, 10, 13, 15, 14, 10, 15, 14, 4, 10, 6, 10, 10, 4, 13, 4, 13, 10,\n",
" 4, 5]),\n",
" torch.tensor([10, 4, 14, 5, 5, 5, 5, 5, 5]),\n",
" torch.tensor([10, 10, 7, 10, 8, 15, 14, 10, 15, 14, 10, 5, 5, 5, 10]),\n",
" torch.tensor([17, 5, 10, 10, 6, 10, 5, 5, 10, 4, 5, 4, 4, 5, 5, 5]),\n",
" torch.tensor([10, 4, 15, 14, 10, 5, 6, 15, 8, 14, 10, 5, 10, 5, 6, 10, 5]),\n",
" torch.tensor([10, 4, 4, 15, 8, 15, 7, 10, 4, 15, 14, 4, 13, 10, 4, 5, 4, 10,\n",
" 5, 6, 5, 5, 10, 5, 6, 15, 8, 15, 8, 10, 0, 10, 4, 19, 15, 6,\n",
" 10, 6, 10, 5]),\n",
" torch.tensor([10, 4, 19, 15, 15, 7, 14, 4, 14, 4, 14, 18, 10, 4, 1, 15, 10, 10,\n",
" 10, 10, 10, 10, 6, 6, 10, 10, 6, 10, 4, 6, 10, 6, 10, 6, 10, 0,\n",
" 10, 10, 6, 10, 10, 8, 10, 9, 14, 10, 9, 5, 4]),\n",
" torch.tensor([14, 10, 0, 10, 4, 0, 10, 4, 4, 5, 4, 4, 4, 4, 8, 10, 10, 0,\n",
" 10, 4, 6, 10, 10, 6, 10, 4, 10, 4, 9, 5, 10, 4, 10, 0, 10, 0,\n",
" 10, 6, 10, 10, 10, 0, 0, 10, 0, 10, 0, 10, 7, 10, 4]),\n",
" torch.tensor([10, 6, 8, 15, 8, 15, 0, 15, 18, 1, 8, 15, 14]),\n",
" torch.tensor([10, 4, 14, 11, 8, 18, 14, 14, 14, 5]),\n",
" torch.tensor([10, 12, 10, 4, 8, 15, 14, 5, 5]),\n",
" torch.tensor([10, 4, 10, 0, 10, 0, 10, 10, 0, 15, 10, 10, 10, 4, 10, 4, 0, 10,\n",
" 0, 10, 0, 10, 0, 10, 4, 9, 10, 6, 10, 5]),\n",
" torch.tensor([10, 10, 5, 10, 10, 0, 10, 5, 10, 5, 10, 5, 10, 5, 10, 4, 8, 15,\n",
" 8, 17]),\n",
" torch.tensor([ 8, 8, 10, 10, 10, 6, 10, 2, 8, 15, 10, 6, 10, 0, 8, 15, 14, 10,\n",
" 10, 10, 2, 10, 6, 10, 18, 10])]\n",
"\n",
"for sentence in range(W_train.shape[0]):\n",
" score_viterbi, backpointers_viterbi = crf.backward_viterbi_log(\n",
" W_train[sentence, :],\n",
" emissions[\n",
" sentence,\n",
" ],\n",
" )\n",
" sequence_viterbi = crf.get_viterbi(backpointers_viterbi)\n",
" sequences_overall += [sequence_viterbi]\n",
"\n",
"assert torch.all(torch.tensor([torch.all(first_batch_sequences_test[ix] == sequences_overall[ix]) for ix in range(len(sequences_overall))]))"
],
"metadata": {
"id": "-4hs8vTzyLZD"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Q3d)"
],
"metadata": {
"id": "pwaRWIiVvLNQ"
}
},
{
"cell_type": "code",
"source": [
"emissions = crf.calculate_emissions(W_train)\n",
"\n",
"for sentence in range(W_train.shape[0]):\n",
" for word_index in [2, 3, 4]:\n",
" score_viterbi, backpointers_viterbi = crf.backward_viterbi_log(\n",
" W_train[sentence, 1:word_index], emissions[sentence, :word_index]\n",
" )\n",
" #sequence_viterbi = crf.get_viterbi(backpointers_viterbi)\n",
" score_dijkstra, sequence_dijsktra, log_Z = crf.dijkstra_viterbi_log(\n",
" W_train[sentence, 1:word_index], emissions[sentence, :word_index]\n",
" )\n",
" assert torch.isclose(\n",
" score_viterbi[0, 0],\n",
" score_dijkstra\n",
" + torch.sum(\n",
" (W_train[sentence, 1:word_index] != crf.eos_idx)\n",
" * (W_train[sentence, 1:word_index] != crf.pad_idx_word)\n",
" )\n",
" * log_Z,\n",
" )\n",
" #assert torch.all(sequence_viterbi == sequence_dijsktra)"
],
"metadata": {
"id": "Yfch1WjMe1-u"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Q3e)"
],
"metadata": {
"id": "RknzYtrUvln7"
}
},
{
"cell_type": "code",
"source": [
"%%timeit -n 10\n",
"score_viterbi, backpointers_viterbi = crf.backward_viterbi_log(W_train[0, 1:4], emissions[0, :])\n",
"#sequence_viterbi = crf.get_viterbi(backpointers_viterbi)"
],
"metadata": {
"id": "49kT9v7yfO3f",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "a22855c3-39bf-4f0a-bd27-1307e25c434c"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"228 µs ± 46.7 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"%%timeit -n 10\n",
"score_dijkstra, sequence_dijsktra, log_Z = crf.dijkstra_viterbi_log(W_train[0, 1:4], emissions[0, :])"
],
"metadata": {
"id": "-cHJ0nUdfhVo",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "c10a6668-ba5d-44dc-8b8b-9fc821c9c0c7"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"543 ms ± 18.7 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"%%timeit -n 10\n",
"score_naive, sequence_naive = crf.viterbi_naive(W_train[0, 1:4], emissions[0, :])"
],
"metadata": {
"id": "4P8rf_32vo-x",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "eba21854-087e-4b48-e508-b1f5e64a463f"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"552 ms ± 34.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"## Q3f)"
],
"metadata": {
"id": "zz5Gely7wU9X"
}
},
{
"cell_type": "code",
"source": [
"def train_model_report_accuracy(\n",
" crf,\n",
" lr,\n",
" epochs,\n",
" train_dataloader,\n",
" dev_dataloader,\n",
" pad_token_idx_word,\n",
" pad_token_idx_tag,\n",
"):\n",
"\n",
" \"\"\"Train model for `epochs` epochs and report performance on \n",
" dev set after each epoch.\n",
"\n",
" Parameters\n",
" ---\n",
" crf : NeuralCRF\n",
" lr : float\n",
" Learning rate to train with.\n",
" epochs : int\n",
" For how many epochs to train.\n",
" train_dataloader : torch.DataLoader\n",
" dev_dataloder : torch.DataLoader\n",
" pad_token_idx_word : int\n",
" Index with which to pad the word indices.\n",
" pad_token_idx_tag : int\n",
" Index with which to pad the tag indices.\n",
" \"\"\"\n",
" crf.train(True)\n",
" optimizer = torch.optim.Adam(crf.parameters(), lr=lr)\n",
" for epoch in range(epochs):\n",
" for i, data in enumerate(train_dataloader):\n",
" torch.autograd.set_detect_anomaly(True)\n",
" W = F.to_tensor(data[\"words\"], padding_value=pad_token_idx_word).to(device)\n",
" T = F.to_tensor(data[\"pos\"], padding_value=pad_token_idx_tag).to(device)\n",
" for param in crf.parameters():\n",
" param.grad = None\n",
" loss = crf.loss(T, W)\n",
" loss.backward()\n",
" optimizer.step()\n",
" with torch.no_grad():\n",
" predicted_sequences = []\n",
" true_sequences = []\n",
" for i_dev, data_dev in enumerate(valid_dataloader):\n",
" W_dev = F.to_tensor(\n",
" data_dev[\"words\"], padding_value=pad_token_idx_word\n",
" ).to(device)\n",
" T_dev = F.to_tensor(\n",
" data_dev[\"pos\"], padding_value=pad_token_idx_tag\n",
" ).to(device)\n",
" sequence_viterbi = crf(W_dev)\n",
" predicted_sequences += sequence_viterbi\n",
" for ix in range(W_dev.shape[0]):\n",
" true_sequences += [\n",
" T_dev[ix, 1 : (sequence_viterbi[ix].shape[0] + 1)]\n",
" ]\n",
"\n",
" acc = torch.tensor(0.0, device = device)\n",
" for ix in range(len(predicted_sequences)):\n",
" acc += torch.mean(\n",
" (predicted_sequences[ix].to(device) == true_sequences[ix]).float()\n",
" )\n",
" acc = acc / len(predicted_sequences)\n",
" print(\"-------------------------\")\n",
" print(f\"Epoch: {epoch + 1} / {epochs}\")\n",
" print(f\"Development set accuracy: {acc}\")\n",
" print(\"-------------------------\")\n",
" epoch += 1\n",
" return None\n"
],
"metadata": {
"id": "ho8m3Vs-wVum"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# My addition (whole cell): For the purpose of running the training on the GPU\n",
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
"torch.use_deterministic_algorithms(False)\n",
"\n",
"for i, data in enumerate(train_dataloader):\n",
" W_train = F.to_tensor(data[\"words\"], padding_value=pad_token_idx).to(device)\n",
" T_train = F.to_tensor(data[\"pos\"], padding_value=pos_vocab[pad_token]).to(device)\n",
" if i == 0:\n",
" break"
],
"metadata": {
"id": "Aed5xeUVNcMc",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "3d17519a-1c66-4ec7-9024-ca1c215763b9"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stderr",
"text": [
"/usr/local/lib/python3.8/dist-packages/torch/utils/data/datapipes/iter/combining.py:248: UserWarning: Some child DataPipes are not exhausted when __iter__ is called. We are resetting the buffer and each child DataPipe will read from the start again.\n",
" warnings.warn(\"Some child DataPipes are not exhausted when __iter__ is called. We are resetting \"\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"torch.manual_seed(SEED)\n",
"random.seed(SEED)\n",
"np.random.seed(SEED)\n",
"\n",
"crf = NeuralCRF(\n",
" pad_idx_word=pad_token_idx,\n",
" pad_idx_pos=pos_vocab[pad_token],\n",
" bos_idx=init_token_idx,\n",
" eos_idx=sep_token_idx,\n",
" bot_idx=pos_vocab[init_token],\n",
" eot_idx=pos_vocab[sep_token],\n",
" t_cal=T_CAL,\n",
" transformer=bert#.to(device),\n",
").to(device)\n",
"train_model_report_accuracy(\n",
" crf,\n",
" LR,\n",
" EPOCHS,\n",
" train_dataloader,\n",
" valid_dataloader,\n",
" pad_token_idx,\n",
" pos_vocab[pad_token],\n",
")\n"
],
"metadata": {
"id": "TYrbXAELyRQR",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "d2413ccc-7616-4887-cef1-dc39d564c0c1"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"-------------------------\n",
"Epoch: 1 / 3\n",
"Development set accuracy: 0.8808290362358093\n",
"-------------------------\n",
"-------------------------\n",
"Epoch: 2 / 3\n",
"Development set accuracy: 0.8994888067245483\n",
"-------------------------\n",
"-------------------------\n",
"Epoch: 3 / 3\n",
"Development set accuracy: 0.9052911400794983\n",
"-------------------------\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"## Q3g)"
],
"metadata": {
"id": "7j3Xr0HBxhq8"
}
},
{
"cell_type": "code",
"source": [
"# My addition:\n",
"device = torch.device('cpu')\n",
"torch.use_deterministic_algorithms(True)\n",
"\n",
"crf.to(device)\n",
"W_train = W_train.to(device)\n",
"T_train = T_train.to(device)\n",
"\n",
"# Rest of the code:\n",
"\n",
"emissions = crf.calculate_emissions(W_train)\n",
"\n",
"for sentence in range(W_train.shape[0]):\n",
" for word_index in [2, 3, 4]:\n",
" assert torch.isclose(\n",
" crf.entropy_naive(\n",
" W_train[sentence, :word_index],\n",
" emissions[\n",
" sentence,\n",
" ],\n",
" ),\n",
" crf.backward_entropy(W_train[:, 1:word_index], emissions)[sentence],\n",
" )\n"
],
"metadata": {
"id": "NgAws_iGxiX6"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# My addition (whole cell): For the purpose of running the training on the GPU\n",
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
"torch.use_deterministic_algorithms(False)\n",
"\n",
"for i, data in enumerate(train_dataloader):\n",
" W_train = F.to_tensor(data[\"words\"], padding_value=pad_token_idx).to(device)\n",
" T_train = F.to_tensor(data[\"pos\"], padding_value=pos_vocab[pad_token]).to(device)\n",
" if i == 0:\n",
" break"
],
"metadata": {
"id": "mvDS3vqxOyr2"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"torch.manual_seed(SEED)\n",
"random.seed(SEED)\n",
"np.random.seed(SEED)\n",
"\n",
"entropy_regularized_crf = NeuralCRF(\n",
" pad_idx_word=pad_token_idx,\n",
" pad_idx_pos=pos_vocab[pad_token],\n",
" bos_idx=init_token_idx,\n",
" eos_idx=sep_token_idx,\n",
" bot_idx=pos_vocab[init_token],\n",
" eot_idx=pos_vocab[sep_token],\n",
" t_cal=T_CAL,\n",
" transformer=bert,\n",
" beta=10.0,\n",
").to(device)\n",
"train_model_report_accuracy(\n",
" entropy_regularized_crf,\n",
" LR,\n",
" EPOCHS,\n",
" train_dataloader,\n",
" valid_dataloader,\n",
" pad_token_idx,\n",
" pos_vocab[pad_token],\n",
")\n"
],
"metadata": {
"id": "jIKnm3b_Bm1N",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "747ab85b-ef85-4626-bbb3-bdfaa77e62e2"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"-------------------------\n",
"Epoch: 1 / 3\n",
"Development set accuracy: 0.9039604663848877\n",
"-------------------------\n",
"-------------------------\n",
"Epoch: 2 / 3\n",
"Development set accuracy: 0.9168574810028076\n",
"-------------------------\n",
"-------------------------\n",
"Epoch: 3 / 3\n",
"Development set accuracy: 0.921291172504425\n",
"-------------------------\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"torch.manual_seed(SEED)\n",
"random.seed(SEED)\n",
"np.random.seed(SEED)\n",
"\n",
"entropy_regularized_crf = NeuralCRF(\n",
" pad_idx_word=pad_token_idx,\n",
" pad_idx_pos=pos_vocab[pad_token],\n",
" bos_idx=init_token_idx,\n",
" eos_idx=sep_token_idx,\n",
" bot_idx=pos_vocab[init_token],\n",
" eot_idx=pos_vocab[sep_token],\n",
" t_cal=T_CAL,\n",
" transformer=bert,\n",
" beta=1.0,\n",
").to(device)\n",
"train_model_report_accuracy(\n",
" entropy_regularized_crf,\n",
" LR,\n",
" EPOCHS,\n",
" train_dataloader,\n",
" valid_dataloader,\n",
" pad_token_idx,\n",
" pos_vocab[pad_token],\n",
")\n"
],
"metadata": {
"id": "wdhhpDDfyj-8",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "f235ad08-b720-469a-dfb5-e28a191ab74f"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"-------------------------\n",
"Epoch: 1 / 3\n",
"Development set accuracy: 0.9181938171386719\n",
"-------------------------\n",
"-------------------------\n",
"Epoch: 2 / 3\n",
"Development set accuracy: 0.9190983772277832\n",
"-------------------------\n",
"-------------------------\n",
"Epoch: 3 / 3\n",
"Development set accuracy: 0.9189178943634033\n",
"-------------------------\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"torch.manual_seed(SEED)\n",
"random.seed(SEED)\n",
"np.random.seed(SEED)\n",
"\n",
"entropy_regularized_crf = NeuralCRF(\n",
" pad_idx_word=pad_token_idx,\n",
" pad_idx_pos=pos_vocab[pad_token],\n",
" bos_idx=init_token_idx,\n",
" eos_idx=sep_token_idx,\n",
" bot_idx=pos_vocab[init_token],\n",
" eot_idx=pos_vocab[sep_token],\n",
" t_cal=T_CAL,\n",
" transformer=bert,\n",
" beta=0.1,\n",
").to(device)\n",
"train_model_report_accuracy(\n",
" entropy_regularized_crf,\n",
" LR,\n",
" EPOCHS,\n",
" train_dataloader,\n",
" valid_dataloader,\n",
" pad_token_idx,\n",
" pos_vocab[pad_token],\n",
")\n"
],
"metadata": {
"id": "DmCPsmTtym3U",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "af6cb9d0-d026-478f-cf1f-d85f43ee596f"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"-------------------------\n",
"Epoch: 1 / 3\n",
"Development set accuracy: 0.9189360737800598\n",
"-------------------------\n",
"-------------------------\n",
"Epoch: 2 / 3\n",
"Development set accuracy: 0.915329098701477\n",
"-------------------------\n",
"-------------------------\n",
"Epoch: 3 / 3\n",
"Development set accuracy: 0.9194207787513733\n",
"-------------------------\n"
]
}
]
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "b17mHbJqer_O"
},
"execution_count": null,
"outputs": []
}
]
}
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
},
"accelerator": "GPU",
"gpuClass": "standard",
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"f432c0297e88426383f09f7bae595113": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HBoxModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HBoxModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HBoxView",
"box_style": "",
"children": [
"IPY_MODEL_8033cf3d0c77455e85dd93ce557f3a47",
"IPY_MODEL_71b3980870624b51b844ae4a1d80fe33",
"IPY_MODEL_b538c74275f74978afa1a2d5505e3f02"
],
"layout": "IPY_MODEL_c47ad738ff014c48934616b94a7a8c89"
}
},
"8033cf3d0c77455e85dd93ce557f3a47": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_27a907429c4749ccbeded0d43f163073",
"placeholder": "",
"style": "IPY_MODEL_bfe8870956384bb5a4ace0799e5ad81a",
"value": "Downloading: 100%"
}
},
"71b3980870624b51b844ae4a1d80fe33": {
"model_module": "@jupyter-widgets/controls",
"model_name": "FloatProgressModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "FloatProgressModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "ProgressView",
"bar_style": "success",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_1049de934dac494fb706f640234531a7",
"max": 231508,
"min": 0,
"orientation": "horizontal",
"style": "IPY_MODEL_ea3d9b1afa544e5b95737e030ec00ff6",
"value": 231508
}
},
"b538c74275f74978afa1a2d5505e3f02": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
Xet Storage Details
- Size:
- 138 kB
- Xet hash:
- 8c7d788c1c589188d67da6426cf2c5a950170fbb4de42a48d7a3d01b8288e6f5
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.