Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tomaarsen/3bfaa73c7876dce2b96b4590a4ce2ddc to your computer and use it in GitHub Desktop.
Save tomaarsen/3bfaa73c7876dce2b96b4590a4ce2ddc to your computer and use it in GitHub Desktop.
Snowflake_Arctic_trust_remote_code.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"gpuType": "T4",
"authorship_tag": "ABX9TyOZY48T0DyOCQli7a0KbJ6b",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
},
"accelerator": "GPU",
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"fda02efe489d40b9ab36c8ed58b5adf8": {
"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_c726de5cf479485bac275972a5566a0c",
"IPY_MODEL_1b8ebcd12b964e6ebdff18db4ecb810e",
"IPY_MODEL_e7491d4453674cf29e52449cb07af627"
],
"layout": "IPY_MODEL_94d4a4ff086e4475a36dc1947abde0a6"
}
},
"c726de5cf479485bac275972a5566a0c": {
"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_340650ac92204290b9825c533b9274e2",
"placeholder": "",
"style": "IPY_MODEL_d381479b71de46ffac35d5fe66a46253",
"value": "Downloading shards:   0%"
}
},
"1b8ebcd12b964e6ebdff18db4ecb810e": {
"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": "danger",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_bf145ee7a8754840aa8929033fad6330",
"max": 195,
"min": 0,
"orientation": "horizontal",
"style": "IPY_MODEL_9a0f6117f73c4b1ab866f7a711fb7525",
"value": 0
}
},
"e7491d4453674cf29e52449cb07af627": {
"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_68fb0033f11a4586ab958658e0455446",
"placeholder": "",
"style": "IPY_MODEL_619e4d5ba7374e5390ed2e1bd2031a72",
"value": " 0/195 [00:39<?, ?it/s]"
}
},
"94d4a4ff086e4475a36dc1947abde0a6": {
"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
}
},
"340650ac92204290b9825c533b9274e2": {
"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
}
},
"d381479b71de46ffac35d5fe66a46253": {
"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": ""
}
},
"bf145ee7a8754840aa8929033fad6330": {
"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
}
},
"9a0f6117f73c4b1ab866f7a711fb7525": {
"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": ""
}
},
"68fb0033f11a4586ab958658e0455446": {
"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
}
},
"619e4d5ba7374e5390ed2e1bd2031a72": {
"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": ""
}
},
"c0abdf66a96c4a948aa8c8f21b9de6a2": {
"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_0fe004a5d01c4b2db4ad55a3df0f4d44",
"IPY_MODEL_aa63fae62df3499aaf0a03eba81e632c",
"IPY_MODEL_6cff2c8114384095b6bdfdb9cc24ad94"
],
"layout": "IPY_MODEL_bc9d5ad32b974d6fb8c259c3bad0f3ae"
}
},
"0fe004a5d01c4b2db4ad55a3df0f4d44": {
"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_0c5f5d9058704251bc1ed525cb739088",
"placeholder": "",
"style": "IPY_MODEL_81810c6196c44fdf8ef4c680e6891282",
"value": "model-00001-of-00195.safetensors:  76%"
}
},
"aa63fae62df3499aaf0a03eba81e632c": {
"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": "danger",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_0afbb057bfe7482882e737c7ec921436",
"max": 4985725144,
"min": 0,
"orientation": "horizontal",
"style": "IPY_MODEL_b6cf90cff12d4adca91e1435fa812e29",
"value": 3774873240
}
},
"6cff2c8114384095b6bdfdb9cc24ad94": {
"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_7778dd1dc35b4b758e1124d8a259e4ee",
"placeholder": "",
"style": "IPY_MODEL_2eea4fac5192484b9cb86416978bc1d4",
"value": " 3.77G/4.99G [00:38<00:39, 31.0MB/s]"
}
},
"bc9d5ad32b974d6fb8c259c3bad0f3ae": {
"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
}
},
"0c5f5d9058704251bc1ed525cb739088": {
"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
}
},
"81810c6196c44fdf8ef4c680e6891282": {
"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": ""
}
},
"0afbb057bfe7482882e737c7ec921436": {
"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
}
},
"b6cf90cff12d4adca91e1435fa812e29": {
"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": ""
}
},
"7778dd1dc35b4b758e1124d8a259e4ee": {
"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
}
},
"2eea4fac5192484b9cb86416978bc1d4": {
"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": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/tomaarsen/3bfaa73c7876dce2b96b4590a4ce2ddc/snowflake_arctic_trust_remote_code.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "My_kChpllDpP",
"outputId": "daefc424-bca4-4b61-9f13-214bfed2ae0a"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"\u001b[33mWARNING: huggingface-hub 0.20.3 does not provide the extra 'hf_transfer'\u001b[0m\u001b[33m\n",
"\u001b[0m"
]
}
],
"source": [
"!pip install deepspeed>=0.14.2 huggingface_hub"
]
},
{
"cell_type": "code",
"source": [
"!pip install hf_transfer"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "xnzZAKoIn8TF",
"outputId": "1a17cb2b-2b8f-45cd-d902-5dae5036edd3"
},
"execution_count": 3,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Collecting hf_transfer\n",
" Downloading hf_transfer-0.1.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.4 MB)\n",
"\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/4.4 MB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[91m╸\u001b[0m\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.1/4.4 MB\u001b[0m \u001b[31m2.4 MB/s\u001b[0m eta \u001b[36m0:00:02\u001b[0m\r\u001b[2K \u001b[91m━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[90m╺\u001b[0m\u001b[90m━━━━━━━━━━━\u001b[0m \u001b[32m3.1/4.4 MB\u001b[0m \u001b[31m45.8 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K \u001b[91m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m \u001b[32m4.4/4.4 MB\u001b[0m \u001b[31m54.7 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m4.4/4.4 MB\u001b[0m \u001b[31m36.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[?25hInstalling collected packages: hf_transfer\n",
"Successfully installed hf_transfer-0.1.6\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"!pip install flash_attn"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "V4ZzMw64oLIe",
"outputId": "7d83d2b9-49d0-4988-9e66-07f9b1c8fd89"
},
"execution_count": 5,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Collecting flash_attn\n",
" Downloading flash_attn-2.5.7.tar.gz (2.5 MB)\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.5/2.5 MB\u001b[0m \u001b[31m15.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[?25h Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
"Requirement already satisfied: torch in /usr/local/lib/python3.10/dist-packages (from flash_attn) (2.2.1+cu121)\n",
"Collecting einops (from flash_attn)\n",
" Downloading einops-0.7.0-py3-none-any.whl (44 kB)\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m44.6/44.6 kB\u001b[0m \u001b[31m6.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[?25hRequirement already satisfied: packaging in /usr/local/lib/python3.10/dist-packages (from flash_attn) (24.0)\n",
"Requirement already satisfied: ninja in /usr/local/lib/python3.10/dist-packages (from flash_attn) (1.11.1.1)\n",
"Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (3.13.4)\n",
"Requirement already satisfied: typing-extensions>=4.8.0 in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (4.11.0)\n",
"Requirement already satisfied: sympy in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (1.12)\n",
"Requirement already satisfied: networkx in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (3.3)\n",
"Requirement already satisfied: jinja2 in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (3.1.3)\n",
"Requirement already satisfied: fsspec in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (2023.6.0)\n",
"Requirement already satisfied: nvidia-cuda-nvrtc-cu12==12.1.105 in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (12.1.105)\n",
"Requirement already satisfied: nvidia-cuda-runtime-cu12==12.1.105 in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (12.1.105)\n",
"Requirement already satisfied: nvidia-cuda-cupti-cu12==12.1.105 in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (12.1.105)\n",
"Requirement already satisfied: nvidia-cudnn-cu12==8.9.2.26 in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (8.9.2.26)\n",
"Requirement already satisfied: nvidia-cublas-cu12==12.1.3.1 in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (12.1.3.1)\n",
"Requirement already satisfied: nvidia-cufft-cu12==11.0.2.54 in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (11.0.2.54)\n",
"Requirement already satisfied: nvidia-curand-cu12==10.3.2.106 in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (10.3.2.106)\n",
"Requirement already satisfied: nvidia-cusolver-cu12==11.4.5.107 in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (11.4.5.107)\n",
"Requirement already satisfied: nvidia-cusparse-cu12==12.1.0.106 in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (12.1.0.106)\n",
"Requirement already satisfied: nvidia-nccl-cu12==2.19.3 in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (2.19.3)\n",
"Requirement already satisfied: nvidia-nvtx-cu12==12.1.105 in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (12.1.105)\n",
"Requirement already satisfied: triton==2.2.0 in /usr/local/lib/python3.10/dist-packages (from torch->flash_attn) (2.2.0)\n",
"Requirement already satisfied: nvidia-nvjitlink-cu12 in /usr/local/lib/python3.10/dist-packages (from nvidia-cusolver-cu12==11.4.5.107->torch->flash_attn) (12.4.127)\n",
"Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from jinja2->torch->flash_attn) (2.1.5)\n",
"Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.10/dist-packages (from sympy->torch->flash_attn) (1.3.0)\n",
"Building wheels for collected packages: flash_attn\n",
" Building wheel for flash_attn (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
" Created wheel for flash_attn: filename=flash_attn-2.5.7-cp310-cp310-linux_x86_64.whl size=120853563 sha256=bbe6f77fd0899f8a125a5bdcf734b660c4c88e81c9b51c7ce98ebeba44dc6fa0\n",
" Stored in directory: /root/.cache/pip/wheels/13/96/ed/bcac89c56b606421f99b45b16a94db5d0f2b6b4eaf8bac4d01\n",
"Successfully built flash_attn\n",
"Installing collected packages: einops, flash_attn\n",
"Successfully installed einops-0.7.0 flash_attn-2.5.7\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"!pip install accelerate"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "luDMtC2Qpb8t",
"outputId": "db1e702f-f964-4c33-be19-7d1e3c009517"
},
"execution_count": 7,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Collecting accelerate\n",
" Downloading accelerate-0.29.3-py3-none-any.whl (297 kB)\n",
"\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/297.6 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[91m━━━━━━━━\u001b[0m\u001b[90m╺\u001b[0m\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m61.4/297.6 kB\u001b[0m \u001b[31m2.2 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K \u001b[91m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[90m╺\u001b[0m\u001b[90m━━━━━\u001b[0m \u001b[32m256.0/297.6 kB\u001b[0m \u001b[31m3.6 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m297.6/297.6 kB\u001b[0m \u001b[31m3.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[?25hRequirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.10/dist-packages (from accelerate) (1.25.2)\n",
"Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.10/dist-packages (from accelerate) (24.0)\n",
"Requirement already satisfied: psutil in /usr/local/lib/python3.10/dist-packages (from accelerate) (5.9.5)\n",
"Requirement already satisfied: pyyaml in /usr/local/lib/python3.10/dist-packages (from accelerate) (6.0.1)\n",
"Requirement already satisfied: torch>=1.10.0 in /usr/local/lib/python3.10/dist-packages (from accelerate) (2.2.1+cu121)\n",
"Requirement already satisfied: huggingface-hub in /usr/local/lib/python3.10/dist-packages (from accelerate) (0.20.3)\n",
"Requirement already satisfied: safetensors>=0.3.1 in /usr/local/lib/python3.10/dist-packages (from accelerate) (0.4.3)\n",
"Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (3.13.4)\n",
"Requirement already satisfied: typing-extensions>=4.8.0 in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (4.11.0)\n",
"Requirement already satisfied: sympy in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (1.12)\n",
"Requirement already satisfied: networkx in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (3.3)\n",
"Requirement already satisfied: jinja2 in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (3.1.3)\n",
"Requirement already satisfied: fsspec in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (2023.6.0)\n",
"Requirement already satisfied: nvidia-cuda-nvrtc-cu12==12.1.105 in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (12.1.105)\n",
"Requirement already satisfied: nvidia-cuda-runtime-cu12==12.1.105 in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (12.1.105)\n",
"Requirement already satisfied: nvidia-cuda-cupti-cu12==12.1.105 in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (12.1.105)\n",
"Requirement already satisfied: nvidia-cudnn-cu12==8.9.2.26 in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (8.9.2.26)\n",
"Requirement already satisfied: nvidia-cublas-cu12==12.1.3.1 in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (12.1.3.1)\n",
"Requirement already satisfied: nvidia-cufft-cu12==11.0.2.54 in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (11.0.2.54)\n",
"Requirement already satisfied: nvidia-curand-cu12==10.3.2.106 in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (10.3.2.106)\n",
"Requirement already satisfied: nvidia-cusolver-cu12==11.4.5.107 in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (11.4.5.107)\n",
"Requirement already satisfied: nvidia-cusparse-cu12==12.1.0.106 in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (12.1.0.106)\n",
"Requirement already satisfied: nvidia-nccl-cu12==2.19.3 in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (2.19.3)\n",
"Requirement already satisfied: nvidia-nvtx-cu12==12.1.105 in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (12.1.105)\n",
"Requirement already satisfied: triton==2.2.0 in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->accelerate) (2.2.0)\n",
"Requirement already satisfied: nvidia-nvjitlink-cu12 in /usr/local/lib/python3.10/dist-packages (from nvidia-cusolver-cu12==11.4.5.107->torch>=1.10.0->accelerate) (12.4.127)\n",
"Requirement already satisfied: requests in /usr/local/lib/python3.10/dist-packages (from huggingface-hub->accelerate) (2.31.0)\n",
"Requirement already satisfied: tqdm>=4.42.1 in /usr/local/lib/python3.10/dist-packages (from huggingface-hub->accelerate) (4.66.2)\n",
"Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from jinja2->torch>=1.10.0->accelerate) (2.1.5)\n",
"Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests->huggingface-hub->accelerate) (3.3.2)\n",
"Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests->huggingface-hub->accelerate) (3.7)\n",
"Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests->huggingface-hub->accelerate) (2.0.7)\n",
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests->huggingface-hub->accelerate) (2024.2.2)\n",
"Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.10/dist-packages (from sympy->torch>=1.10.0->accelerate) (1.3.0)\n",
"Installing collected packages: accelerate\n",
"Successfully installed accelerate-0.29.3\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"import os\n",
"# enable hf_transfer for faster ckpt download\n",
"os.environ[\"HF_HUB_ENABLE_HF_TRANSFER\"] = \"1\"\n",
"\n",
"from dataclasses import dataclass\n",
"import torch\n",
"from transformers import AutoModelForCausalLM, AutoTokenizer\n",
"\n",
"tokenizer = AutoTokenizer.from_pretrained(\n",
" \"Snowflake/snowflake-arctic-instruct\",\n",
" trust_remote_code=True,\n",
" revision=\"refs/pr/3\",\n",
")\n",
"\n",
"tokenized_example = tokenizer([\"This is some example text\"])\n",
"print(f\"{tokenized_example=}\")\n",
"\n",
"@dataclass\n",
"class ArcticQuantizationConfig:\n",
" q_bits: int = 8\n",
" rounding: str = \"nearest\"\n",
" mantissa_bits: int = 3\n",
" group_size: int = 512\n",
"\n",
"quant_config = ArcticQuantizationConfig(q_bits=8)\n",
"\n",
"model = AutoModelForCausalLM.from_pretrained(\n",
" \"Snowflake/snowflake-arctic-instruct\",\n",
" trust_remote_code=True,\n",
" low_cpu_mem_usage=True,\n",
" device_map=\"auto\",\n",
" ds_quantization_config=quant_config,\n",
" max_memory={i: \"150GiB\" for i in range(8)},\n",
" torch_dtype=torch.bfloat16,\n",
" revision=\"refs/pr/3\",\n",
")\n",
"\n",
"messages = [{\"role\": \"user\", \"content\": \"What is 1 + 1 \"}]\n",
"input_ids = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors=\"pt\").to(\"cuda\")\n",
"\n",
"outputs = model.generate(input_ids=input_ids, max_new_tokens=20)\n",
"print(tokenizer.decode(outputs[0]))"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 697,
"referenced_widgets": [
"fda02efe489d40b9ab36c8ed58b5adf8",
"c726de5cf479485bac275972a5566a0c",
"1b8ebcd12b964e6ebdff18db4ecb810e",
"e7491d4453674cf29e52449cb07af627",
"94d4a4ff086e4475a36dc1947abde0a6",
"340650ac92204290b9825c533b9274e2",
"d381479b71de46ffac35d5fe66a46253",
"bf145ee7a8754840aa8929033fad6330",
"9a0f6117f73c4b1ab866f7a711fb7525",
"68fb0033f11a4586ab958658e0455446",
"619e4d5ba7374e5390ed2e1bd2031a72",
"c0abdf66a96c4a948aa8c8f21b9de6a2",
"0fe004a5d01c4b2db4ad55a3df0f4d44",
"aa63fae62df3499aaf0a03eba81e632c",
"6cff2c8114384095b6bdfdb9cc24ad94",
"bc9d5ad32b974d6fb8c259c3bad0f3ae",
"0c5f5d9058704251bc1ed525cb739088",
"81810c6196c44fdf8ef4c680e6891282",
"0afbb057bfe7482882e737c7ec921436",
"b6cf90cff12d4adca91e1435fa812e29",
"7778dd1dc35b4b758e1124d8a259e4ee",
"2eea4fac5192484b9cb86416978bc1d4"
]
},
"id": "pvC7lIhElMAO",
"outputId": "217af783-234d-45a4-d9f9-cf102f571174"
},
"execution_count": 1,
"outputs": [
{
"output_type": "stream",
"name": "stderr",
"text": [
"/usr/local/lib/python3.10/dist-packages/huggingface_hub/utils/_token.py:88: UserWarning: \n",
"The secret `HF_TOKEN` does not exist in your Colab secrets.\n",
"To authenticate with the Hugging Face Hub, create a token in your settings tab (https://huggingface.co/settings/tokens), set it as secret in your Google Colab and restart your session.\n",
"You will be able to reuse this secret in all of your notebooks.\n",
"Please note that authentication is recommended but still optional to access public models or datasets.\n",
" warnings.warn(\n"
]
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"tokenized_example={'input_ids': [[31998, 910, 338, 777, 1342, 1426]], 'attention_mask': [[1, 1, 1, 1, 1, 1]]}\n",
"[2024-04-24 15:13:02,357] [INFO] [real_accelerator.py:203:get_accelerator] Setting ds_accelerator to cuda (auto detect)\n",
"\u001b[93m [WARNING] \u001b[0m async_io requires the dev libaio .so object and headers but these were not found.\n",
"\u001b[93m [WARNING] \u001b[0m async_io: please install the libaio-dev package with apt\n",
"\u001b[93m [WARNING] \u001b[0m If libaio is already installed (perhaps from source), try setting the CFLAGS and LDFLAGS environment variables to where it can be found.\n",
"\u001b[93m [WARNING] \u001b[0m Please specify the CUTLASS repo directory as environment variable $CUTLASS_PATH\n",
"\u001b[93m [WARNING] \u001b[0m NVIDIA Inference is only supported on Ampere and newer architectures\n",
"\u001b[93m [WARNING] \u001b[0m sparse_attn requires a torch version >= 1.5 and < 2.0 but detected 2.2\n",
"\u001b[93m [WARNING] \u001b[0m using untested triton version (2.2.0), only 1.0.0 is known to be compatible\n"
]
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"Downloading shards: 0%| | 0/195 [00:00<?, ?it/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "fda02efe489d40b9ab36c8ed58b5adf8"
}
},
"metadata": {}
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"model-00001-of-00195.safetensors: 0%| | 0.00/4.99G [00:00<?, ?B/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "c0abdf66a96c4a948aa8c8f21b9de6a2"
}
},
"metadata": {}
},
{
"output_type": "error",
"ename": "KeyboardInterrupt",
"evalue": "",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mKeyboardInterrupt\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-1-61992f9d7087>\u001b[0m in \u001b[0;36m<cell line: 27>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 25\u001b[0m \u001b[0mquant_config\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mArcticQuantizationConfig\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mq_bits\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m8\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 26\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 27\u001b[0;31m model = AutoModelForCausalLM.from_pretrained(\n\u001b[0m\u001b[1;32m 28\u001b[0m \u001b[0;34m\"Snowflake/snowflake-arctic-instruct\"\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 29\u001b[0m \u001b[0mtrust_remote_code\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/transformers/models/auto/auto_factory.py\u001b[0m in \u001b[0;36mfrom_pretrained\u001b[0;34m(cls, pretrained_model_name_or_path, *model_args, **kwargs)\u001b[0m\n\u001b[1;32m 556\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 557\u001b[0m \u001b[0mcls\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mregister\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mconfig\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__class__\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmodel_class\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mexist_ok\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 558\u001b[0;31m return model_class.from_pretrained(\n\u001b[0m\u001b[1;32m 559\u001b[0m \u001b[0mpretrained_model_name_or_path\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0mmodel_args\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mconfig\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mconfig\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mhub_kwargs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 560\u001b[0m )\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/transformers/modeling_utils.py\u001b[0m in \u001b[0;36mfrom_pretrained\u001b[0;34m(cls, pretrained_model_name_or_path, config, cache_dir, ignore_mismatched_sizes, force_download, local_files_only, token, revision, use_safetensors, *model_args, **kwargs)\u001b[0m\n\u001b[1;32m 3434\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mis_sharded\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3435\u001b[0m \u001b[0;31m# rsolved_archive_file becomes a list of files that point to the different checkpoint shards in this case.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 3436\u001b[0;31m resolved_archive_file, sharded_metadata = get_checkpoint_shard_files(\n\u001b[0m\u001b[1;32m 3437\u001b[0m \u001b[0mpretrained_model_name_or_path\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3438\u001b[0m \u001b[0mresolved_archive_file\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/transformers/utils/hub.py\u001b[0m in \u001b[0;36mget_checkpoint_shard_files\u001b[0;34m(pretrained_model_name_or_path, index_filename, cache_dir, force_download, proxies, resume_download, local_files_only, token, user_agent, revision, subfolder, _commit_hash, **deprecated_kwargs)\u001b[0m\n\u001b[1;32m 1036\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1037\u001b[0m \u001b[0;31m# Load from URL\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1038\u001b[0;31m cached_filename = cached_file(\n\u001b[0m\u001b[1;32m 1039\u001b[0m \u001b[0mpretrained_model_name_or_path\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1040\u001b[0m \u001b[0mshard_filename\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/transformers/utils/hub.py\u001b[0m in \u001b[0;36mcached_file\u001b[0;34m(path_or_repo_id, filename, cache_dir, force_download, resume_download, proxies, token, revision, local_files_only, subfolder, repo_type, user_agent, _raise_exceptions_for_gated_repo, _raise_exceptions_for_missing_entries, _raise_exceptions_for_connection_errors, _commit_hash, **deprecated_kwargs)\u001b[0m\n\u001b[1;32m 396\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 397\u001b[0m \u001b[0;31m# Load from URL or cache if already cached\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 398\u001b[0;31m resolved_file = hf_hub_download(\n\u001b[0m\u001b[1;32m 399\u001b[0m \u001b[0mpath_or_repo_id\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 400\u001b[0m \u001b[0mfilename\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/huggingface_hub/utils/_validators.py\u001b[0m in \u001b[0;36m_inner_fn\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m 116\u001b[0m \u001b[0mkwargs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0msmoothly_deprecate_use_auth_token\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfn_name\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mfn\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__name__\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mhas_token\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mhas_token\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mkwargs\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 117\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 118\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfn\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 119\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 120\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0m_inner_fn\u001b[0m \u001b[0;31m# type: ignore\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/huggingface_hub/file_download.py\u001b[0m in \u001b[0;36mhf_hub_download\u001b[0;34m(repo_id, filename, subfolder, repo_type, revision, library_name, library_version, cache_dir, local_dir, local_dir_use_symlinks, user_agent, force_download, force_filename, proxies, etag_timeout, resume_download, token, local_files_only, legacy_cache_layout, endpoint)\u001b[0m\n\u001b[1;32m 1455\u001b[0m \u001b[0m_check_disk_space\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mexpected_size\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mlocal_dir\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1456\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1457\u001b[0;31m http_get(\n\u001b[0m\u001b[1;32m 1458\u001b[0m \u001b[0murl_to_download\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1459\u001b[0m \u001b[0mtemp_file\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/huggingface_hub/file_download.py\u001b[0m in \u001b[0;36mhttp_get\u001b[0;34m(url, temp_file, proxies, resume_size, headers, expected_size, _nb_retries)\u001b[0m\n\u001b[1;32m 496\u001b[0m )\n\u001b[1;32m 497\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 498\u001b[0;31m hf_transfer.download(\n\u001b[0m\u001b[1;32m 499\u001b[0m \u001b[0murl\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0murl\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 500\u001b[0m \u001b[0mfilename\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mtemp_file\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/tqdm/notebook.py\u001b[0m in \u001b[0;36mupdate\u001b[0;34m(self, n)\u001b[0m\n\u001b[1;32m 260\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mupdate\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mn\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 261\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 262\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0msuper\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtqdm_notebook\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mupdate\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mn\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mn\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 263\u001b[0m \u001b[0;31m# NB: except ... [ as ...] breaks IPython async KeyboardInterrupt\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 264\u001b[0m \u001b[0;32mexcept\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;31m# NOQA\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mKeyboardInterrupt\u001b[0m: "
]
}
]
},
{
"cell_type": "code",
"source": [
"!cat ~/.cache/huggingface/modules/transformers_modules/Snowflake/snowflake-arctic-instruct/f9281b708c4e07b2348d2f7d71a9816d32eca8a4/configuration_arctic.py"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Y1UTOFlMn9V0",
"outputId": "606fd47a-1cbc-421c-afc4-b0983c8eb8cb"
},
"execution_count": 10,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"# Copyright 2023 Snowflake AI and the HuggingFace Inc. team. All rights reserved.\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# http://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License.\n",
"\"\"\" Arctic model configuration\"\"\"\n",
"\n",
"from dataclasses import asdict, dataclass\n",
"from typing import Any, Dict\n",
"\n",
"from transformers.configuration_utils import PretrainedConfig\n",
"from transformers.utils import logging\n",
"\n",
"\n",
"logger = logging.get_logger(__name__)\n",
"\n",
"ARCTIC_PRETRAINED_CONFIG_ARCHIVE_MAP = {\n",
" \"arctic\": \"https://huggingface.co/Snowflake/snowflake-arctic-instruct/tree/main/config.json\",\n",
"}\n",
"\n",
"\n",
"@dataclass\n",
"class ArcticLoraConfig:\n",
" lora_r: int = 64\n",
" lora_alpha: float = 16\n",
" shard_base_weights: bool = False\n",
"\n",
"\n",
"@dataclass\n",
"class ArcticQuantizationConfig:\n",
" q_bits: int = 8\n",
" rounding: str = \"nearest\"\n",
" mantissa_bits: int = 3\n",
" group_size: int = 512\n",
"\n",
"\n",
"class ArcticConfig(PretrainedConfig):\n",
" r\"\"\"\n",
" This is the configuration class to store the configuration of a [`ArcticModel`]. It is used to instantiate an\n",
" Arctic model according to the specified arguments, defining the model architecture. Instantiating a configuration\n",
" with the defaults will yield a similar configuration to that of the #TODO(rsamdani): add what model has the default config..\n",
"\n",
"\n",
" Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the\n",
" documentation from [`PretrainedConfig`] for more information.\n",
"\n",
"\n",
" Args:\n",
" vocab_size (`int`, *optional*, defaults to 32000):\n",
" Vocabulary size of the Arctic model. Defines the number of different tokens that can be represented by the\n",
" `inputs_ids` passed when calling [`ArcticModel`]\n",
" hidden_size (`int`, *optional*, defaults to 4096):\n",
" Dimension of the hidden representations.\n",
" intermediate_size (`int`, *optional*, defaults to 14336):\n",
" Dimension of the MLP representations.\n",
" num_hidden_layers (`int`, *optional*, defaults to 32):\n",
" Number of hidden layers in the Transformer encoder.\n",
" num_attention_heads (`int`, *optional*, defaults to 32):\n",
" Number of attention heads for each attention layer in the Transformer encoder.\n",
" num_key_value_heads (`int`, *optional*, defaults to 8):\n",
" This is the number of key_value heads that should be used to implement Grouped Query Attention. If\n",
" `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if\n",
" `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When\n",
" converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed\n",
" by meanpooling all the original heads within that group. For more details checkout [this\n",
" paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `8`.\n",
" hidden_act (`str` or `function`, *optional*, defaults to `\"silu\"`):\n",
" The non-linear activation function (function or string) in the decoder.\n",
" max_position_embeddings (`int`, *optional*, defaults to `4096*32`):\n",
" The maximum sequence length that this model might ever be used with. Arctic's sliding window attention\n",
" allows sequence of up to 4096*32 tokens.\n",
" initializer_range (`float`, *optional*, defaults to 0.02):\n",
" The standard deviation of the truncated_normal_initializer for initializing all weight matrices.\n",
" rms_norm_eps (`float`, *optional*, defaults to 1e-05):\n",
" The epsilon used by the rms normalization layers.\n",
" use_cache (`bool`, *optional*, defaults to `True`):\n",
" Whether or not the model should return the last key/values attentions (not used by all models). Only\n",
" relevant if `config.is_decoder=True`.\n",
" pad_token_id (`int`, *optional*):\n",
" The id of the padding token.\n",
" bos_token_id (`int`, *optional*, defaults to 1):\n",
" The id of the \"beginning-of-sequence\" token.\n",
" eos_token_id (`int`, *optional*, defaults to 2):\n",
" The id of the \"end-of-sequence\" token.\n",
" tie_word_embeddings (`bool`, *optional*, defaults to `False`):\n",
" Whether the model's input and output word embeddings should be tied.\n",
" rope_theta (`float`, *optional*, defaults to 1000000.0):\n",
" The base period of the RoPE embeddings.\n",
" sliding_window (`int`, *optional*):\n",
" Sliding window attention window size. If not specified, will default to `4096`.\n",
" attention_dropout (`float`, *optional*, defaults to 0.0):\n",
" The dropout ratio for the attention probabilities.\n",
" num_experts_per_tok (`int`, *optional*, defaults to 2):\n",
" The number of experts to root per-token, can be also interpreted as the `top-p` routing\n",
" parameter\n",
" num_local_experts (`int`, *optional*, defaults to 8):\n",
" Number of experts per Sparse MLP layer.\n",
" router_aux_loss_coef (`float`, *optional*, defaults to 0.001):\n",
" The aux loss factor for the total loss.\n",
"\n",
" ```python\n",
" >>> from transformers import ArcticModel, ArcticConfig\n",
"\n",
" >>> # Initializing a Arctic 7B style configuration TODO(rsamdani): verify which model does the default configuration correspond to.\n",
" >>> configuration = ArcticConfig()\n",
"\n",
" >>> # Initializing a model from the Arctic 7B style configuration\n",
" >>> model = ArcticModel(configuration)\n",
"\n",
" >>> # Accessing the model configuration\n",
" >>> configuration = model.config\n",
" ```\"\"\"\n",
"\n",
" model_type = \"arctic\"\n",
" keys_to_ignore_at_inference = [\"past_key_values\"]\n",
"\n",
" def __init__(\n",
" self,\n",
" vocab_size=32000,\n",
" hidden_size=4096,\n",
" intermediate_size=14336,\n",
" num_hidden_layers=32,\n",
" num_attention_heads=32,\n",
" num_key_value_heads=None,\n",
" hidden_act=\"silu\",\n",
" max_position_embeddings=4096,\n",
" initializer_range=0.02,\n",
" rms_norm_eps=1e-5,\n",
" use_cache=True,\n",
" pad_token_id=None,\n",
" bos_token_id=1,\n",
" eos_token_id=2,\n",
" tie_word_embeddings=False,\n",
" rope_theta=1e6,\n",
" sliding_window=None,\n",
" attention_dropout=0.0,\n",
" num_experts_per_tok=1,\n",
" num_local_experts=8,\n",
" router_aux_loss_coef=0.001,\n",
" moe_layer_frequency=2,\n",
" parallel_attn_mlp_res=False,\n",
" moe_train_capacity_factor=1,\n",
" moe_eval_capacity_factor=1,\n",
" enable_expert_tensor_parallelism=False,\n",
" moe_min_capacity=0,\n",
" moe_token_dropping=True,\n",
" quantization=None,\n",
" **kwargs,\n",
" ):\n",
" self.vocab_size = vocab_size\n",
" self.max_position_embeddings = max_position_embeddings\n",
" self.hidden_size = hidden_size\n",
" self.intermediate_size = intermediate_size\n",
" self.num_hidden_layers = num_hidden_layers\n",
" self.num_attention_heads = num_attention_heads\n",
" self.sliding_window = sliding_window\n",
"\n",
" # for backward compatibility\n",
" if num_key_value_heads is None:\n",
" num_key_value_heads = num_attention_heads\n",
"\n",
" self.num_key_value_heads = num_key_value_heads\n",
" self.hidden_act = hidden_act\n",
" self.initializer_range = initializer_range\n",
" self.rms_norm_eps = rms_norm_eps\n",
" self.use_cache = use_cache\n",
" self.rope_theta = rope_theta\n",
" self.attention_dropout = attention_dropout\n",
"\n",
" self.num_experts_per_tok = num_experts_per_tok\n",
" self.num_local_experts = num_local_experts\n",
" self.router_aux_loss_coef = router_aux_loss_coef\n",
" self.moe_layer_frequency = moe_layer_frequency\n",
" self.moe_train_capacity_factor = moe_train_capacity_factor\n",
" self.moe_eval_capacity_factor = moe_eval_capacity_factor\n",
" self.enable_expert_tensor_parallelism = enable_expert_tensor_parallelism\n",
" self.moe_min_capacity = moe_min_capacity\n",
" self.moe_token_dropping = moe_token_dropping\n",
" self.parallel_attn_mlp_res = parallel_attn_mlp_res\n",
" if isinstance(quantization, dict):\n",
" self.quantization = ArcticQuantizationConfig(**quantization)\n",
" else:\n",
" self.quantization = quantization\n",
"\n",
" super().__init__(\n",
" pad_token_id=pad_token_id,\n",
" bos_token_id=bos_token_id,\n",
" eos_token_id=eos_token_id,\n",
" tie_word_embeddings=tie_word_embeddings,\n",
" **kwargs,\n",
" )\n",
"\n",
" @classmethod\n",
" def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> \"ArcticConfig\":\n",
" result = super().from_dict(config_dict, **kwargs)\n",
" if isinstance(result, tuple):\n",
" config = result[0]\n",
" else:\n",
" config = result\n",
" if isinstance(config.quantization, dict):\n",
" config.quantization = ArcticQuantizationConfig(**config.quantization)\n",
" return result\n",
"\n",
" def to_dict(self) -> Dict[str, Any]:\n",
" ret = super().to_dict()\n",
" if isinstance(ret[\"quantization\"], ArcticQuantizationConfig):\n",
" ret[\"quantization\"] = asdict(ret[\"quantization\"])\n",
" return ret\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"!cat ~/.cache/huggingface/modules/transformers_modules/Snowflake/snowflake-arctic-instruct/f9281b708c4e07b2348d2f7d71a9816d32eca8a4/modeling_arctic.py"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "9VSEIBrppxuH",
"outputId": "491164bb-3188-4388-9992-62f762686c55"
},
"execution_count": 13,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"# coding=utf-8\n",
"# Copyright 2023 Mistral AI and the HuggingFace Inc. team. All rights reserved.\n",
"#\n",
"# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX\n",
"# and OPT implementations in this library. It has been modified from its\n",
"# original forms to accommodate minor architectural differences compared\n",
"# to GPT-NeoX and OPT used by the Meta AI team that trained the model.\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# http://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License.\n",
"\"\"\" PyTorch Arctic model.\"\"\"\n",
"import copy\n",
"import inspect\n",
"import time\n",
"import math\n",
"import warnings\n",
"import re\n",
"from typing import List, Optional, Tuple, Union\n",
"\n",
"import deepspeed\n",
"import torch\n",
"import torch.nn.functional as F\n",
"import torch.utils.checkpoint\n",
"from torch import nn\n",
"from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss\n",
"\n",
"from transformers.activations import ACT2FN\n",
"from transformers.cache_utils import Cache, DynamicCache\n",
"from transformers.modeling_attn_mask_utils import (\n",
" _prepare_4d_causal_attention_mask,\n",
" _prepare_4d_causal_attention_mask_for_sdpa,\n",
")\n",
"from transformers.modeling_outputs import (\n",
" MoeCausalLMOutputWithPast,\n",
" MoeModelOutputWithPast,\n",
" SequenceClassifierOutputWithPast,\n",
")\n",
"from transformers.modeling_utils import PreTrainedModel\n",
"from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_13\n",
"from transformers.utils import (\n",
" add_start_docstrings,\n",
" add_start_docstrings_to_model_forward,\n",
" is_flash_attn_2_available,\n",
" is_flash_attn_greater_or_equal_2_10,\n",
" logging,\n",
" replace_return_docstrings,\n",
")\n",
"from transformers.utils.import_utils import is_torch_fx_available\n",
"from .configuration_arctic import ArcticConfig\n",
"from transformers.integrations.deepspeed import is_deepspeed_available \n",
"from transformers.utils.versions import require_version\n",
"\n",
"if is_deepspeed_available():\n",
" from deepspeed.moe.layer import MoE \n",
" # Note that below will crash if there is an available deepspeed that does not have ds_linear.\n",
" try:\n",
" import deepspeed.linear as ds_linear\n",
" except Exception:\n",
" pass\n",
"else:\n",
" MoE = None\n",
"\n",
"if is_flash_attn_2_available():\n",
" from flash_attn import flash_attn_func, flash_attn_varlen_func\n",
" from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa\n",
"\n",
" _flash_supports_window_size = \"window_size\" in list(inspect.signature(flash_attn_func).parameters)\n",
"\n",
"# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.\n",
"# It means that the function will not be traced through and simply appear as a node in the graph.\n",
"if is_torch_fx_available():\n",
" if not is_torch_greater_or_equal_than_1_13:\n",
" import torch.fx\n",
"\n",
" _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)\n",
"\n",
"\n",
"logger = logging.get_logger(__name__)\n",
"\n",
"_CONFIG_FOR_DOC = \"ArcticConfig\"\n",
"USE_DEEPSPEED_MOE_ARG = \"use_deepspeed_moe_implementation\"\n",
"MOE_EXPERT_PARALLEL_SIZE_ARG = \"moe_expert_parallel_size\"\n",
"DEEPSPEED_QUANTIZATION_CONFIG = \"deepspeed_quantization\"\n",
"DEEPSPEED_LORA_CONFIG = \"deepspeed_lora\"\n",
"QUANTIZATION_CONFIG = \"ds_quantization_config\"\n",
"\n",
"# REQUIRED_DEEPSPEED_VERSION = \"deepspeed>0.14.5\"\n",
"# def is_deepspeed_valid_and_available(raise_error=False, error_msg=\"\"):\n",
"# available_and_valid = True\n",
"# if not is_deepspeed_available():\n",
"# available_and_valid = False\n",
"# if raise_error:\n",
"# raise ValueError(f\"DeepSpeed is required for this feature, {error_msg}\")\n",
"# else:\n",
" \n",
"# return available_and_valid\n",
"\n",
"def load_balancing_loss_func(\n",
" gate_logits: torch.Tensor, num_experts: torch.Tensor = None, top_k=4, attention_mask: Optional[torch.Tensor] = None\n",
") -> float:\n",
" r\"\"\"\n",
" Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.\n",
"\n",
" See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss\n",
" function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between\n",
" experts is too unbalanced.\n",
"\n",
" Args:\n",
" gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):\n",
" Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of\n",
" shape [batch_size X sequence_length, num_experts].\n",
" attention_mask (`torch.Tensor`, None):\n",
" The attention_mask used in forward function\n",
" shape [batch_size X sequence_length] if not None.\n",
" num_experts (`int`, *optional*):\n",
" Number of experts\n",
"\n",
" Returns:\n",
" The auxiliary loss.\n",
" \"\"\"\n",
" if gate_logits is None or not isinstance(gate_logits, tuple):\n",
" return 0\n",
"\n",
" if isinstance(gate_logits, tuple):\n",
" compute_device = gate_logits[0].device\n",
" concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)\n",
"\n",
" routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)\n",
"\n",
" _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)\n",
"\n",
" expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)\n",
"\n",
" if attention_mask is None:\n",
" # Compute the percentage of tokens routed to each experts\n",
" tokens_per_expert = torch.mean(expert_mask.float(), dim=0)\n",
"\n",
" # Compute the average probability of routing to these experts\n",
" router_prob_per_expert = torch.mean(routing_weights, dim=0)\n",
" else:\n",
" batch_size, sequence_length = attention_mask.shape\n",
" num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)\n",
"\n",
" # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask\n",
" expert_attention_mask = (\n",
" attention_mask[None, :, :, None, None]\n",
" .expand((num_hidden_layers, batch_size, sequence_length, 2, num_experts))\n",
" .reshape(-1, 2, num_experts)\n",
" .to(compute_device)\n",
" )\n",
"\n",
" # Compute the percentage of tokens routed to each experts\n",
" tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(\n",
" expert_attention_mask, dim=0\n",
" )\n",
"\n",
" # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert\n",
" router_per_expert_attention_mask = (\n",
" attention_mask[None, :, :, None]\n",
" .expand((num_hidden_layers, batch_size, sequence_length, num_experts))\n",
" .reshape(-1, num_experts)\n",
" .to(compute_device)\n",
" )\n",
"\n",
" # Compute the average probability of routing to these experts\n",
" router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(\n",
" router_per_expert_attention_mask, dim=0\n",
" )\n",
"\n",
" overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))\n",
" return overall_loss * num_experts\n",
"\n",
"\n",
"# Copied from transformers.models.llama.modeling_llama._get_unpad_data\n",
"def _get_unpad_data(attention_mask):\n",
" seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)\n",
" indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()\n",
" max_seqlen_in_batch = seqlens_in_batch.max().item()\n",
" cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))\n",
" return (\n",
" indices,\n",
" cu_seqlens,\n",
" max_seqlen_in_batch,\n",
" )\n",
"\n",
"\n",
"# Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Arctic\n",
"class ArcticRMSNorm(nn.Module):\n",
" def __init__(self, hidden_size, eps=1e-6):\n",
" \"\"\"\n",
" ArcticRMSNorm is equivalent to T5LayerNorm\n",
" \"\"\"\n",
" super().__init__()\n",
" self.weight = nn.Parameter(torch.ones(hidden_size))\n",
" self.variance_epsilon = eps\n",
"\n",
" def forward(self, hidden_states):\n",
" input_dtype = hidden_states.dtype\n",
" hidden_states = hidden_states.to(torch.float32)\n",
" variance = hidden_states.pow(2).mean(-1, keepdim=True)\n",
" hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)\n",
" return self.weight * hidden_states.to(input_dtype)\n",
"\n",
"\n",
"# Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Arctic\n",
"class ArcticRotaryEmbedding(nn.Module):\n",
" def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):\n",
" super().__init__()\n",
"\n",
" self.dim = dim\n",
" self.max_position_embeddings = max_position_embeddings\n",
" self.base = base\n",
" inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))\n",
" self.register_buffer(\"inv_freq\", inv_freq, persistent=False)\n",
"\n",
" # Build here to make `torch.jit.trace` work.\n",
" self._set_cos_sin_cache(\n",
" seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()\n",
" )\n",
"\n",
" def _set_cos_sin_cache(self, seq_len, device, dtype):\n",
" self.max_seq_len_cached = seq_len\n",
" t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)\n",
"\n",
" freqs = torch.outer(t, self.inv_freq)\n",
" # Different from paper, but it uses a different permutation in order to obtain the same calculation\n",
" emb = torch.cat((freqs, freqs), dim=-1)\n",
" self.register_buffer(\"cos_cached\", emb.cos().to(dtype), persistent=False)\n",
" self.register_buffer(\"sin_cached\", emb.sin().to(dtype), persistent=False)\n",
"\n",
" def forward(self, x, seq_len=None):\n",
" # x: [bs, num_attention_heads, seq_len, head_size]\n",
" if seq_len > self.max_seq_len_cached:\n",
" self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)\n",
"\n",
" return (\n",
" self.cos_cached[:seq_len].to(dtype=x.dtype),\n",
" self.sin_cached[:seq_len].to(dtype=x.dtype),\n",
" )\n",
"\n",
"\n",
"# Copied from transformers.models.llama.modeling_llama.rotate_half\n",
"def rotate_half(x):\n",
" \"\"\"Rotates half the hidden dims of the input.\"\"\"\n",
" x1 = x[..., : x.shape[-1] // 2]\n",
" x2 = x[..., x.shape[-1] // 2 :]\n",
" return torch.cat((-x2, x1), dim=-1)\n",
"\n",
"\n",
"# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb\n",
"def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):\n",
" \"\"\"Applies Rotary Position Embedding to the query and key tensors.\n",
"\n",
" Args:\n",
" q (`torch.Tensor`): The query tensor.\n",
" k (`torch.Tensor`): The key tensor.\n",
" cos (`torch.Tensor`): The cosine part of the rotary embedding.\n",
" sin (`torch.Tensor`): The sine part of the rotary embedding.\n",
" position_ids (`torch.Tensor`):\n",
" The position indices of the tokens corresponding to the query and key tensors. For example, this can be\n",
" used to pass offsetted position ids when working with a KV-cache.\n",
" unsqueeze_dim (`int`, *optional*, defaults to 1):\n",
" The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and\n",
" sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note\n",
" that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and\n",
" k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes\n",
" cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have\n",
" the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.\n",
" Returns:\n",
" `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.\n",
" \"\"\"\n",
" cos = cos[position_ids].unsqueeze(unsqueeze_dim)\n",
" sin = sin[position_ids].unsqueeze(unsqueeze_dim)\n",
" q_embed = (q * cos) + (rotate_half(q) * sin)\n",
" k_embed = (k * cos) + (rotate_half(k) * sin)\n",
" return q_embed, k_embed\n",
"\n",
"\n",
"# Copied from transformers.models.llama.modeling_llama.repeat_kv\n",
"def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:\n",
" \"\"\"\n",
" This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,\n",
" num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)\n",
" \"\"\"\n",
" batch, num_key_value_heads, slen, head_dim = hidden_states.shape\n",
" if n_rep == 1:\n",
" return hidden_states\n",
" hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)\n",
" return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)\n",
"\n",
"\n",
"# Copied from transformers.models.mistral.modeling_mistral.MistralAttention with Mistral->Arctic\n",
"class ArcticAttention(nn.Module):\n",
" \"\"\"\n",
" Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer\n",
" and \"Generating Long Sequences with Sparse Transformers\".\n",
" \"\"\"\n",
"\n",
" def __init__(self, config: ArcticConfig, layer_idx: Optional[int] = None, **kwargs):\n",
" super().__init__()\n",
" self.config = config\n",
" self.layer_idx = layer_idx\n",
" if layer_idx is None:\n",
" logger.warning_once(\n",
" f\"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will \"\n",
" \"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` \"\n",
" \"when creating this class.\"\n",
" )\n",
"\n",
" self.hidden_size = config.hidden_size\n",
" self.num_heads = config.num_attention_heads\n",
" self.head_dim = self.hidden_size // self.num_heads\n",
" self.num_key_value_heads = config.num_key_value_heads\n",
" self.num_key_value_groups = self.num_heads // self.num_key_value_heads\n",
" self.max_position_embeddings = config.max_position_embeddings\n",
" self.rope_theta = config.rope_theta\n",
" self.is_causal = True\n",
" self.attention_dropout = config.attention_dropout\n",
" self.use_deepspeed_implementation = USE_DEEPSPEED_MOE_ARG in kwargs and kwargs[USE_DEEPSPEED_MOE_ARG]\n",
" if (self.head_dim * self.num_heads) != self.hidden_size:\n",
" raise ValueError(\n",
" f\"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}\"\n",
" f\" and `num_heads`: {self.num_heads}).\"\n",
" )\n",
"\n",
" deepspeed_quantization = kwargs.get(DEEPSPEED_QUANTIZATION_CONFIG)\n",
" deepspeed_lora_config = kwargs.get(DEEPSPEED_LORA_CONFIG)\n",
" quantization_config = kwargs.get(QUANTIZATION_CONFIG, None)\n",
"\n",
" self.q_proj = get_arctic_linear(self.hidden_size, self.num_heads * self.head_dim, bias=False,\n",
" use_deepspeed_implementation=self.use_deepspeed_implementation,\n",
" ds_optimized_lora_config=deepspeed_lora_config, \n",
" ds_optimized_quantization_config=quantization_config, \n",
" ds_optimized_base_weight_sharding=True,\n",
" dtype=torch.bfloat16)\n",
" self.k_proj = get_arctic_linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False,\n",
" use_deepspeed_implementation=self.use_deepspeed_implementation, \n",
" ds_optimized_lora_config=deepspeed_lora_config, \n",
" ds_optimized_quantization_config=quantization_config, \n",
" ds_optimized_base_weight_sharding=True,\n",
" dtype=torch.bfloat16)\n",
" self.v_proj = get_arctic_linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False,\n",
" use_deepspeed_implementation=self.use_deepspeed_implementation,\n",
" ds_optimized_lora_config=deepspeed_lora_config, \n",
" ds_optimized_quantization_config=quantization_config, \n",
" ds_optimized_base_weight_sharding=True,\n",
" dtype=torch.bfloat16)\n",
" self.o_proj = get_arctic_linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False,\n",
" use_deepspeed_implementation=self.use_deepspeed_implementation,\n",
" ds_optimized_lora_config=deepspeed_lora_config, \n",
" ds_optimized_quantization_config=quantization_config, \n",
" ds_optimized_base_weight_sharding=True,\n",
" dtype=torch.bfloat16)\n",
" \n",
" self.rotary_emb = ArcticRotaryEmbedding(\n",
" self.head_dim,\n",
" max_position_embeddings=self.max_position_embeddings,\n",
" base=self.rope_theta,\n",
" )\n",
"\n",
" def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):\n",
" return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()\n",
"\n",
" def forward(\n",
" self,\n",
" hidden_states: torch.Tensor,\n",
" attention_mask: Optional[torch.Tensor] = None,\n",
" position_ids: Optional[torch.LongTensor] = None,\n",
" past_key_value: Optional[Cache] = None,\n",
" output_attentions: bool = False,\n",
" use_cache: bool = False,\n",
" **kwargs,\n",
" ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:\n",
" if \"padding_mask\" in kwargs:\n",
" warnings.warn(\n",
" \"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`\"\n",
" )\n",
" bsz, q_len, _ = hidden_states.size()\n",
"\n",
" query_states = self.q_proj(hidden_states)\n",
" key_states = self.k_proj(hidden_states)\n",
" value_states = self.v_proj(hidden_states)\n",
"\n",
" query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)\n",
" key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)\n",
" value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)\n",
"\n",
" kv_seq_len = key_states.shape[-2]\n",
" if past_key_value is not None:\n",
" if self.layer_idx is None:\n",
" raise ValueError(\n",
" f\"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} \"\n",
" \"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class \"\n",
" \"with a layer index.\"\n",
" )\n",
" kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)\n",
" cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)\n",
" query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)\n",
"\n",
" if past_key_value is not None:\n",
" cache_kwargs = {\"sin\": sin, \"cos\": cos} # Specific to RoPE models\n",
" key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)\n",
"\n",
" # repeat k/v heads if n_kv_heads < n_heads\n",
" key_states = repeat_kv(key_states, self.num_key_value_groups)\n",
" value_states = repeat_kv(value_states, self.num_key_value_groups)\n",
"\n",
" attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)\n",
"\n",
" if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):\n",
" raise ValueError(\n",
" f\"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is\"\n",
" f\" {attn_weights.size()}\"\n",
" )\n",
"\n",
" if attention_mask is not None:\n",
" if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):\n",
" raise ValueError(\n",
" f\"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}\"\n",
" )\n",
"\n",
" attn_weights = attn_weights + attention_mask\n",
"\n",
" # upcast attention to fp32\n",
" attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)\n",
" attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)\n",
" attn_output = torch.matmul(attn_weights, value_states)\n",
"\n",
" if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):\n",
" raise ValueError(\n",
" f\"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is\"\n",
" f\" {attn_output.size()}\"\n",
" )\n",
"\n",
" attn_output = attn_output.transpose(1, 2).contiguous()\n",
" attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)\n",
"\n",
" attn_output = self.o_proj(attn_output)\n",
"\n",
" if not output_attentions:\n",
" attn_weights = None\n",
"\n",
" return attn_output, attn_weights, past_key_value\n",
"\n",
"\n",
"# Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2 with Mistral->Arctic\n",
"class ArcticFlashAttention2(ArcticAttention):\n",
" \"\"\"\n",
" Arctic flash attention module. This module inherits from `ArcticAttention` as the weights of the module stays\n",
" untouched. The only required change would be on the forward pass where it needs to correctly call the public API of\n",
" flash attention and deal with padding tokens in case the input contains any of them.\n",
" \"\"\"\n",
"\n",
" # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__\n",
" def __init__(self, *args, **kwargs):\n",
" super().__init__(*args, **kwargs)\n",
"\n",
" # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.\n",
" # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.\n",
" # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).\n",
" self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()\n",
"\n",
" def forward(\n",
" self,\n",
" hidden_states: torch.Tensor,\n",
" attention_mask: Optional[torch.Tensor] = None,\n",
" position_ids: Optional[torch.LongTensor] = None,\n",
" past_key_value: Optional[Cache] = None,\n",
" output_attentions: bool = False,\n",
" use_cache: bool = False,\n",
" **kwargs,\n",
" ):\n",
" if \"padding_mask\" in kwargs:\n",
" warnings.warn(\n",
" \"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`\"\n",
" )\n",
"\n",
" # overwrite attention_mask with padding_mask\n",
" attention_mask = kwargs.pop(\"padding_mask\")\n",
" bsz, q_len, _ = hidden_states.size()\n",
"\n",
" query_states = self.q_proj(hidden_states)\n",
" key_states = self.k_proj(hidden_states)\n",
" value_states = self.v_proj(hidden_states)\n",
"\n",
" query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)\n",
" key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)\n",
" value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)\n",
"\n",
" kv_seq_len = key_states.shape[-2]\n",
" if past_key_value is not None:\n",
" if self.layer_idx is None:\n",
" raise ValueError(\n",
" f\"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} \"\n",
" \"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class \"\n",
" \"with a layer index.\"\n",
" )\n",
" kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)\n",
"\n",
" # Because the input can be padded, the absolute sequence length depends on the max position id.\n",
" rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1\n",
" cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)\n",
"\n",
" query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)\n",
"\n",
" use_sliding_windows = (\n",
" _flash_supports_window_size\n",
" and getattr(self.config, \"sliding_window\", None) is not None\n",
" and kv_seq_len > self.config.sliding_window\n",
" )\n",
"\n",
" if not _flash_supports_window_size:\n",
" logger.warning_once(\n",
" \"The current flash attention version does not support sliding window attention, for a more memory efficient implementation\"\n",
" \" make sure to upgrade flash-attn library.\"\n",
" )\n",
"\n",
" if past_key_value is not None:\n",
" # Activate slicing cache only if the config has a value `sliding_windows` attribute\n",
" cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0\n",
" if (\n",
" getattr(self.config, \"sliding_window\", None) is not None\n",
" and kv_seq_len > self.config.sliding_window\n",
" and cache_has_contents\n",
" ):\n",
" slicing_tokens = 1 - self.config.sliding_window\n",
"\n",
" past_key = past_key_value[self.layer_idx][0]\n",
" past_value = past_key_value[self.layer_idx][1]\n",
"\n",
" past_key = past_key[:, :, slicing_tokens:, :].contiguous()\n",
" past_value = past_value[:, :, slicing_tokens:, :].contiguous()\n",
"\n",
" if past_key.shape[-2] != self.config.sliding_window - 1:\n",
" raise ValueError(\n",
" f\"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got\"\n",
" f\" {past_key.shape}\"\n",
" )\n",
"\n",
" if attention_mask is not None:\n",
" attention_mask = attention_mask[:, slicing_tokens:]\n",
" attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)\n",
"\n",
" cache_kwargs = {\"sin\": sin, \"cos\": cos} # Specific to RoPE models\n",
" key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)\n",
"\n",
" # repeat k/v heads if n_kv_heads < n_heads\n",
" key_states = repeat_kv(key_states, self.num_key_value_groups)\n",
" value_states = repeat_kv(value_states, self.num_key_value_groups)\n",
" dropout_rate = 0.0 if not self.training else self.attention_dropout\n",
"\n",
" # In PEFT, usually we cast the layer norms in float32 for training stability reasons\n",
" # therefore the input hidden states gets silently casted in float32. Hence, we need\n",
" # cast them back in float16 just to be sure everything works as expected.\n",
" input_dtype = query_states.dtype\n",
" if input_dtype == torch.float32:\n",
" if torch.is_autocast_enabled():\n",
" target_dtype = torch.get_autocast_gpu_dtype()\n",
" # Handle the case where the model is quantized\n",
" elif hasattr(self.config, \"_pre_quantization_dtype\"):\n",
" target_dtype = self.config._pre_quantization_dtype\n",
" else:\n",
" target_dtype = self.q_proj.weight.dtype\n",
"\n",
" logger.warning_once(\n",
" f\"The input hidden states seems to be silently casted in float32, this might be related to\"\n",
" f\" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in\"\n",
" f\" {target_dtype}.\"\n",
" )\n",
"\n",
" query_states = query_states.to(target_dtype)\n",
" key_states = key_states.to(target_dtype)\n",
" value_states = value_states.to(target_dtype)\n",
"\n",
" # Reashape to the expected shape for Flash Attention\n",
" query_states = query_states.transpose(1, 2)\n",
" key_states = key_states.transpose(1, 2)\n",
" value_states = value_states.transpose(1, 2)\n",
"\n",
" attn_output = self._flash_attention_forward(\n",
" query_states,\n",
" key_states,\n",
" value_states,\n",
" attention_mask,\n",
" q_len,\n",
" dropout=dropout_rate,\n",
" use_sliding_windows=use_sliding_windows,\n",
" )\n",
"\n",
" attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()\n",
" attn_output = self.o_proj(attn_output)\n",
"\n",
" if not output_attentions:\n",
" attn_weights = None\n",
"\n",
" return attn_output, attn_weights, past_key_value\n",
"\n",
" def _flash_attention_forward(\n",
" self,\n",
" query_states,\n",
" key_states,\n",
" value_states,\n",
" attention_mask,\n",
" query_length,\n",
" dropout=0.0,\n",
" softmax_scale=None,\n",
" use_sliding_windows=False,\n",
" ):\n",
" \"\"\"\n",
" Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token\n",
" first unpad the input, then computes the attention scores and pad the final attention scores.\n",
"\n",
" Args:\n",
" query_states (`torch.Tensor`):\n",
" Input query states to be passed to Flash Attention API\n",
" key_states (`torch.Tensor`):\n",
" Input key states to be passed to Flash Attention API\n",
" value_states (`torch.Tensor`):\n",
" Input value states to be passed to Flash Attention API\n",
" attention_mask (`torch.Tensor`):\n",
" The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the\n",
" position of padding tokens and 1 for the position of non-padding tokens.\n",
" dropout (`int`, *optional*):\n",
" Attention dropout\n",
" softmax_scale (`float`, *optional*):\n",
" The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)\n",
" use_sliding_windows (`bool`, *optional*):\n",
" Whether to activate sliding window attention.\n",
" \"\"\"\n",
" if not self._flash_attn_uses_top_left_mask:\n",
" causal = self.is_causal\n",
" else:\n",
" # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.\n",
" causal = self.is_causal and query_length != 1\n",
"\n",
" # Contains at least one padding token in the sequence\n",
" if attention_mask is not None:\n",
" batch_size = query_states.shape[0]\n",
" query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(\n",
" query_states, key_states, value_states, attention_mask, query_length\n",
" )\n",
"\n",
" cu_seqlens_q, cu_seqlens_k = cu_seq_lens\n",
" max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens\n",
"\n",
" if not use_sliding_windows:\n",
" attn_output_unpad = flash_attn_varlen_func(\n",
" query_states,\n",
" key_states,\n",
" value_states,\n",
" cu_seqlens_q=cu_seqlens_q,\n",
" cu_seqlens_k=cu_seqlens_k,\n",
" max_seqlen_q=max_seqlen_in_batch_q,\n",
" max_seqlen_k=max_seqlen_in_batch_k,\n",
" dropout_p=dropout,\n",
" softmax_scale=softmax_scale,\n",
" causal=causal,\n",
" )\n",
" else:\n",
" attn_output_unpad = flash_attn_varlen_func(\n",
" query_states,\n",
" key_states,\n",
" value_states,\n",
" cu_seqlens_q=cu_seqlens_q,\n",
" cu_seqlens_k=cu_seqlens_k,\n",
" max_seqlen_q=max_seqlen_in_batch_q,\n",
" max_seqlen_k=max_seqlen_in_batch_k,\n",
" dropout_p=dropout,\n",
" softmax_scale=softmax_scale,\n",
" causal=causal,\n",
" window_size=(self.config.sliding_window, self.config.sliding_window),\n",
" )\n",
"\n",
" attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)\n",
" else:\n",
" if not use_sliding_windows:\n",
" attn_output = flash_attn_func(\n",
" query_states,\n",
" key_states,\n",
" value_states,\n",
" dropout,\n",
" softmax_scale=softmax_scale,\n",
" causal=causal,\n",
" )\n",
" else:\n",
" attn_output = flash_attn_func(\n",
" query_states,\n",
" key_states,\n",
" value_states,\n",
" dropout,\n",
" softmax_scale=softmax_scale,\n",
" causal=causal,\n",
" window_size=(self.config.sliding_window, self.config.sliding_window),\n",
" )\n",
"\n",
" return attn_output\n",
"\n",
" def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):\n",
" batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape\n",
"\n",
" # On the first iteration we need to properly re-create the padding mask\n",
" # by slicing it on the proper place\n",
" if kv_seq_len != attention_mask.shape[-1]:\n",
" attention_mask_num_tokens = attention_mask.shape[-1]\n",
" attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]\n",
"\n",
" indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)\n",
"\n",
" key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)\n",
" value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)\n",
"\n",
" if query_length == kv_seq_len:\n",
" query_layer = index_first_axis(\n",
" query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k\n",
" )\n",
" cu_seqlens_q = cu_seqlens_k\n",
" max_seqlen_in_batch_q = max_seqlen_in_batch_k\n",
" indices_q = indices_k\n",
" elif query_length == 1:\n",
" max_seqlen_in_batch_q = 1\n",
" cu_seqlens_q = torch.arange(\n",
" batch_size + 1, dtype=torch.int32, device=query_layer.device\n",
" ) # There is a memcpy here, that is very bad.\n",
" indices_q = cu_seqlens_q[:-1]\n",
" query_layer = query_layer.squeeze(1)\n",
" else:\n",
" # The -q_len: slice assumes left padding.\n",
" attention_mask = attention_mask[:, -query_length:]\n",
" query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)\n",
"\n",
" return (\n",
" query_layer,\n",
" key_layer,\n",
" value_layer,\n",
" indices_q,\n",
" (cu_seqlens_q, cu_seqlens_k),\n",
" (max_seqlen_in_batch_q, max_seqlen_in_batch_k),\n",
" )\n",
"\n",
"def get_arctic_linear(input_dim, \n",
" output_dim, \n",
" bias=False,\n",
" use_deepspeed_implementation=False,\n",
" ds_optimized_lora_config=None, \n",
" ds_optimized_quantization_config=None, \n",
" ds_optimized_base_weight_sharding=False,\n",
" dtype=torch.bfloat16):\n",
" \"\"\"Can return deepspeed optimized linear if available.\n",
" Args:\n",
" input_dim, output_dim, bias, dtype: self explanatory (same as from nn.Linear)\n",
" ds_optimized_lora_config: config of type ds_linear.LoRAConfig that contains lora specific parameter if we want to add lora to this layer.\n",
" ds_optimized_quantization_config: config of type ds_linear.QuantizationConfig.\n",
" ds_optimized_base_weight_sharding: bool. If true, the base weight for lora (provided ds_optimized_lora_config is not None) will be sharded across all available gpus\n",
" in a tensor parallel way.\n",
" \"\"\"\n",
" if is_deepspeed_available():\n",
" if ds_optimized_lora_config is not None:\n",
" ds_optimized_lora_config: ds_linear.LoRAConfig = copy.deepcopy(ds_optimized_lora_config)\n",
" ds_optimized_lora_config.base_weight_sharding = torch.distributed.get_world_size() if ds_optimized_base_weight_sharding else 1\n",
" return ds_linear.OptimizedLinear(input_dim, output_dim, bias, ds_optimized_lora_config, ds_optimized_quantization_config, dtype=dtype)\n",
" return nn.Linear(input_dim, output_dim, bias=bias, dtype=dtype)\n",
"\n",
"\n",
"# Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Arctic\n",
"class ArcticSdpaAttention(ArcticAttention):\n",
" \"\"\"\n",
" Arctic attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from\n",
" `ArcticAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to\n",
" SDPA API.\n",
" \"\"\"\n",
"\n",
" # Adapted from ArcticAttention.forward\n",
" def forward(\n",
" self,\n",
" hidden_states: torch.Tensor,\n",
" attention_mask: Optional[torch.Tensor] = None,\n",
" position_ids: Optional[torch.LongTensor] = None,\n",
" past_key_value: Optional[Cache] = None,\n",
" output_attentions: bool = False,\n",
" use_cache: bool = False,\n",
" ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:\n",
" if output_attentions:\n",
" # TODO: Improve this warning with e.g. `model.config.attn_implementation = \"manual\"` once this is implemented.\n",
" logger.warning_once(\n",
" \"ArcticModel is using ArcticSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, \"\n",
" 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation=\"eager\"` when loading the model.'\n",
" )\n",
" return super().forward(\n",
" hidden_states=hidden_states,\n",
" attention_mask=attention_mask,\n",
" position_ids=position_ids,\n",
" past_key_value=past_key_value,\n",
" output_attentions=output_attentions,\n",
" use_cache=use_cache,\n",
" )\n",
"\n",
" bsz, q_len, _ = hidden_states.size()\n",
"\n",
" query_states = self.q_proj(hidden_states)\n",
" key_states = self.k_proj(hidden_states)\n",
" value_states = self.v_proj(hidden_states)\n",
"\n",
" query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)\n",
" key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)\n",
" value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)\n",
"\n",
" kv_seq_len = key_states.shape[-2]\n",
" if past_key_value is not None:\n",
" kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)\n",
" cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)\n",
"\n",
" query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)\n",
"\n",
" if past_key_value is not None:\n",
" cache_kwargs = {\"sin\": sin, \"cos\": cos} # Specific to RoPE models\n",
" key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)\n",
"\n",
" key_states = repeat_kv(key_states, self.num_key_value_groups)\n",
" value_states = repeat_kv(value_states, self.num_key_value_groups)\n",
"\n",
" if attention_mask is not None:\n",
" if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):\n",
" raise ValueError(\n",
" f\"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}\"\n",
" )\n",
"\n",
" # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,\n",
" # Reference: https://github.com/pytorch/pytorch/issues/112577.\n",
" if query_states.device.type == \"cuda\" and attention_mask is not None:\n",
" query_states = query_states.contiguous()\n",
" key_states = key_states.contiguous()\n",
" value_states = value_states.contiguous()\n",
"\n",
" attn_output = torch.nn.functional.scaled_dot_product_attention(\n",
" query_states,\n",
" key_states,\n",
" value_states,\n",
" attn_mask=attention_mask,\n",
" dropout_p=self.attention_dropout if self.training else 0.0,\n",
" # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.\n",
" is_causal=self.is_causal and attention_mask is None and q_len > 1,\n",
" )\n",
"\n",
" attn_output = attn_output.transpose(1, 2).contiguous()\n",
" attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)\n",
"\n",
" attn_output = self.o_proj(attn_output)\n",
"\n",
" return attn_output, None, past_key_value\n",
"\n",
"\n",
"MIXTRAL_ATTENTION_CLASSES = {\n",
" \"eager\": ArcticAttention,\n",
" \"flash_attention_2\": ArcticFlashAttention2,\n",
" \"sdpa\": ArcticSdpaAttention,\n",
"}\n",
"\n",
"\n",
"class ArcticMLP(nn.Module):\n",
" def __init__(self, config: ArcticConfig, \n",
" use_deepspeed_implementation=False,\n",
" ds_optimized_lora_config=None,\n",
" ds_optimized_quantization_config=None,\n",
" shard_base_weights_if_doing_lora=False, \n",
" is_residual_mlp=False):\n",
" \"\"\"MLP class for Arctic supporting vanilla linear layers as well as some deepspeed optimizations.\n",
"\n",
" ds_optimized_lora_config: config of type ds_linear.LoRAConfig that contains lora specific parameter if we want to add lora to this layer.\n",
" ds_optimized_quantization_config: config of type ds_linear.QuantizationConfig.\n",
" ds_optimized_base_weight_sharding: bool. If true, the base weight for lora (provided ds_optimized_lora_config is not None) will be sharded across all available gpus\n",
" in a tensor parallel way.\n",
" is_residual_mlp: bool. If true, this is MLP inside arctic residual layer which has ffn_dim the same as full intermediate_size.\n",
" \"\"\" \n",
" super(ArcticMLP, self).__init__()\n",
" self.hidden_dim = config.hidden_size\n",
" self.ffn_dim = config.intermediate_size if not is_residual_mlp else self.hidden_dim \n",
" self.w1 = get_arctic_linear(self.hidden_dim, self.ffn_dim, False,\n",
" use_deepspeed_implementation=use_deepspeed_implementation,\n",
" ds_optimized_lora_config=ds_optimized_lora_config, \n",
" ds_optimized_quantization_config=ds_optimized_quantization_config, \n",
" ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora,\n",
" dtype=torch.bfloat16)\n",
" self.w2 = get_arctic_linear(self.ffn_dim, self.hidden_dim, False,\n",
" use_deepspeed_implementation=use_deepspeed_implementation, \n",
" ds_optimized_lora_config=ds_optimized_lora_config, \n",
" ds_optimized_quantization_config=ds_optimized_quantization_config, \n",
" ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora,\n",
" dtype=torch.bfloat16)\n",
" self.w3 = get_arctic_linear(self.hidden_dim, self.ffn_dim, False,\n",
" use_deepspeed_implementation=use_deepspeed_implementation, \n",
" ds_optimized_lora_config=ds_optimized_lora_config, \n",
" ds_optimized_quantization_config=ds_optimized_quantization_config, \n",
" ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora,\n",
" dtype=torch.bfloat16)\n",
" self.act_fn = ACT2FN[config.hidden_act]\n",
"\n",
" def forward(self, hidden_states):\n",
" current_hidden_states = self.act_fn(self.w1(hidden_states)) * self.w3(hidden_states)\n",
" current_hidden_states = self.w2(current_hidden_states)\n",
" return current_hidden_states\n",
"\n",
"\n",
"class ArcticMoE(nn.Module):\n",
" def __init__(self, config: ArcticConfig, layer_id: int, **kwargs):\n",
" super(ArcticMoE, self).__init__()\n",
"\n",
" self.hidden_dim = config.hidden_size\n",
" self.num_experts = config.num_local_experts\n",
" self.layer_id = layer_id \n",
" self.top_k = config.num_experts_per_tok\n",
" self.is_moe_layer = (layer_id+1) % config.moe_layer_frequency == 0\n",
"\n",
" self.use_deepspeed_implementation = USE_DEEPSPEED_MOE_ARG in kwargs and kwargs[USE_DEEPSPEED_MOE_ARG]\n",
" if self.use_deepspeed_implementation and MoE is None:\n",
" raise ValueError(\"Deepspeed is not installed\")\n",
" quantization_config = kwargs.get(QUANTIZATION_CONFIG, None)\n",
" deepspeed_lora = kwargs.get(DEEPSPEED_LORA_CONFIG)\n",
" if not self.is_moe_layer: # dense, not MoE\n",
" self.mlp = ArcticMLP(config,\n",
" use_deepspeed_implementation=self.use_deepspeed_implementation,\n",
" ds_optimized_quantization_config=quantization_config,\n",
" ds_optimized_lora_config=deepspeed_lora,\n",
" shard_base_weights_if_doing_lora=True)\n",
" else:\n",
" if self.use_deepspeed_implementation: # DeepSpeed's MoE \n",
" moe_expert_parallel_size = kwargs.get(MOE_EXPERT_PARALLEL_SIZE_ARG, 1)\n",
" self.mlp = MoE(self.hidden_dim,\n",
" # base weight sharding false for all deepspeed moe calls because it is already sharded\n",
" ArcticMLP(config, \n",
" use_deepspeed_implementation=True,\n",
" ds_optimized_quantization_config=quantization_config,\n",
" ds_optimized_lora_config=deepspeed_lora,\n",
" shard_base_weights_if_doing_lora=False),\n",
" num_experts=config.num_local_experts,\n",
" ep_size=moe_expert_parallel_size,\n",
" k=config.num_experts_per_tok,\n",
" use_residual=False,\n",
" capacity_factor=config.moe_train_capacity_factor,\n",
" eval_capacity_factor=config.moe_eval_capacity_factor,\n",
" enable_expert_tensor_parallelism=config.enable_expert_tensor_parallelism,\n",
" min_capacity=config.moe_min_capacity,\n",
" drop_tokens=config.moe_token_dropping\n",
" )\n",
" else:\n",
" # \"local\" MoE implementation\n",
" self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False)\n",
" self.experts = nn.ModuleList([ArcticMLP(config,\n",
" use_deepspeed_implementation=self.use_deepspeed_implementation, \n",
" ds_optimized_quantization_config=quantization_config,\n",
" ds_optimized_lora_config=deepspeed_lora,\n",
" shard_base_weights_if_doing_lora=True) for i in range(self.num_experts)])\n",
"\n",
" # if torch.distributed.get_rank() == 0:\n",
" # deepspeed.runtime.utils.see_memory_usage(\"\", force=True)\n",
"\n",
"\n",
" # Similar in behavior to transformers.models.mixtral.modeling_mixtral.MixtralSparseMoeBlock.forward but more efficient.\n",
" def _moe_foreward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n",
" batch_size, sequence_length, hidden_dim = hidden_states.shape\n",
" hidden_states = hidden_states.view(-1, hidden_dim)\n",
" # router_logits: (batch * sequence_length, n_experts)\n",
" router_logits = self.gate(hidden_states)\n",
"\n",
" routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)\n",
" routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)\n",
" if self.top_k > 1:\n",
" routing_weights /= routing_weights.sum(dim=-1, keepdim=True)\n",
" # we cast back to the input dtype\n",
"\n",
" final_hidden_states = torch.zeros(\n",
" (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device\n",
" )\n",
"\n",
" # Matching between experts, tokens, and their top-k rank. For every i,\n",
" # expert_idx[i] is the rank topk_idx[i] expert for token_idx[i].\n",
" expert_idx, token_idx, topk_idx = torch.where(\n",
" selected_experts == torch.arange(\n",
" self.num_experts,\n",
" device=selected_experts.device,\n",
" ).view((self.num_experts, 1, 1))\n",
" )\n",
"\n",
" # Split into one chunk per expert.\n",
" bincount = torch.bincount(expert_idx, minlength=self.num_experts).tolist()\n",
" token_idx = token_idx.split(bincount)\n",
" topk_idx = topk_idx.split(bincount)\n",
"\n",
" # Loop over all available experts in the model and perform the computation on each expert\n",
" for expert_layer, top_x, idx in zip(self.experts, token_idx, topk_idx):\n",
" if top_x.shape[0] == 0:\n",
" continue\n",
"\n",
" # in torch it is faster to index using lists than torch tensors\n",
" top_x_list = top_x.tolist()\n",
" idx_list = idx.tolist()\n",
"\n",
" # Index the correct hidden states and compute the expert hidden state for\n",
" # the current expert. We need to make sure to multiply the output hidden\n",
" # states by `routing_weights` on the corresponding tokens (top-1 and top-2)\n",
" current_state = hidden_states[None, top_x_list].reshape(-1, hidden_dim)\n",
" current_hidden_states = expert_layer(current_state) * routing_weights[top_x_list, idx_list, None]\n",
"\n",
" # However `index_add_` only support torch tensors for indexing so we'll use\n",
" # the `top_x` tensor here.\n",
" final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))\n",
" # torch.distributed.barrier()\n",
" final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)\n",
" return final_hidden_states, load_balancing_loss_func((router_logits, ), self.num_experts, self.top_k) # ZY: let's directly output the loss to align what we have in ds\n",
"\n",
" def forward(self, hidden_states: torch.Tensor):\n",
" if self.is_moe_layer:\n",
" if self.use_deepspeed_implementation:\n",
" # deepspeed returns a tuple including output, gate loss, and expert count.\n",
" hidden_states, moe_loss, _ = self.mlp(hidden_states)\n",
" return hidden_states, moe_loss\n",
" else:\n",
" return self._moe_foreward(hidden_states)\n",
" else:\n",
" return self.mlp(hidden_states), torch.tensor(0.0, device=hidden_states.device, dtype=hidden_states.dtype)\n",
"\n",
"\n",
"class ArcticDecoderLayer(nn.Module):\n",
" def __init__(self, config: ArcticConfig, layer_idx: int, **kwargs):\n",
" super().__init__()\n",
" self.layer_idx = layer_idx\n",
" self.hidden_size = config.hidden_size\n",
" self.self_attn = MIXTRAL_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx, **kwargs)\n",
" self.block_sparse_moe = ArcticMoE(config, layer_id=layer_idx, **kwargs)\n",
" self.input_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps) \n",
" self.post_attention_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps)\n",
" self.use_deepspeed_implementation = USE_DEEPSPEED_MOE_ARG in kwargs and kwargs[USE_DEEPSPEED_MOE_ARG]\n",
"\n",
" self.parallel_attn_mlp_res = config.parallel_attn_mlp_res and self.block_sparse_moe.is_moe_layer # add residual only when it is moe layer\n",
" deepspeed_quantization = kwargs.get(DEEPSPEED_QUANTIZATION_CONFIG)\n",
" deepspeed_lora = kwargs.get(DEEPSPEED_LORA_CONFIG)\n",
" if self.parallel_attn_mlp_res:\n",
" self.residual_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps) \n",
" self.residual_mlp = ArcticMLP(config,\n",
" use_deepspeed_implementation=self.use_deepspeed_implementation,\n",
" is_residual_mlp=True,\n",
" ds_optimized_quantization_config=deepspeed_quantization,\n",
" ds_optimized_lora_config=deepspeed_lora,\n",
" shard_base_weights_if_doing_lora=True) # for the residual layer. always shard the base weight if doing deepspeed lora.\n",
"\n",
" def forward(\n",
" self,\n",
" hidden_states: torch.Tensor,\n",
" attention_mask: Optional[torch.Tensor] = None,\n",
" position_ids: Optional[torch.LongTensor] = None,\n",
" past_key_value: Optional[Tuple[torch.Tensor]] = None,\n",
" output_attentions: Optional[bool] = False,\n",
" use_cache: Optional[bool] = False,\n",
" **kwargs,\n",
" ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:\n",
" if \"padding_mask\" in kwargs:\n",
" warnings.warn(\n",
" \"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`\"\n",
" )\n",
" \"\"\"\n",
" Args:\n",
" hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`\n",
" attention_mask (`torch.FloatTensor`, *optional*): attention mask of size\n",
" `(batch, sequence_length)` where padding elements are indicated by 0.\n",
" past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states\n",
" output_attentions (`bool`, *optional*):\n",
" Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n",
" returned tensors for more detail.\n",
" use_cache (`bool`, *optional*):\n",
" If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding\n",
" (see `past_key_values`).\n",
" \"\"\"\n",
"\n",
" residual_input = hidden_states\n",
"\n",
" hidden_states = self.input_layernorm(hidden_states)\n",
"\n",
" # Self Attention\n",
" hidden_states, self_attn_weights, present_key_value = self.self_attn(\n",
" hidden_states=hidden_states,\n",
" attention_mask=attention_mask,\n",
" position_ids=position_ids,\n",
" past_key_value=past_key_value,\n",
" output_attentions=output_attentions,\n",
" use_cache=use_cache,\n",
" )\n",
" hidden_states = residual_input + hidden_states\n",
"\n",
" residual_attn = hidden_states\n",
" \n",
" if self.parallel_attn_mlp_res:\n",
" # Note the architecture here is that the MOE layers reads the **pre-attention** input while there is a \"normal\" transformer residual part.\n",
" # This is to achieve better parallelization.\n",
"\n",
" # residual mlp part\n",
"\n",
" hidden_states = self.residual_layernorm(hidden_states)\n",
" hidden_states = self.residual_mlp(hidden_states)\n",
" residual_residual = residual_attn + hidden_states\n",
" # parallel mlp moe part\n",
" hidden_states = self.post_attention_layernorm(residual_input) # parallel attn mlp has the same input\n",
" hidden_states, gate_loss = self.block_sparse_moe(hidden_states)\n",
" hidden_states = residual_residual + hidden_states\n",
" else:\n",
" hidden_states = self.post_attention_layernorm(hidden_states)\n",
" hidden_states, gate_loss = self.block_sparse_moe(hidden_states)\n",
" hidden_states = residual_attn + hidden_states\n",
"\n",
" outputs = (hidden_states,)\n",
"\n",
" if output_attentions:\n",
" outputs += (self_attn_weights,)\n",
"\n",
" if use_cache:\n",
" outputs += (present_key_value,)\n",
"\n",
" outputs += (gate_loss,)\n",
"\n",
" return outputs\n",
"\n",
"\n",
"ARCTIC_START_DOCSTRING = r\"\"\"\n",
" This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the\n",
" library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads\n",
" etc.)\n",
"\n",
" This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.\n",
" Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage\n",
" and behavior.\n",
"\n",
" Parameters:\n",
" config ([`ArcticConfig`]):\n",
" Model configuration class with all the parameters of the model. Initializing with a config file does not\n",
" load the weights associated with the model, only the configuration. Check out the\n",
" [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n",
"\"\"\"\n",
"\n",
"\n",
"@add_start_docstrings(\n",
" \"The bare Arctic Model outputting raw hidden-states without any specific head on top.\",\n",
" ARCTIC_START_DOCSTRING,\n",
")\n",
"# Copied from transformers.models.mistral.modeling_mistral.MistralPreTrainedModel with Mistral->Arctic\n",
"class ArcticPreTrainedModel(PreTrainedModel):\n",
" config_class = ArcticConfig\n",
" base_model_prefix = \"model\"\n",
" supports_gradient_checkpointing = True\n",
" _no_split_modules = [\"ArcticDecoderLayer\"]\n",
" _skip_keys_device_placement = \"past_key_values\"\n",
" _supports_flash_attn_2 = True\n",
" _supports_sdpa = True\n",
" _supports_cache_class = True\n",
"\n",
" def _init_weights(self, module):\n",
" std = self.config.initializer_range\n",
" # if is_deepspeed_available():\n",
" # # TODO(rajhans): remove this once ds has init for quantizedlinear.\n",
" # try:\n",
" # from deepspeed.linear.quantization import QuantizedLinear, QuantizedParameter\n",
" # if isinstance(module, QuantizedLinear):\n",
" # weights = module.weight.dequantized()\n",
" # weights.normal_(mean=0.0, std=std)\n",
" # if module.bias is not None:\n",
" # module.bias.data.zero_()\n",
" # module.weight = QuantizedParameter(weights)\n",
" # module.weight.to(dtype=torch.bfloat16, device=weights.device)\n",
" # el\n",
" if isinstance(module, nn.Linear):\n",
" module.weight.data.normal_(mean=0.0, std=std)\n",
" if module.bias is not None:\n",
" module.bias.data.zero_()\n",
" elif isinstance(module, nn.Embedding):\n",
" module.weight.data.normal_(mean=0.0, std=std)\n",
" if module.padding_idx is not None:\n",
" module.weight.data[module.padding_idx].zero_()\n",
"\n",
"MIXTRAL_INPUTS_DOCSTRING = r\"\"\"\n",
" Args:\n",
" input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n",
" Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide\n",
" it.\n",
"\n",
" Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n",
" [`PreTrainedTokenizer.__call__`] for details.\n",
"\n",
" [What are input IDs?](../glossary#input-ids)\n",
" attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n",
" Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n",
"\n",
" - 1 for tokens that are **not masked**,\n",
" - 0 for tokens that are **masked**.\n",
"\n",
" [What are attention masks?](../glossary#attention-mask)\n",
"\n",
" Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n",
" [`PreTrainedTokenizer.__call__`] for details.\n",
"\n",
" If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see\n",
" `past_key_values`).\n",
"\n",
" If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]\n",
" and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more\n",
" information on the default strategy.\n",
"\n",
" - 1 indicates the head is **not masked**,\n",
" - 0 indicates the head is **masked**.\n",
" position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n",
" Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,\n",
" config.n_positions - 1]`.\n",
"\n",
" [What are position IDs?](../glossary#position-ids)\n",
" past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):\n",
" Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape\n",
" `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape\n",
" `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.\n",
"\n",
" Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention\n",
" blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.\n",
"\n",
" If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n",
" don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n",
" `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n",
" inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n",
" Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This\n",
" is useful if you want more control over how to convert `input_ids` indices into associated vectors than the\n",
" model's internal embedding lookup matrix.\n",
" use_cache (`bool`, *optional*):\n",
" If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n",
" `past_key_values`).\n",
" output_attentions (`bool`, *optional*):\n",
" Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n",
" tensors for more detail.\n",
" output_hidden_states (`bool`, *optional*):\n",
" Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n",
" more detail.\n",
" return_dict (`bool`, *optional*):\n",
" Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n",
"\"\"\"\n",
"\n",
"\n",
"@add_start_docstrings(\n",
" \"The bare Arctic Model outputting raw hidden-states without any specific head on top.\",\n",
" ARCTIC_START_DOCSTRING,\n",
")\n",
"# Copied from transformers.models.mistral.modeling_mistral.MistralModel with MISTRAL->MIXTRAL,Mistral->Arctic\n",
"class ArcticModel(ArcticPreTrainedModel):\n",
" \"\"\"\n",
" Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ArcticDecoderLayer`]\n",
"\n",
" Args:\n",
" config: ArcticConfig\n",
" \"\"\"\n",
"\n",
" def __init__(self, config: ArcticConfig, **kwargs):\n",
" super().__init__(config)\n",
" self.padding_idx = config.pad_token_id\n",
" self.vocab_size = config.vocab_size\n",
"\n",
" self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)\n",
" self.layers = nn.ModuleList(\n",
" [ArcticDecoderLayer(config, layer_idx, **kwargs) for layer_idx in range(config.num_hidden_layers)]\n",
" )\n",
" self._attn_implementation = config._attn_implementation\n",
" self.norm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps)\n",
"\n",
" self.gradient_checkpointing = True\n",
" # Initialize weights and apply final processing\n",
" self.post_init()\n",
"\n",
" def get_input_embeddings(self):\n",
" return self.embed_tokens\n",
"\n",
" def set_input_embeddings(self, value):\n",
" self.embed_tokens = value\n",
"\n",
" # Ignore copy\n",
" @add_start_docstrings_to_model_forward(MIXTRAL_INPUTS_DOCSTRING)\n",
" def forward(\n",
" self,\n",
" input_ids: torch.LongTensor = None,\n",
" attention_mask: Optional[torch.Tensor] = None,\n",
" position_ids: Optional[torch.LongTensor] = None,\n",
" past_key_values: Optional[List[torch.FloatTensor]] = None,\n",
" inputs_embeds: Optional[torch.FloatTensor] = None,\n",
" use_cache: Optional[bool] = None,\n",
" output_attentions: Optional[bool] = None,\n",
" output_hidden_states: Optional[bool] = None,\n",
" return_dict: Optional[bool] = None,\n",
" ) -> Union[Tuple, MoeModelOutputWithPast]:\n",
" output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n",
" output_hidden_states = (\n",
" output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n",
" )\n",
" use_cache = use_cache if use_cache is not None else self.config.use_cache\n",
"\n",
" return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n",
"\n",
" # retrieve input_ids and inputs_embeds\n",
" if input_ids is not None and inputs_embeds is not None:\n",
" raise ValueError(\"You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time\")\n",
" elif input_ids is not None:\n",
" batch_size, seq_length = input_ids.shape\n",
" elif inputs_embeds is not None:\n",
" batch_size, seq_length, _ = inputs_embeds.shape\n",
" else:\n",
" raise ValueError(\"You have to specify either decoder_input_ids or decoder_inputs_embeds\")\n",
"\n",
" past_key_values_length = 0\n",
"\n",
" if self.gradient_checkpointing and self.training:\n",
" if use_cache:\n",
" logger.warning_once(\n",
" \"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...\"\n",
" )\n",
" use_cache = False\n",
"\n",
" if use_cache:\n",
" use_legacy_cache = not isinstance(past_key_values, Cache)\n",
" if use_legacy_cache:\n",
" past_key_values = DynamicCache.from_legacy_cache(past_key_values)\n",
" past_key_values_length = past_key_values.get_usable_length(seq_length)\n",
"\n",
" if position_ids is None:\n",
" device = input_ids.device if input_ids is not None else inputs_embeds.device\n",
" position_ids = torch.arange(\n",
" past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device\n",
" )\n",
" position_ids = position_ids.unsqueeze(0).view(-1, seq_length)\n",
" else:\n",
" position_ids = position_ids.view(-1, seq_length).long()\n",
"\n",
" if inputs_embeds is None:\n",
" inputs_embeds = self.embed_tokens(input_ids)\n",
"\n",
" if attention_mask is not None and self._attn_implementation == \"flash_attention_2\" and use_cache:\n",
" is_padding_right = attention_mask[:, -1].sum().item() != batch_size\n",
" if is_padding_right:\n",
" raise ValueError(\n",
" \"You are attempting to perform batched generation with padding_side='right'\"\n",
" \" this may lead to unexpected behaviour for Flash Attention version of Arctic. Make sure to \"\n",
" \" call `tokenizer.padding_side = 'left'` before tokenizing the input. \"\n",
" )\n",
"\n",
" if self._attn_implementation == \"flash_attention_2\":\n",
" # 2d mask is passed through the layers\n",
" attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None\n",
" elif self._attn_implementation == \"sdpa\" and not output_attentions:\n",
" # output_attentions=True can not be supported when using SDPA, and we fall back on\n",
" # the manual implementation that requires a 4D causal mask in all cases.\n",
" attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(\n",
" attention_mask,\n",
" (batch_size, seq_length),\n",
" inputs_embeds,\n",
" past_key_values_length,\n",
" )\n",
" else:\n",
" # 4d mask is passed through the layers\n",
" attention_mask = _prepare_4d_causal_attention_mask(\n",
" attention_mask,\n",
" (batch_size, seq_length),\n",
" inputs_embeds,\n",
" past_key_values_length,\n",
" sliding_window=self.config.sliding_window,\n",
" )\n",
"\n",
" hidden_states = inputs_embeds\n",
"\n",
" # decoder layers\n",
" all_hidden_states = () if output_hidden_states else None\n",
" all_self_attns = () if output_attentions else None\n",
" all_router_losses = ()\n",
" next_decoder_cache = None\n",
"\n",
" for i, decoder_layer in enumerate(self.layers):\n",
" if output_hidden_states:\n",
" all_hidden_states += (hidden_states,)\n",
"\n",
" if self.gradient_checkpointing and self.training:\n",
" layer_outputs = self._gradient_checkpointing_func(\n",
" decoder_layer.__call__,\n",
" hidden_states,\n",
" attention_mask,\n",
" position_ids,\n",
" past_key_values,\n",
" output_attentions,\n",
" use_cache,\n",
" )\n",
" else:\n",
" layer_outputs = decoder_layer(\n",
" hidden_states,\n",
" attention_mask=attention_mask,\n",
" position_ids=position_ids,\n",
" past_key_value=past_key_values,\n",
" output_attentions=output_attentions,\n",
" use_cache=use_cache,\n",
" )\n",
"\n",
" hidden_states = layer_outputs[0]\n",
"\n",
" if use_cache:\n",
" if hasattr(layer_outputs[2 if output_attentions else 1], 'to_legacy_cache'):\n",
" next_decoder_cache = layer_outputs[2 if output_attentions else 1]\n",
" else:\n",
" if next_decoder_cache is None:\n",
" next_decoder_cache = [layer_outputs[2 if output_attentions else 1]]\n",
" else:\n",
" next_decoder_cache.append(layer_outputs[2 if output_attentions else 1])\n",
"\n",
" if output_attentions:\n",
" all_self_attns += (layer_outputs[1],)\n",
"\n",
" all_router_losses += (layer_outputs[-1],)\n",
" hidden_states = self.norm(hidden_states)\n",
"\n",
" # add hidden states from the last decoder layer\n",
" if output_hidden_states:\n",
" all_hidden_states += (hidden_states,)\n",
"\n",
" next_cache = None\n",
" if use_cache:\n",
" next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache and hasattr(next_decoder_cache, 'to_legacy_cache') else next_decoder_cache\n",
" torch.cuda.empty_cache() \n",
"\n",
" if not return_dict:\n",
" return tuple(\n",
" v\n",
" for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_losses]\n",
" if v is not None\n",
" )\n",
" return MoeModelOutputWithPast(\n",
" last_hidden_state=hidden_states,\n",
" past_key_values=next_cache,\n",
" hidden_states=all_hidden_states,\n",
" attentions=all_self_attns,\n",
" router_logits=all_router_losses,\n",
" )\n",
"\n",
"class ArcticForCausalLM(ArcticPreTrainedModel):\n",
" # TODO(jeffra): update _keys_to_ignore_on_load_unexpected with expert keys not relevant for this rank\n",
" _keys_to_ignore_on_load_unexpected = [r\"model\\.layers\\.\\d+\\.block_sparse_moe\\.experts\\.\\d+\\.w\\d+\\.weight\"\n",
" r\"model\\.layers\\.\\d+\\.block_sparse_moe\\.gate\\.weight\"]\n",
" _keys_to_ignore_on_load_missing = [r\"model\\.layers\\.\\d+\\.block_sparse_moe\\.mlp\\.deepspeed_moe\\.experts\\.deepspeed_experts\\.\\d+\\.w\\d+\\.weight\",\n",
" r\"model\\.layers\\.\\d+\\.block_sparse_moe\\.mlp\\.deepspeed_moe\\.gate\\.wg\\.weight\"]\n",
" _tied_weights_keys = []#[\"lm_head.weight\"]\n",
"\n",
" def __init__(self, config, **kwargs):\n",
" super().__init__(config)\n",
" self.model = ArcticModel(config, **kwargs)\n",
" self.vocab_size = config.vocab_size\n",
" self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n",
" self.router_aux_loss_coef = config.router_aux_loss_coef\n",
" self.num_experts = config.num_local_experts\n",
" self.num_experts_per_tok = config.num_experts_per_tok\n",
" self.use_deepspeed_moe = kwargs.get(USE_DEEPSPEED_MOE_ARG, False)\n",
" self.moe_expert_parallel_size = kwargs.get(MOE_EXPERT_PARALLEL_SIZE_ARG, 1)\n",
" self.is_deepspeed_lora = kwargs.get(DEEPSPEED_LORA_CONFIG) is not None\n",
" self.gradient_checkpointing = True\n",
" # self.shard_base_weights_if_doing_lora = kwargs.get(\"shard_base_weights_if_doing_lora\", False)\n",
" # Initialize weights and apply final processing\n",
" self.post_init()\n",
"\n",
" def get_input_embeddings(self):\n",
" return self.model.embed_tokens\n",
"\n",
" def set_input_embeddings(self, value):\n",
" self.model.embed_tokens = value\n",
"\n",
" def get_output_embeddings(self):\n",
" return self.lm_head\n",
"\n",
" def set_output_embeddings(self, new_embeddings):\n",
" self.lm_head = new_embeddings\n",
"\n",
" def set_decoder(self, decoder):\n",
" self.model = decoder\n",
"\n",
" def get_decoder(self):\n",
" return self.model\n",
"\n",
"\n",
" def _expert_number_from_param_name(self, param_name):\n",
" # example param_name: model.layers.1.block_sparse_moe.experts.10.w1.weight\n",
" pattern = r'experts\\.(\\d+)\\.'\n",
" m = re.search(pattern, param_name)\n",
" if m:\n",
" return int(m[1])\n",
" else:\n",
" return None\n",
"\n",
" def state_dict(self, *args, **kwargs):\n",
" state_dict = super().state_dict(*args, **kwargs)\n",
"\n",
" if not self.use_deepspeed_moe:\n",
" return state_dict\n",
"\n",
" # when trying to construct the deepspeed checkpoint we don't want to gather everything\n",
" if not getattr(self, '_gather_expert_params', False):\n",
" return state_dict\n",
"\n",
" rank = torch.distributed.get_rank() if torch.distributed.is_initialized() else 0\n",
" world_size = torch.distributed.get_world_size() if torch.distributed.is_initialized() else 1\n",
"\n",
" # non-lora experts\n",
" pattern = r\"model\\.layers\\.\\d+\\.block_sparse_moe\\.mlp\\.deepspeed_moe\\.experts\\.deepspeed_experts\\.\\d+\\.w\\d+\\.weight\"\n",
" expert_params = [s for s in state_dict.keys() if re.search(pattern, s)]\n",
"\n",
" for param_name in expert_params:\n",
" param_tensor = state_dict[param_name].to('cuda')\n",
" output = [torch.zeros_like(param_tensor) for _ in range(world_size)]\n",
" torch.distributed.gather(param_tensor, gather_list=output if rank == 0 else None, dst=0, group=None)\n",
" # rename from local rank to global rank\n",
" for gather_rank, gather_param in enumerate(output):\n",
" experts_per_rank = self.num_experts // self.moe_expert_parallel_size\n",
" new_expert_number = gather_rank * experts_per_rank + self._expert_number_from_param_name(param_name)\n",
" new_param_name = re.sub(r'(experts\\.)(\\d+)(\\.)', rf'\\g<1>{new_expert_number}\\3', param_name)\n",
" state_dict[new_param_name] = gather_param\n",
" if rank == 0:\n",
" print(f\"adding to state_dict and renaming: {param_name} -> {new_param_name}\")\n",
" \n",
" # Handle custom LoRA implementation \n",
" # TODO(rajhans): the part below is untested and shows up when doing lora training. Should not affect inference.\n",
" if self.is_deepspeed_lora:\n",
" for param_name in list(state_dict.keys()): # Use list to avoid RuntimeError due to changing size during iteration \n",
" if param_name.endswith(\"base_weight\"): \n",
" base_weight = state_dict[param_name].to('cuda')\n",
" \n",
" # If the base weight is sharded, gather weights from multiple ranks and concatenate \n",
" # except if the weights are from deespeed_moe which is not sharded (due to EP). \n",
" if self.shard_base_weights_if_doing_lora and 'deepspeed_moe.experts.deepspeed_experts' not in param_name:\n",
" gathered_weights = [torch.zeros_like(base_weight, \n",
" device=base_weight.device, dtype=base_weight.dtype) for _ in range(world_size)]\n",
" torch.distributed.gather(base_weight, gather_list=gathered_weights if rank == 0 else None, dst=0, group=None) \n",
" base_weight = torch.cat(gathered_weights, dim=1)\n",
"\n",
"\n",
" ## The part below is useful if we want to output HF transformer path weights, but commenting it for now \n",
" # Merge the LoRA weights into the base weights \n",
" # lora_weight_1 = state_dict.get(param_name.replace(\"base_weight\", \"lora_weight_1.weight\")) \n",
" # lora_weight_2 = state_dict.get(param_name.replace(\"base_weight\", \"lora_weight_2.weight\")) \n",
" # if lora_weight_1 is not None and lora_weight_2 is not None:\n",
" # lora_weights = torch.matmul(lora_weight_2, lora_weight_1)\n",
" # base_weight += lora_weights\n",
" # else:\n",
" # raise ValueError \n",
"\n",
" # # Rename the base weight to weight \n",
" # new_param_name = param_name.replace(\"base_weight\", \"weight\") \n",
" # state_dict[new_param_name] = base_weight \n",
" \n",
" # Remove the base weight from the state dict \n",
" # del state_dict[param_name] \n",
" return state_dict \n",
"\n",
"\n",
" def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):\n",
" if not self.use_deepspeed_moe:\n",
" return super()._load_from_state_dict(\n",
" state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs\n",
" )\n",
"\n",
" world_size = torch.distributed.get_world_size() if torch.distributed.is_initialized() else 1\n",
" #TODO(jeffra): currently assumes fine-tuning only on one node, fix for world_size != ep size\n",
" if self.moe_expert_parallel_size > 1:\n",
" assert self.moe_expert_parallel_size == world_size, \\\n",
" f\"currently only support expert parallel size equal to world size but {self.moe_expert_parallel_size=} and {world_size=}\"\n",
"\n",
" rank = torch.distributed.get_rank() if torch.distributed.is_initialized() else 0\n",
" num_local_experts = self.num_experts // self.moe_expert_parallel_size\n",
" local_expert_range = range(num_local_experts * rank, num_local_experts * rank + num_local_experts)\n",
"\n",
" # no deepspeed\n",
" # model.layers.1.block_sparse_moe.experts.10.w1.weight\n",
" # model.layers.1.block_sparse_moe.gate.weight\n",
" # w. deepspeed\n",
" # model.layers.1.block_sparse_moe.mlp.deepspeed_moe.gate.wg.weight\n",
" # model.layers.1.block_sparse_moe.mlp.deepspeed_moe.experts.deepspeed_experts.10.w1.weight\n",
"\n",
" gate_pattern = r'model\\.layers\\.\\d+\\.block_sparse_moe\\.gate\\.weight'\n",
"\n",
" expert_params_to_keep = []\n",
" expert_params_to_remove = []\n",
" gate_params = []\n",
" for param_name in state_dict.keys():\n",
" expert_number = self._expert_number_from_param_name(param_name)\n",
" if expert_number is not None:\n",
" if expert_number in local_expert_range:\n",
" expert_params_to_keep.append(param_name)\n",
" else:\n",
" expert_params_to_remove.append(param_name)\n",
" elif re.search(gate_pattern, param_name):\n",
" gate_params.append(param_name)\n",
"\n",
" # drop all experts in the state_dict that we don't need locally\n",
" for param_name in expert_params_to_remove:\n",
" print(f'{rank=} dropping {param_name}')\n",
" del state_dict[param_name]\n",
"\n",
" # rename remaining experts to align with the local config\n",
" for param_name in expert_params_to_keep:\n",
" # adjust expert number wrt expert parallelism\n",
" new_expert_number = self._expert_number_from_param_name(param_name) % num_local_experts\n",
" new_param_name = re.sub(r'(experts\\.)(\\d+)(\\.)', rf'\\g<1>{new_expert_number}\\3', param_name)\n",
"\n",
" # use deepspeed moe param path\n",
" split_param_name = new_param_name.split('.')\n",
" idx = split_param_name.index('experts')\n",
" ds_moe_path = \"mlp.deepspeed_moe.experts.deepspeed_experts\".split('.')\n",
" new_param_name = split_param_name[0:idx] + ds_moe_path + split_param_name[idx+1:]\n",
" new_param_name = \".\".join(new_param_name)\n",
"\n",
" print(f'Deepspeed {rank=}, renaming {param_name} -> {new_param_name}')\n",
" state_dict[new_param_name] = state_dict.pop(param_name)\n",
"\n",
" # rename gate params\n",
" ds_suffix = \"mlp.deepspeed_moe.gate.wg.weight\".split('.')\n",
" for param_name in gate_params:\n",
" new_param_name = '.'.join(param_name.split('.')[:4] + ds_suffix)\n",
" print(f'Gating: {rank=}, renaming {param_name} -> {new_param_name}')\n",
" state_dict[new_param_name] = state_dict.pop(param_name)\n",
"\n",
" # If deepspeed lora is enabled, then we need to rename weight to base_weight.\n",
" # Furthermore, if the base_weight is sharded, we need to shard each weight and select the slice of local rank.\n",
" if self.is_deepspeed_lora:\n",
" local_state_dict = self.state_dict()\n",
" for param_name in local_state_dict:\n",
" if not param_name.endswith(\"base_weight\"):\n",
" continue\n",
"\n",
" incoming_param_name = param_name.replace(\"base_weight\", \"weight\")\n",
" if incoming_param_name not in state_dict:\n",
" continue\n",
"\n",
" incoming_param = state_dict[incoming_param_name]\n",
"\n",
" shape_local = local_state_dict[param_name].shape\n",
" shape_incoming = incoming_param.shape\n",
" if 'deepspeed_moe' in incoming_param_name:\n",
" assert shape_local == shape_incoming, \"deepspeed moe weights are never sharded\"\n",
" else:\n",
" assert shape_incoming[1] == shape_local[1] * world_size, \"weights should be sharded equally across world size\"\n",
" incoming_param = incoming_param[:, rank*shape_local[1]: (rank+1)*shape_local[1]]\n",
" print(f'Deepspeed lora: {rank=}, renaming {incoming_param_name} -> {param_name}')\n",
" state_dict[param_name] = incoming_param\n",
" del state_dict[incoming_param_name]\n",
"\n",
" return super()._load_from_state_dict(\n",
" state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs\n",
" )\n",
"\n",
" @add_start_docstrings_to_model_forward(MIXTRAL_INPUTS_DOCSTRING)\n",
" @replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)\n",
" # Ignore copy\n",
" def forward(\n",
" self,\n",
" input_ids: torch.LongTensor = None,\n",
" attention_mask: Optional[torch.Tensor] = None,\n",
" position_ids: Optional[torch.LongTensor] = None,\n",
" past_key_values: Optional[List[torch.FloatTensor]] = None,\n",
" inputs_embeds: Optional[torch.FloatTensor] = None,\n",
" labels: Optional[torch.LongTensor] = None,\n",
" use_cache: Optional[bool] = None,\n",
" output_attentions: Optional[bool] = None,\n",
" output_hidden_states: Optional[bool] = None,\n",
" return_dict: Optional[bool] = None,\n",
" ) -> Union[Tuple, MoeCausalLMOutputWithPast]:\n",
" r\"\"\"\n",
" Args:\n",
" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n",
" Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n",
" config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n",
" (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n",
"\n",
" Returns:\n",
"\n",
" Example:\n",
"\n",
" ```python\n",
" >>> from transformers import AutoTokenizer, ArcticForCausalLM\n",
"\n",
" >>> model = ArcticForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)\n",
" >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)\n",
"\n",
" >>> prompt = \"Hey, are you conscious? Can you talk to me?\"\n",
" >>> inputs = tokenizer(prompt, return_tensors=\"pt\")\n",
"\n",
" >>> # Generate\n",
" >>> generate_ids = model.generate(inputs.input_ids, max_length=30)\n",
" >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n",
" \"Hey, are you conscious? Can you talk to me?\\nI'm not conscious, but I can talk to you.\"\n",
" ```\"\"\"\n",
"\n",
" output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n",
"\n",
" output_hidden_states = (\n",
" output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n",
" )\n",
" return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n",
"\n",
" # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)\n",
" outputs = self.model(\n",
" input_ids=input_ids,\n",
" attention_mask=attention_mask,\n",
" position_ids=position_ids,\n",
" past_key_values=past_key_values,\n",
" inputs_embeds=inputs_embeds,\n",
" use_cache=use_cache,\n",
" output_attentions=output_attentions,\n",
" output_hidden_states=output_hidden_states,\n",
" return_dict=return_dict,\n",
" )\n",
" hidden_states = outputs[0]\n",
" logits = self.lm_head(hidden_states)\n",
" logits = logits.float()\n",
"\n",
" loss = None\n",
" if labels is not None:\n",
" # Shift so that tokens < n predict n\n",
" shift_logits = logits[..., :-1, :].contiguous()\n",
" shift_labels = labels[..., 1:].contiguous()\n",
" # Flatten the tokens\n",
" loss_fct = CrossEntropyLoss()\n",
" shift_logits = shift_logits.view(-1, self.config.vocab_size)\n",
" shift_labels = shift_labels.view(-1)\n",
" # Enable model parallelism\n",
" shift_labels = shift_labels.to(shift_logits.device)\n",
" loss = loss_fct(shift_logits, shift_labels)\n",
"\n",
" # Move to same device for model parallelism.\n",
" aux_loss = sum([out.to(logits.device) for out in outputs[-1]])\n",
" if labels is not None:\n",
" loss += self.router_aux_loss_coef * aux_loss\n",
"\n",
" if not return_dict:\n",
" output = (logits,) + outputs[1:]\n",
" # torch.distributed.barrier()\n",
" return (loss,) + output if loss is not None else output\n",
"\n",
" return MoeCausalLMOutputWithPast(\n",
" loss=loss,\n",
" aux_loss=aux_loss,\n",
" logits=logits,\n",
" past_key_values=outputs.past_key_values,\n",
" hidden_states=outputs.hidden_states,\n",
" attentions=outputs.attentions,\n",
" )\n",
"\n",
" def prepare_inputs_for_generation(\n",
" self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs\n",
" ):\n",
" # Omit tokens covered by past_key_values\n",
" if past_key_values is not None:\n",
" if isinstance(past_key_values, Cache):\n",
" cache_length = past_key_values.get_seq_length()\n",
" past_length = past_key_values.seen_tokens\n",
" max_cache_length = past_key_values.get_max_length()\n",
" else:\n",
" cache_length = past_length = past_key_values[0][0].shape[2]\n",
" max_cache_length = None\n",
"\n",
" # Keep only the unprocessed tokens:\n",
" # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where\n",
" # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as\n",
" # input)\n",
" if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:\n",
" input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]\n",
" # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard\n",
" # input_ids based on the past_length.\n",
" elif past_length < input_ids.shape[1]:\n",
" input_ids = input_ids[:, past_length:]\n",
" # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.\n",
"\n",
" # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.\n",
" if (\n",
" max_cache_length is not None\n",
" and attention_mask is not None\n",
" and cache_length + input_ids.shape[1] > max_cache_length\n",
" ):\n",
" attention_mask = attention_mask[:, -max_cache_length:]\n",
"\n",
" position_ids = kwargs.get(\"position_ids\", None)\n",
" if attention_mask is not None and position_ids is None:\n",
" # create position_ids on the fly for batch generation\n",
" position_ids = attention_mask.long().cumsum(-1) - 1\n",
" position_ids.masked_fill_(attention_mask == 0, 1)\n",
" if past_key_values:\n",
" position_ids = position_ids[:, -input_ids.shape[1] :]\n",
"\n",
" # if `inputs_embeds` are passed, we only want to use them in the 1st generation step\n",
" if inputs_embeds is not None and past_key_values is None:\n",
" model_inputs = {\"inputs_embeds\": inputs_embeds}\n",
" else:\n",
" model_inputs = {\"input_ids\": input_ids}\n",
"\n",
" model_inputs.update(\n",
" {\n",
" \"position_ids\": position_ids,\n",
" \"past_key_values\": past_key_values,\n",
" \"use_cache\": kwargs.get(\"use_cache\"),\n",
" \"attention_mask\": attention_mask,\n",
" }\n",
" )\n",
" return model_inputs\n",
"\n",
" @staticmethod\n",
" def _reorder_cache(past_key_values, beam_idx):\n",
" reordered_past = ()\n",
" for layer_past in past_key_values:\n",
" reordered_past += (\n",
" tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),\n",
" )\n",
" return reordered_past\n",
"\n",
"\n",
"@add_start_docstrings(\n",
" \"\"\"\n",
" The Arctic Model transformer with a sequence classification head on top (linear layer).\n",
"\n",
" [`ArcticForSequenceClassification`] uses the last token in order to do the classification, as other causal models\n",
" (e.g. GPT-2) do.\n",
"\n",
" Since it does classification on the last token, it requires to know the position of the last token. If a\n",
" `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If\n",
" no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the\n",
" padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in\n",
" each row of the batch).\n",
" \"\"\",\n",
" ARCTIC_START_DOCSTRING,\n",
")\n",
"# Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Arctic, LLAMA->MIXTRAL\n",
"class ArcticForSequenceClassification(ArcticPreTrainedModel):\n",
" def __init__(self, config):\n",
" super().__init__(config)\n",
" self.num_labels = config.num_labels\n",
" self.model = ArcticModel(config)\n",
" self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)\n",
"\n",
" # Initialize weights and apply final processing\n",
" self.post_init()\n",
"\n",
" def get_input_embeddings(self):\n",
" return self.model.embed_tokens\n",
"\n",
" def set_input_embeddings(self, value):\n",
" self.model.embed_tokens = value\n",
"\n",
" @add_start_docstrings_to_model_forward(MIXTRAL_INPUTS_DOCSTRING)\n",
" def forward(\n",
" self,\n",
" input_ids: torch.LongTensor = None,\n",
" attention_mask: Optional[torch.Tensor] = None,\n",
" position_ids: Optional[torch.LongTensor] = None,\n",
" past_key_values: Optional[List[torch.FloatTensor]] = None,\n",
" inputs_embeds: Optional[torch.FloatTensor] = None,\n",
" labels: Optional[torch.LongTensor] = None,\n",
" use_cache: Optional[bool] = None,\n",
" output_attentions: Optional[bool] = None,\n",
" output_hidden_states: Optional[bool] = None,\n",
" return_dict: Optional[bool] = None,\n",
" ) -> Union[Tuple, SequenceClassifierOutputWithPast]:\n",
" r\"\"\"\n",
" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n",
" Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n",
" config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n",
" `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n",
" \"\"\"\n",
" return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n",
"\n",
" transformer_outputs = self.model(\n",
" input_ids,\n",
" attention_mask=attention_mask,\n",
" position_ids=position_ids,\n",
" past_key_values=past_key_values,\n",
" inputs_embeds=inputs_embeds,\n",
" use_cache=use_cache,\n",
" output_attentions=output_attentions,\n",
" output_hidden_states=output_hidden_states,\n",
" return_dict=return_dict,\n",
" )\n",
" hidden_states = transformer_outputs[0]\n",
" logits = self.score(hidden_states)\n",
"\n",
" if input_ids is not None:\n",
" batch_size = input_ids.shape[0]\n",
" else:\n",
" batch_size = inputs_embeds.shape[0]\n",
"\n",
" if self.config.pad_token_id is None and batch_size != 1:\n",
" raise ValueError(\"Cannot handle batch sizes > 1 if no padding token is defined.\")\n",
" if self.config.pad_token_id is None:\n",
" sequence_lengths = -1\n",
" else:\n",
" if input_ids is not None:\n",
" # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility\n",
" sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1\n",
" sequence_lengths = sequence_lengths % input_ids.shape[-1]\n",
" sequence_lengths = sequence_lengths.to(logits.device)\n",
" else:\n",
" sequence_lengths = -1\n",
"\n",
" pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]\n",
"\n",
" loss = None\n",
" if labels is not None:\n",
" labels = labels.to(logits.device)\n",
" if self.config.problem_type is None:\n",
" if self.num_labels == 1:\n",
" self.config.problem_type = \"regression\"\n",
" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):\n",
" self.config.problem_type = \"single_label_classification\"\n",
" else:\n",
" self.config.problem_type = \"multi_label_classification\"\n",
"\n",
" if self.config.problem_type == \"regression\":\n",
" loss_fct = MSELoss()\n",
" if self.num_labels == 1:\n",
" loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())\n",
" else:\n",
" loss = loss_fct(pooled_logits, labels)\n",
" elif self.config.problem_type == \"single_label_classification\":\n",
" loss_fct = CrossEntropyLoss()\n",
" loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))\n",
" elif self.config.problem_type == \"multi_label_classification\":\n",
" loss_fct = BCEWithLogitsLoss()\n",
" loss = loss_fct(pooled_logits, labels)\n",
" if not return_dict:\n",
" output = (pooled_logits,) + transformer_outputs[1:]\n",
" return ((loss,) + output) if loss is not None else output\n",
"\n",
" return SequenceClassifierOutputWithPast(\n",
" loss=loss,\n",
" logits=pooled_logits,\n",
" past_key_values=transformer_outputs.past_key_values,\n",
" hidden_states=transformer_outputs.hidden_states,\n",
" attentions=transformer_outputs.attentions,\n",
" )\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"!cat ~/.cache/huggingface/modules/transformers_modules/Snowflake/snowflake-arctic-instruct/f9281b708c4e07b2348d2f7d71a9816d32eca8a4/tokenization_arctic.py"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "jQl7TH1eqAed",
"outputId": "20e10331-3a6c-417c-f0cc-7e7e69055caa"
},
"execution_count": 12,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"\"\"\"Tokenization classes for Arctic.\"\"\"\n",
"\n",
"from typing import Any, Dict, Optional\n",
"\n",
"from transformers.models.llama import LlamaTokenizer\n",
"\n",
"\n",
"class ArcticTokenizer(LlamaTokenizer):\n",
"\n",
" def __init__(\n",
" self,\n",
" vocab_file,\n",
" unk_token=\"<unk>\",\n",
" bos_token=\"<s>\",\n",
" eos_token=\"</s>\",\n",
" pad_token=None,\n",
" sp_model_kwargs: Optional[Dict[str, Any]] = None,\n",
" add_bos_token=True,\n",
" add_eos_token=False,\n",
" clean_up_tokenization_spaces=False,\n",
" use_default_system_prompt=False,\n",
" spaces_between_special_tokens=False,\n",
" legacy=False,\n",
" add_prefix_space=True,\n",
" **kwargs,\n",
" ):\n",
" # Same as LlamaTokenizer except default legacy=False.\n",
" super().__init__(\n",
" vocab_file,\n",
" bos_token=bos_token,\n",
" eos_token=eos_token,\n",
" unk_token=unk_token,\n",
" pad_token=pad_token,\n",
" sp_model_kwargs=sp_model_kwargs,\n",
" add_bos_token=add_bos_token,\n",
" add_eos_token=add_eos_token,\n",
" clean_up_tokenization_spaces=clean_up_tokenization_spaces,\n",
" use_default_system_prompt=use_default_system_prompt,\n",
" spaces_between_special_tokens=spaces_between_special_tokens,\n",
" legacy=legacy,\n",
" add_prefix_space=add_prefix_space,\n",
" **kwargs,\n",
" )\n",
"\n",
" @property\n",
" def default_chat_template(self):\n",
" \"\"\"\n",
" This template formats inputs in the standard Arctic format.\n",
" \"\"\"\n",
" return (\n",
" \"{% for message in messages %}\"\n",
" \"{{'<|im_start|>' + message['role'] + '\\n' + message['content'] + '<|im_end|>' + '\\n'}}\"\n",
" \"{% endfor %}\"\n",
" \"{% if add_generation_prompt %}\"\n",
" \"{{ '<|im_start|>assistant\\n' }}\"\n",
" \"{% endif %}\"\n",
" )\n"
]
}
]
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "PDHHPXMtqCd8"
},
"execution_count": null,
"outputs": []
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment