Spaces:
Build error
Build error
File size: 10,178 Bytes
3506b46 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 |
{
"cells": [
{
"cell_type": "markdown",
"id": "a6b7c9f9-db9d-4278-8e0c-192db80afb9b",
"metadata": {},
"source": [
"### Importing Libraries\n",
"\n",
"This cell imports the necessary libraries for the project. `keras` is a high-level neural networks API, and `keras_nlp` provides additional tools and functionalities for natural language processing tasks using Keras.\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "09958eb5-8363-47dd-b508-353d6e538827",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"2024-08-29 18:01:15.929029: I tensorflow/core/util/port.cc:153] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.\n",
"2024-08-29 18:01:15.944717: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:485] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",
"2024-08-29 18:01:15.963838: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:8454] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",
"2024-08-29 18:01:15.969620: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1452] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",
"2024-08-29 18:01:15.983677: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",
"To enable the following instructions: AVX2 AVX512F AVX512_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n",
"/usr/local/lib/python3.10/dist-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
" from .autonotebook import tqdm as notebook_tqdm\n"
]
}
],
"source": [
"import keras\n",
"import keras_nlp\n",
"import tensorflow"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "de2731f6-422e-46bf-839d-ef8f474e7742",
"metadata": {},
"outputs": [],
"source": [
"# import os\n",
"\n",
"# os.environ[\"KERAS_BACKEND\"] = \"jax\" \n",
"# # Avoid memory fragmentation on JAX backend.\n",
"# os.environ[\"XLA_PYTHON_CLIENT_MEM_FRACTION\"]=\"1.00\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8725e8ba-f1c3-4e5f-8bb8-1451e3a7a394",
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"import json\n",
"\n",
"# Initialize an empty list to hold the processed data.\n",
"data = []\n",
"\n",
"# Open and read the JSON file line by line.\n",
"with open('/project/data/combined_dataset.json') as file:\n",
" for line in file:\n",
" features = json.loads(line)\n",
" \n",
" # Filter out examples without \"Context\".\n",
" if not features.get(\"Context\"):\n",
" continue\n",
" \n",
" # Format the example as a string.\n",
" template = \"Instruction:\\n{Context}\\n\\nResponse:\\n{Response}\"\n",
" formatted_example = template.format(**features)\n",
" \n",
" # Append the formatted example to the data list.\n",
" data.append(formatted_example)\n",
"\n",
"# Now data contains a list of formatted strings.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a26993cb-c8aa-42b1-943f-b6033d909336",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"\n",
"# Set Kaggle API credentials\n",
"os.environ[\"KAGGLE_USERNAME\"] = \"rogerkorantenng\"\n",
"os.environ[\"KAGGLE_KEY\"] = \"9a33b6e88bcb6058b1281d777fa6808d\"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "008c3f60-b0f6-4709-a7c7-836a6ea4f5cb",
"metadata": {},
"outputs": [],
"source": [
"gemma_lm = keras_nlp.models.GemmaCausalLM.from_preset(\"gemma_2b_en\")\n",
"gemma_lm.summary()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8fcd0823-61b8-4037-863d-d81dfcd8dec1",
"metadata": {},
"outputs": [],
"source": [
"# Define the template with placeholders for 'instruction' and 'response'\n",
"template = \"Instruction:\\n{instruction}\\n\\nResponse:\\n{response}\"\n",
"\n",
"# Create the prompt by formatting the template with actual data\n",
"prompt = template.format(\n",
" instruction=\"I'm going through some things with my feelings and myself. I barely sleep and I do nothing but think about how I'm worthless and how I shouldn't be here.\\n I've never tried or contemplated suicide. I've always wanted to fix my issues, but I never get around to it.\\n How can I change my feeling of being worthless to everyone?\",\n",
" response=\"\",\n",
")\n",
"\n",
"# Assuming gemma_lm is a language model that you're using to generate text\n",
"print(gemma_lm.generate(prompt, max_length=256))\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "834bffa8-4361-4ec9-8c3a-7403d3ce83c4",
"metadata": {},
"outputs": [],
"source": [
"# gemma_lm.save(\"gemma_model.h5\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3af9301d-2623-4773-9f3b-07efcc788fc4",
"metadata": {},
"outputs": [],
"source": [
"# Enable LoRA for the model and set the LoRA rank to 4.\n",
"gemma_lm.backbone.enable_lora(rank=10)\n",
"gemma_lm.summary()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ab365ee3-da5f-4b5c-b00b-428005ff42e4",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import tensorflow as tf\n",
"import keras_nlp\n",
"import keras\n",
"import json\n",
"\n",
"# Set Kaggle API credentials\n",
"os.environ[\"KAGGLE_USERNAME\"] = \"rogerkorantenng\"\n",
"os.environ[\"KAGGLE_KEY\"] = \"9a33b6e88bcb6058b1281d777fa6808d\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ae2db527-0964-491d-8fd6-0c746cbcae2e",
"metadata": {},
"outputs": [],
"source": [
"def get_compiled_model():\n",
" gemma_lm = keras_nlp.models.GemmaCausalLM.from_preset(\"gemma_2b_en\")\n",
" gemma_lm.summary()\n",
"\n",
" gemma_lm.backbone.enable_lora(rank=2)\n",
" gemma_lm.summary()\n",
" \n",
" # Set the sequence length to 128 before using the model.\n",
" gemma_lm.preprocessor.sequence_length = 128\n",
" \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",
" \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",
"\n",
" \n",
" return gemma_lm\n",
"print(gemma_lm.)\n",
"\n",
"print(gemma_lm.summary())\n",
"\n",
"\n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bd11ce52-9eb8-4e48-a4da-fdc759e7f789",
"metadata": {},
"outputs": [],
"source": [
"def get_dataset():\n",
" # Initialize an empty list to hold the processed data.\n",
" data = []\n",
" \n",
" # Open and read the JSON file line by line.\n",
" with open('/project/data/HealthCareMagic-100k-en.jsonl') as file:\n",
" for line in file:\n",
" features = json.loads(line)\n",
" \n",
" # Filter out examples without \"Context\".\n",
" if not features.get(\"Context\"):\n",
" continue\n",
" \n",
" # Format the example as a string.\n",
" template = \"Instruction:\\n{Context}\\n\\nResponse:\\n{Response}\"\n",
" formatted_example = template.format(**features)\n",
" \n",
" # Append the formatted example to the data list.\n",
" data.append(formatted_example)\n",
" \n",
" return data "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4ec94c5f-70b6-4683-95d4-53c1231f5a9c",
"metadata": {},
"outputs": [],
"source": [
"model = get_compiled_model()\n",
"\n",
"# Get the dataset outside the strategy scope.\n",
"data = get_dataset()\n",
"\n",
"# Fit the model using the data.\n",
"model.fit(data, epochs=2, batch_size=0, verbose=1)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "bfe053b2-a02f-4e2b-af04-48c28a00c20e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello\n"
]
}
],
"source": [
"print('Hello')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "35d93608-b1ef-44a1-a57b-4c1a3d3dbebb",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|