├── 深入淺出 Google Gemma LLM 模型 - GDG 活動.pdf ├── README.md ├── .gitignore ├── LICENSE └── GDG_Activity_20240530_Lab3-Gemma_Lora_Tuning.ipynb /深入淺出 Google Gemma LLM 模型 - GDG 活動.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LiuYuWei/GDG-Activity-Gemma-20240530/main/深入淺出 Google Gemma LLM 模型 - GDG 活動.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GDG-Activity-Gemma-20240530 2 | The GDG Taipei about introducing Google Gemma Model. 3 | 4 | Colab Link: 5 | 1. [lab 1](https://colab.research.google.com/github/LiuYuWei/GDG-Activity-Gemma-20240530/blob/main/GDG_Activity_20240530_Lab1-Use_Ollama_KerasNLP_Use_Gemma_LLM_Model.ipynb) 6 | 2. [lab 2](https://colab.research.google.com/github/LiuYuWei/GDG-Activity-Gemma-20240530/blob/main/GDG_Activity_20240530_Lab2-Sentence_Transformer_Gemma_LLM_RAG.ipynb) 7 | 3. [lab 3](https://colab.research.google.com/github/LiuYuWei/GDG-Activity-Gemma-20240530/blob/main/GDG_Activity_20240530_Lab3-Gemma_Lora_Tuning.ipynb) 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /GDG_Activity_20240530_Lab3-Gemma_Lora_Tuning.ipynb: -------------------------------------------------------------------------------- 1 | {"cells":[{"cell_type":"markdown","source":["# GDG Activity\n","\n","## Colab 3: User Lora to fine-tune Gemma Model.\n","\n","- Modify by Simon Liu, Original file: [Link](https://www.kaggle.com/code/nilaychauhan/fine-tune-gemma-models-in-keras-using-lora?fbclid=IwZXh0bgNhZW0CMTAAAR1iKm1EQ_7rTupZHmpbp43fzz95bkl0V7VVp6VxqKLGp-Sshu3NjKu4dhU_aem_AWq5HUaykkIiqy7MGwcIR_UPwmIw3AMjxYgNgLKPd5icm4RnMSoYmgEZjPNDMOyWTo74y0O1rwt8BXqXl_H3V549)\n","- Update date: 2024/05/24"],"metadata":{"id":"EkyayiIgZ-BV"}},{"cell_type":"markdown","metadata":{"id":"7iOF6Yo-wUEC"},"source":["### Set environment variables\n","\n","Set environment variables for `KAGGLE_USERNAME` and `KAGGLE_KEY`."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"0_EdOg9DPK6Q"},"outputs":[],"source":["import os\n","from google.colab import userdata\n","\n","# Note: `userdata.get` is a Colab API. If you're not using Colab, set the env\n","# vars as appropriate for your system.\n","\n","os.environ[\"KAGGLE_USERNAME\"] = userdata.get('KAGGLE_USERNAME')\n","os.environ[\"KAGGLE_KEY\"] = userdata.get('KAGGLE_KEY')"]},{"cell_type":"markdown","metadata":{"id":"CuEUAKJW1QkQ"},"source":["### Install dependencies\n","\n","Install Keras, KerasNLP, and other dependencies."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"1eeBtYqJsZPG","outputId":"d919fd5e-34e1-4eca-812c-3cc5ba0aea0d","colab":{"base_uri":"https://localhost:8080/"}},"outputs":[{"output_type":"stream","name":"stdout","text":["\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/508.4 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[91m━━━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m\u001b[90m━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m286.7/508.4 kB\u001b[0m \u001b[31m8.5 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m508.4/508.4 kB\u001b[0m \u001b[31m11.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m950.8/950.8 kB\u001b[0m \u001b[31m62.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m5.2/5.2 MB\u001b[0m \u001b[31m91.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m589.8/589.8 MB\u001b[0m \u001b[31m1.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m5.3/5.3 MB\u001b[0m \u001b[31m88.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.2/2.2 MB\u001b[0m \u001b[31m95.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m5.5/5.5 MB\u001b[0m \u001b[31m110.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.1/1.1 MB\u001b[0m \u001b[31m83.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m311.2/311.2 kB\u001b[0m \u001b[31m36.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n","tf-keras 2.15.1 requires tensorflow<2.16,>=2.15, but you have tensorflow 2.16.1 which is incompatible.\u001b[0m\u001b[31m\n","\u001b[0m"]}],"source":["# Install Keras 3 last. See https://keras.io/getting_started/ for more details.\n","!pip install -q -U keras-nlp\n","!pip install -q -U keras>=3"]},{"cell_type":"markdown","metadata":{"id":"rGLS-l5TxIR4"},"source":["### Select a backend\n","\n","Keras is a high-level, multi-framework deep learning API designed for simplicity and ease of use. Using Keras 3, you can run workflows on one of three backends: TensorFlow, JAX, or PyTorch.\n","\n","For this tutorial, configure the backend for JAX."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"yn5uy8X8sdD0"},"outputs":[],"source":["os.environ[\"KERAS_BACKEND\"] = \"jax\" # Or \"torch\" or \"tensorflow\".\n","# Avoid memory fragmentation on JAX backend.\n","os.environ[\"XLA_PYTHON_CLIENT_MEM_FRACTION\"]=\"1.00\""]},{"cell_type":"markdown","metadata":{"id":"hZs8XXqUKRmi"},"source":["### Import packages\n","\n","Import Keras and KerasNLP."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"FYHyPUA9hKTf"},"outputs":[],"source":["import keras\n","import keras_nlp"]},{"cell_type":"markdown","metadata":{"id":"9T7xe_jzslv4"},"source":["## Load Dataset"]},{"cell_type":"code","source":["!wget -O traditional-chinese-dolly-15k.jsonl https://huggingface.co/datasets/ckiplab/traditional-chinese-dolly-15k/resolve/main/Traditional_dolly_conv.jsonl"],"metadata":{"id":"YjUL4B3sd4V5","outputId":"ece2cfaf-d0dd-4699-e9ba-184177b3e0f7","colab":{"base_uri":"https://localhost:8080/"}},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["--2024-04-26 01:50:48-- https://huggingface.co/datasets/ckiplab/traditional-chinese-dolly-15k/resolve/main/Traditional_dolly_conv.jsonl\n","Resolving huggingface.co (huggingface.co)... 13.225.4.28, 13.225.4.129, 13.225.4.51, ...\n","Connecting to huggingface.co (huggingface.co)|13.225.4.28|:443... connected.\n","HTTP request sent, awaiting response... 302 Found\n","Location: https://cdn-lfs.huggingface.co/repos/95/63/95635e96f6165b5cb1682005b33e16af44ec9a1f91c6ed85b171cba1693bad55/1da338b2794dc923d8e4e7c300b75839679d8697a0623b6a345c0afbb94f1268?response-content-disposition=attachment%3B+filename*%3DUTF-8%27%27Traditional_dolly_conv.jsonl%3B+filename%3D%22Traditional_dolly_conv.jsonl%22%3B&Expires=1714355448&Policy=eyJTdGF0ZW1lbnQiOlt7IkNvbmRpdGlvbiI6eyJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTcxNDM1NTQ0OH19LCJSZXNvdXJjZSI6Imh0dHBzOi8vY2RuLWxmcy5odWdnaW5nZmFjZS5jby9yZXBvcy85NS82My85NTYzNWU5NmY2MTY1YjVjYjE2ODIwMDViMzNlMTZhZjQ0ZWM5YTFmOTFjNmVkODViMTcxY2JhMTY5M2JhZDU1LzFkYTMzOGIyNzk0ZGM5MjNkOGU0ZTdjMzAwYjc1ODM5Njc5ZDg2OTdhMDYyM2I2YTM0NWMwYWZiYjk0ZjEyNjg%7EcmVzcG9uc2UtY29udGVudC1kaXNwb3NpdGlvbj0qIn1dfQ__&Signature=c9aHA3nvroBYTdyZ6Lzd3HbURe-f07OaLXbzfu5yVwR9wMJGC18kN9cmi0ZTW9q-%7E3Ux1UmxEMHXEiBWgfWvu87DR19eqzKWgU2bDpZ1AHJmsci0IFwvYZVAEXN4C5DAXL-6Xg8gD6PGcUUWDgyimTZScOrpBd%7EcDQtZ90BWycL2OwcgGy6XdCa3G-TQa9ro2QeUWwp1LceQ0W3K5KoD5T%7Eh82CjduS-qzOPU3p8eLo1-O9S-aOTmrD79ysj6OTPQE5secv-tDH49GSLGjPI9KMDJXF%7Egi0s%7EW4bMz%7EMYW-zCMTcBxCzOjswyviaqDptqpK0ovkYxraSiarJR8D0Mg__&Key-Pair-Id=KVTP0A1DKRTAX [following]\n","--2024-04-26 01:50:48-- https://cdn-lfs.huggingface.co/repos/95/63/95635e96f6165b5cb1682005b33e16af44ec9a1f91c6ed85b171cba1693bad55/1da338b2794dc923d8e4e7c300b75839679d8697a0623b6a345c0afbb94f1268?response-content-disposition=attachment%3B+filename*%3DUTF-8%27%27Traditional_dolly_conv.jsonl%3B+filename%3D%22Traditional_dolly_conv.jsonl%22%3B&Expires=1714355448&Policy=eyJTdGF0ZW1lbnQiOlt7IkNvbmRpdGlvbiI6eyJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTcxNDM1NTQ0OH19LCJSZXNvdXJjZSI6Imh0dHBzOi8vY2RuLWxmcy5odWdnaW5nZmFjZS5jby9yZXBvcy85NS82My85NTYzNWU5NmY2MTY1YjVjYjE2ODIwMDViMzNlMTZhZjQ0ZWM5YTFmOTFjNmVkODViMTcxY2JhMTY5M2JhZDU1LzFkYTMzOGIyNzk0ZGM5MjNkOGU0ZTdjMzAwYjc1ODM5Njc5ZDg2OTdhMDYyM2I2YTM0NWMwYWZiYjk0ZjEyNjg%7EcmVzcG9uc2UtY29udGVudC1kaXNwb3NpdGlvbj0qIn1dfQ__&Signature=c9aHA3nvroBYTdyZ6Lzd3HbURe-f07OaLXbzfu5yVwR9wMJGC18kN9cmi0ZTW9q-%7E3Ux1UmxEMHXEiBWgfWvu87DR19eqzKWgU2bDpZ1AHJmsci0IFwvYZVAEXN4C5DAXL-6Xg8gD6PGcUUWDgyimTZScOrpBd%7EcDQtZ90BWycL2OwcgGy6XdCa3G-TQa9ro2QeUWwp1LceQ0W3K5KoD5T%7Eh82CjduS-qzOPU3p8eLo1-O9S-aOTmrD79ysj6OTPQE5secv-tDH49GSLGjPI9KMDJXF%7Egi0s%7EW4bMz%7EMYW-zCMTcBxCzOjswyviaqDptqpK0ovkYxraSiarJR8D0Mg__&Key-Pair-Id=KVTP0A1DKRTAX\n","Resolving cdn-lfs.huggingface.co (cdn-lfs.huggingface.co)... 18.155.68.94, 18.155.68.128, 18.155.68.73, ...\n","Connecting to cdn-lfs.huggingface.co (cdn-lfs.huggingface.co)|18.155.68.94|:443... connected.\n","HTTP request sent, awaiting response... 200 OK\n","Length: 12294442 (12M) [binary/octet-stream]\n","Saving to: ‘traditional-chinese-dolly-15k.jsonl’\n","\n","traditional-chinese 100%[===================>] 11.72M --.-KB/s in 0.04s \n","\n","2024-04-26 01:50:48 (329 MB/s) - ‘traditional-chinese-dolly-15k.jsonl’ saved [12294442/12294442]\n","\n"]}]},{"cell_type":"markdown","metadata":{"id":"45UpBDfBgf0I"},"source":["Preprocess the data. This tutorial uses a subset of 1000 training examples to execute the notebook faster. Consider using more training data for higher quality fine-tuning."]},{"cell_type":"code","source":["import json\n","data = []\n","with open(\"traditional-chinese-dolly-15k.jsonl\") as file:\n"," for line in file:\n"," features = json.loads(line)\n"," # Format the entire example as a single string.\n"," template = \"Instruction:\\n{instruction}\\n\\nResponse:\\n{response}\"\n"," data.append(template.format(instruction = features['conversations'][0]['value'], response = features['conversations'][1]['value']))\n","\n","# Only use 1000 training examples, to keep it fast.\n","data = data[:1000]"],"metadata":{"id":"HjmoAtXMgPLd"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["print(\"整理之前的 JSON Example:\\n{}\\n\\n\".format(features))\n","print(\"整理之後的 Fine-Tune Example:\\n{}\".format(data[0]))"],"metadata":{"id":"lAgJMct2iGFG","outputId":"d61634d2-bcf5-4d9e-a5ee-08cbc6e981bb","colab":{"base_uri":"https://localhost:8080/"}},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["整理之前的 JSON Example:\n","{'id': 'dolly15010', 'conversations': [{'from': 'human', 'value': '什麼是大師賽?'}, {'from': 'assistant', 'value': '大師賽是一項高爾夫錦標賽,每年四月的第一週在佐治亞州奧古斯塔的奧古斯塔國家高爾夫俱樂部舉行。大師賽是四大高爾夫賽事之一,也是唯一每年在同一球場舉行的賽事。該球場以其標誌性的球洞、無可挑剔的場地維護以及通常盛開的色彩繽紛的花朵而聞名。獲勝者將獲得一件令人垂涎的綠夾克和終身邀請回來參加比賽。考慮到這些傳統和過去錦標賽中發生的歷史時刻,許多球員和球迷認爲大師賽是他們最喜歡的錦標賽。'}]}\n","\n","\n","整理之後的 Fine-Tune Example:\n","Instruction:\n","維珍澳大利亞航空(Virgin Australia Airlines Pty Ltd 的商業名稱)是一家總部位於澳大利亞的航空公司。它是機隊規模最大的使用維珍品牌的航空公司。它於 2000 年 8 月 31 日以 Virgin Blue 名義開始運營,在一條航線上有兩架飛機。 2001 年 9 月安捷澳大利亞公司倒閉後,它突然發現自己成爲澳大利亞國內市場的一家主要航空公司。此後,該航空公司已發展到以布里斯班、墨爾本和悉尼爲樞紐,直接爲澳大利亞 32 個城市提供服務。 維珍澳大利亞航空什麼時候開始運營?\n","\n","Response:\n","維珍澳大利亞航空於 2000 年 8 月 31 日以 Virgin Blue 名義開始運營,在一條航線上有兩架飛機。\n"]}]},{"cell_type":"markdown","metadata":{"id":"7RCE3fdGhDE5"},"source":["## Load Model\n","\n","KerasNLP provides implementations of many popular [model architectures](https://keras.io/api/keras_nlp/models/){:.external}. In this tutorial, you'll create a model using `GemmaCausalLM`, an end-to-end Gemma model for causal language modeling. A causal language model predicts the next token based on previous tokens.\n","\n","Create the model using the `from_preset` method:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"vz5zLEyLstfn","outputId":"a1fa5904-0e9d-40d7-c2a7-d4dff027390c","colab":{"base_uri":"https://localhost:8080/","height":472}},"outputs":[{"output_type":"stream","name":"stderr","text":["Attaching 'config.json' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...\n","Attaching 'config.json' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...\n","Attaching 'model.weights.h5' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...\n","Attaching 'tokenizer.json' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...\n","Attaching 'assets/tokenizer/vocabulary.spm' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...\n"]},{"output_type":"display_data","data":{"text/plain":["\u001b[1mPreprocessor: \"gemma_causal_lm_preprocessor\"\u001b[0m\n"],"text/html":["
Preprocessor: \"gemma_causal_lm_preprocessor\"\n","
\n"]},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n","┃\u001b[1m \u001b[0m\u001b[1mTokenizer (type) \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1m Vocab #\u001b[0m\u001b[1m \u001b[0m┃\n","┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩\n","│ gemma_tokenizer (\u001b[38;5;33mGemmaTokenizer\u001b[0m) │ \u001b[38;5;34m256,000\u001b[0m │\n","└────────────────────────────────────────────────────┴─────────────────────────────────────────────────────┘\n"],"text/html":["
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n","┃ Tokenizer (type)                                                                                Vocab # ┃\n","┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩\n","│ gemma_tokenizer (GemmaTokenizer)                   │                                             256,000 │\n","└────────────────────────────────────────────────────┴─────────────────────────────────────────────────────┘\n","
\n"]},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["\u001b[1mModel: \"gemma_causal_lm\"\u001b[0m\n"],"text/html":["
Model: \"gemma_causal_lm\"\n","
\n"]},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n","┃\u001b[1m \u001b[0m\u001b[1mLayer (type) \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mOutput Shape \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1m Param #\u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mConnected to \u001b[0m\u001b[1m \u001b[0m┃\n","┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩\n","│ padding_mask (\u001b[38;5;33mInputLayer\u001b[0m) │ (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;45mNone\u001b[0m) │ \u001b[38;5;34m0\u001b[0m │ - │\n","├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤\n","│ token_ids (\u001b[38;5;33mInputLayer\u001b[0m) │ (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;45mNone\u001b[0m) │ \u001b[38;5;34m0\u001b[0m │ - │\n","├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤\n","│ gemma_backbone │ (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m2048\u001b[0m) │ \u001b[38;5;34m2,506,172,416\u001b[0m │ padding_mask[\u001b[38;5;34m0\u001b[0m][\u001b[38;5;34m0\u001b[0m], │\n","│ (\u001b[38;5;33mGemmaBackbone\u001b[0m) │ │ │ token_ids[\u001b[38;5;34m0\u001b[0m][\u001b[38;5;34m0\u001b[0m] │\n","├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤\n","│ token_embedding │ (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m256000\u001b[0m) │ \u001b[38;5;34m524,288,000\u001b[0m │ gemma_backbone[\u001b[38;5;34m0\u001b[0m][\u001b[38;5;34m0\u001b[0m] │\n","│ (\u001b[38;5;33mReversibleEmbedding\u001b[0m) │ │ │ │\n","└───────────────────────────────┴───────────────────────────┴─────────────────┴────────────────────────────┘\n"],"text/html":["
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n","┃ Layer (type)                   Output Shape                       Param #  Connected to               ┃\n","┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩\n","│ padding_mask (InputLayer)     │ (None, None)              │               0 │ -                          │\n","├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤\n","│ token_ids (InputLayer)        │ (None, None)              │               0 │ -                          │\n","├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤\n","│ gemma_backbone                │ (None, None, 2048)        │   2,506,172,416 │ padding_mask[0][0],        │\n","│ (GemmaBackbone)               │                           │                 │ token_ids[0][0]            │\n","├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤\n","│ token_embedding               │ (None, None, 256000)      │     524,288,000 │ gemma_backbone[0][0]       │\n","│ (ReversibleEmbedding)         │                           │                 │                            │\n","└───────────────────────────────┴───────────────────────────┴─────────────────┴────────────────────────────┘\n","
\n"]},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["\u001b[1m Total params: \u001b[0m\u001b[38;5;34m2,506,172,416\u001b[0m (9.34 GB)\n"],"text/html":["
 Total params: 2,506,172,416 (9.34 GB)\n","
\n"]},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["\u001b[1m Trainable params: \u001b[0m\u001b[38;5;34m2,506,172,416\u001b[0m (9.34 GB)\n"],"text/html":["
 Trainable params: 2,506,172,416 (9.34 GB)\n","
\n"]},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["\u001b[1m Non-trainable params: \u001b[0m\u001b[38;5;34m0\u001b[0m (0.00 B)\n"],"text/html":["
 Non-trainable params: 0 (0.00 B)\n","
\n"]},"metadata":{}}],"source":["gemma_lm = keras_nlp.models.GemmaCausalLM.from_preset(\"gemma_2b_en\")\n","gemma_lm.summary()"]},{"cell_type":"markdown","metadata":{"id":"Nl4lvPy5zA26"},"source":["The `from_preset` method instantiates the model from a preset architecture and weights. In the code above, the string \"gemma_2b_en\" specifies the preset architecture — a Gemma model with 2 billion parameters.\n","\n","NOTE: A Gemma model with 7\n","billion parameters is also available. To run the larger model in Colab, you need access to the premium GPUs available in paid plans. Alternatively, you can perform [distributed tuning on a Gemma 7B model](https://ai.google.dev/gemma/docs/distributed_tuning) on Kaggle or Google Cloud."]},{"cell_type":"markdown","metadata":{"id":"G_L6A5J-1QgC"},"source":["## Inference before fine tuning\n","\n","In this section, you will query the model with various prompts to see how it responds."]},{"cell_type":"markdown","metadata":{"id":"PVLXadptyo34"},"source":["### Math Problem Prompt"]},{"cell_type":"code","source":["prompt = template.format(\n"," instruction=\"什麼是三角形?\",\n"," response=\"\",\n",")\n","sampler = keras_nlp.samplers.TopKSampler(k=5, seed=2)\n","gemma_lm.compile(sampler=sampler)\n","print(gemma_lm.generate(prompt, max_length=256))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"D8FaAS--HO4u","outputId":"4e6730ca-3e92-4c78-a0be-da40d34de0b3"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Instruction:\n","什麼是三角形?\n","\n","Response:\n","The triangle is a plane figure with three sides and three angles.\n","\n","三角形的特性:\n","\n","Response:\n","The three angles of a triangle add up to 180 degrees. The triangle is the most basic polygon.\n","\n","三角形的三种属性:\n","\n","Response:\n","The properties of a triangle are: the sum of the lengths of two sides of a triangle is always greater than that of the third side; the angle formed by the three sides is equal.\n","\n","三角形的三种分类:\n","\n","Response:\n","The triangle is divided into three categories: equilateral triangle, isosceles triangle and scalene triangle.\n"]}]},{"cell_type":"markdown","metadata":{"id":"AePQUIs2h-Ks"},"source":["The model responds with the error answer."]},{"cell_type":"markdown","metadata":{"id":"YQ74Zz_S0iVv"},"source":["### Language Prompt"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"lorJMbsusgoo","outputId":"b3c7f53d-67e1-40e7-affa-d908153483e4","colab":{"base_uri":"https://localhost:8080/"}},"outputs":[{"output_type":"stream","name":"stdout","text":["Instruction:\n","什麼是動詞?\n","\n","Response:\n","What is a verb?\n","動詞的定義\n","\n","A verb is a word used to express action or a state of being.\n","一個動詞用以表達動作或狀態。\n","\n","There are two kinds of verbs in English:\n","英語中有一個類動詞和一個非類動詞。\n","1、類動詞:\n","The verbs that can be conjugated into different forms to indicate different meanings.\n","類動詞:可轉換成不同型態表達不同的意思。\n","2、非類動詞:\n","The verbs that can’t be conjugated into different forms to indicate different meanings.\n","非類動詞:不能轉換成不同型態表達不同的意思。\n","\n","The difference between a verb and a noun is that a verb is used to express action or state of being, while a noun is used to identify a person, thing or place.\n","動詞與名詞的區別在於動詞用來表達動作或狀態,而名詞則用來表示人、物或地方。\n","\n","For example, the verb \"to be\" in the sentence \"The teacher is in class.\"\n","例子:\n","The sentence \"The teacher is in class.\" has\n"]}],"source":["prompt = template.format(\n"," instruction=\"什麼是動詞?\",\n"," response=\"\",\n",")\n","sampler = keras_nlp.samplers.TopKSampler(k=5, seed=2)\n","gemma_lm.compile(sampler=sampler)\n","print(gemma_lm.generate(prompt, max_length=256))"]},{"cell_type":"markdown","metadata":{"id":"WBQieduRizZf"},"source":["The model response contains words that might not be easy to understand for a child such as chlorophyll."]},{"cell_type":"markdown","metadata":{"id":"Pt7Nr6a7tItO"},"source":["## LoRA Fine-tuning\n","\n","To get better responses from the model, fine-tune the model with Low Rank Adaptation (LoRA) using the Databricks Dolly 15k dataset.\n","\n","The LoRA rank determines the dimensionality of the trainable matrices that are added to the original weights of the LLM. It controls the expressiveness and precision of the fine-tuning adjustments.\n","\n","A higher rank means more detailed changes are possible, but also means more trainable parameters. A lower rank means less computational overhead, but potentially less precise adaptation.\n","\n","This tutorial uses a LoRA rank of 4. In practice, begin with a relatively small rank (such as 4, 8, 16). This is computationally efficient for experimentation. Train your model with this rank and evaluate the performance improvement on your task. Gradually increase the rank in subsequent trials and see if that further boosts performance."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"RCucu6oHz53G","outputId":"00cf3143-b605-4327-e16a-95e5bb2a0ab3","colab":{"base_uri":"https://localhost:8080/","height":385}},"outputs":[{"output_type":"display_data","data":{"text/plain":["\u001b[1mPreprocessor: \"gemma_causal_lm_preprocessor\"\u001b[0m\n"],"text/html":["
Preprocessor: \"gemma_causal_lm_preprocessor\"\n","
\n"]},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n","┃\u001b[1m \u001b[0m\u001b[1mTokenizer (type) \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1m Vocab #\u001b[0m\u001b[1m \u001b[0m┃\n","┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩\n","│ gemma_tokenizer (\u001b[38;5;33mGemmaTokenizer\u001b[0m) │ \u001b[38;5;34m256,000\u001b[0m │\n","└────────────────────────────────────────────────────┴─────────────────────────────────────────────────────┘\n"],"text/html":["
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n","┃ Tokenizer (type)                                                                                Vocab # ┃\n","┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩\n","│ gemma_tokenizer (GemmaTokenizer)                   │                                             256,000 │\n","└────────────────────────────────────────────────────┴─────────────────────────────────────────────────────┘\n","
\n"]},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["\u001b[1mModel: \"gemma_causal_lm\"\u001b[0m\n"],"text/html":["
Model: \"gemma_causal_lm\"\n","
\n"]},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n","┃\u001b[1m \u001b[0m\u001b[1mLayer (type) \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mOutput Shape \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1m Param #\u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mConnected to \u001b[0m\u001b[1m \u001b[0m┃\n","┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩\n","│ padding_mask (\u001b[38;5;33mInputLayer\u001b[0m) │ (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;45mNone\u001b[0m) │ \u001b[38;5;34m0\u001b[0m │ - │\n","├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤\n","│ token_ids (\u001b[38;5;33mInputLayer\u001b[0m) │ (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;45mNone\u001b[0m) │ \u001b[38;5;34m0\u001b[0m │ - │\n","├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤\n","│ gemma_backbone │ (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m2048\u001b[0m) │ \u001b[38;5;34m2,507,536,384\u001b[0m │ padding_mask[\u001b[38;5;34m0\u001b[0m][\u001b[38;5;34m0\u001b[0m], │\n","│ (\u001b[38;5;33mGemmaBackbone\u001b[0m) │ │ │ token_ids[\u001b[38;5;34m0\u001b[0m][\u001b[38;5;34m0\u001b[0m] │\n","├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤\n","│ token_embedding │ (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m256000\u001b[0m) │ \u001b[38;5;34m524,288,000\u001b[0m │ gemma_backbone[\u001b[38;5;34m0\u001b[0m][\u001b[38;5;34m0\u001b[0m] │\n","│ (\u001b[38;5;33mReversibleEmbedding\u001b[0m) │ │ │ │\n","└───────────────────────────────┴───────────────────────────┴─────────────────┴────────────────────────────┘\n"],"text/html":["
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n","┃ Layer (type)                   Output Shape                       Param #  Connected to               ┃\n","┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩\n","│ padding_mask (InputLayer)     │ (None, None)              │               0 │ -                          │\n","├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤\n","│ token_ids (InputLayer)        │ (None, None)              │               0 │ -                          │\n","├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤\n","│ gemma_backbone                │ (None, None, 2048)        │   2,507,536,384 │ padding_mask[0][0],        │\n","│ (GemmaBackbone)               │                           │                 │ token_ids[0][0]            │\n","├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤\n","│ token_embedding               │ (None, None, 256000)      │     524,288,000 │ gemma_backbone[0][0]       │\n","│ (ReversibleEmbedding)         │                           │                 │                            │\n","└───────────────────────────────┴───────────────────────────┴─────────────────┴────────────────────────────┘\n","
\n"]},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["\u001b[1m Total params: \u001b[0m\u001b[38;5;34m2,507,536,384\u001b[0m (9.34 GB)\n"],"text/html":["
 Total params: 2,507,536,384 (9.34 GB)\n","
\n"]},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["\u001b[1m Trainable params: \u001b[0m\u001b[38;5;34m1,363,968\u001b[0m (5.20 MB)\n"],"text/html":["
 Trainable params: 1,363,968 (5.20 MB)\n","
\n"]},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["\u001b[1m Non-trainable params: \u001b[0m\u001b[38;5;34m2,506,172,416\u001b[0m (9.34 GB)\n"],"text/html":["
 Non-trainable params: 2,506,172,416 (9.34 GB)\n","
\n"]},"metadata":{}}],"source":["# Enable LoRA for the model and set the LoRA rank to 4.\n","gemma_lm.backbone.enable_lora(rank=4)\n","gemma_lm.summary()"]},{"cell_type":"markdown","metadata":{"id":"hQQ47kcdpbZ9"},"source":["Note that enabling LoRA reduces the number of trainable parameters significantly (from 2.5 billion to 1.3 million)."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"_Peq7TnLtHse","outputId":"035ccb1e-0134-4f60-b207-64afb5a79b1d","colab":{"base_uri":"https://localhost:8080/"}},"outputs":[{"output_type":"stream","name":"stdout","text":["\u001b[1m1000/1000\u001b[0m \u001b[32m━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[37m\u001b[0m \u001b[1m1409s\u001b[0m 1s/step - loss: 0.9200 - sparse_categorical_accuracy: 0.4921\n"]},{"output_type":"execute_result","data":{"text/plain":[""]},"metadata":{},"execution_count":25}],"source":["# Limit the input sequence length to 512 (to control memory usage).\n","gemma_lm.preprocessor.sequence_length = 512\n","# Use AdamW (a common optimizer for transformer models).\n","optimizer = keras.optimizers.AdamW(\n"," learning_rate=5e-5,\n"," weight_decay=0.01,\n",")\n","# Exclude layernorm and bias terms from decay.\n","optimizer.exclude_from_weight_decay(var_names=[\"bias\", \"scale\"])\n","\n","gemma_lm.compile(\n"," loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n"," optimizer=optimizer,\n"," weighted_metrics=[keras.metrics.SparseCategoricalAccuracy()],\n",")\n","gemma_lm.fit(data, epochs=1, batch_size=1)"]},{"cell_type":"markdown","metadata":{"id":"bx3m8f1dB7nk"},"source":["### Note on mixed precision fine-tuning on NVIDIA GPUs\n","\n","Full precision is recommended for fine-tuning. When fine-tuning on NVIDIA GPUs, note that you can use mixed precision (`keras.mixed_precision.set_global_policy('mixed_bfloat16')`) to speed up training with minimal effect on training quality. Mixed precision fine-tuning does consume more memory so is useful only on larger GPUs.\n","\n","\n","For inference, half-precision (`keras.config.set_floatx(\"bfloat16\")`) will work and save memory while mixed precision is not applicable."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"T0lHxEDX03gp"},"outputs":[],"source":["# Uncomment the line below if you want to enable mixed precision training on GPUs\n","# keras.mixed_precision.set_global_policy('mixed_bfloat16')"]},{"cell_type":"markdown","metadata":{"id":"4yd-1cNw1dTn"},"source":["## Inference after fine-tuning\n","After fine-tuning, responses follow the instruction provided in the prompt."]},{"cell_type":"markdown","metadata":{"id":"H55JYJ1a1Kos"},"source":["### Math Problem Prompt"]},{"cell_type":"code","source":["prompt = template.format(\n"," instruction=\"什麼是三角形?\",\n"," response=\"\",\n",")\n","sampler = keras_nlp.samplers.TopKSampler(k=5, seed=2)\n","gemma_lm.compile(sampler=sampler)\n","print(gemma_lm.generate(prompt, max_length=256))"],"metadata":{"id":"QTF7dWR3svyH","outputId":"8b8b861b-fb28-4136-8bfd-87fa38e36191","colab":{"base_uri":"https://localhost:8080/"}},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Instruction:\n","什麼是三角形?\n","\n","Response:\n","一組三個邊,三組角度和三組邊的邊緣,三個角和三個邊緣的邊緣\n"]}]},{"cell_type":"markdown","metadata":{"id":"H7nVd8Mi1Yta"},"source":["### Language Prompt"]},{"cell_type":"code","source":["prompt = template.format(\n"," instruction=\"什麼是動詞?\",\n"," response=\"\",\n",")\n","print(gemma_lm.generate(prompt, max_length=256))"],"metadata":{"id":"72E-nEMNmPcd","outputId":"3af3adb7-9b07-495d-cb39-cda0426f0590","colab":{"base_uri":"https://localhost:8080/"}},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Instruction:\n","什麼是動詞?\n","\n","Response:\n","動詞是動名詞和名詞的合體形式。動詞通常是“進行”的,但有時也會使用“完成”或“完成”來表示動詞,如“完成”或“完成”。動詞可以是單數、複數或多數。它們也可以是單一性的,或具有多個形式,如“be”或“go”。\n"]}]},{"cell_type":"markdown","metadata":{"id":"I8kFG12l0mVe"},"source":["Note that for demonstration purposes, this tutorial fine-tunes the model on a small subset of the dataset for just one epoch and with a low LoRA rank value. To get better responses from the fine-tuned model, you can experiment with:\n","\n","1. Increasing the size of the fine-tuning dataset\n","2. Training for more steps (epochs)\n","3. Setting a higher LoRA rank\n","4. Modifying the hyperparameter values such as `learning_rate` and `weight_decay`."]},{"cell_type":"markdown","metadata":{"id":"gSsRdeiof_rJ"},"source":["## Summary and next steps\n","\n","This tutorial covered LoRA fine-tuning on a Gemma model using KerasNLP. Check out the following docs next:\n","\n","* Learn how to [generate text with a Gemma model](https://ai.google.dev/gemma/docs/get_started).\n","* Learn how to perform [distributed fine-tuning and inference on a Gemma model](https://ai.google.dev/gemma/docs/distributed_tuning).\n","* Learn how to [use Gemma open models with Vertex AI](https://cloud.google.com/vertex-ai/docs/generative-ai/open-models/use-gemma){:.external}.\n","* Learn how to [fine-tune Gemma using KerasNLP and deploy to Vertex AI](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_gemma_kerasnlp_to_vertexai.ipynb){:.external}."]}],"metadata":{"accelerator":"GPU","colab":{"provenance":[]},"kernelspec":{"display_name":"Python 3","name":"python3"}},"nbformat":4,"nbformat_minor":0} --------------------------------------------------------------------------------