File size: 11,730 Bytes
ff43179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96786e2
 
ff43179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fec9aea
ff43179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Deploy LLaVA on Amazon SageMaker\n",
    "\n",
    "Amazon SageMaker is a popular platform for running AI models, and models on huggingface deploy [Hugging Face Transformers](https://github.com/huggingface/transformers) using [Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/whatis.html) and the [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable/).\n",
    "\n",
    "![llava](https://i.imgur.com/YNVG140.png)\n",
    "\n",
    "Install sagemaker sdk:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install sagemaker --upgrade\n",
    "!pip install -r code/requirements.txt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Bundle llava model weights and code into a `model.tar.gz`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create SageMaker model.tar.gz artifact\n",
    "!tar -cf model.tar.gz --use-compress-program=pigz *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After we created the `model.tar.gz` archive we can upload it to Amazon S3. We will use the `sagemaker` SDK to upload the model to our sagemaker session bucket.\n",
    "\n",
    "Initialize sagemaker session first:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sagemaker\n",
    "import boto3\n",
    "sess = sagemaker.Session()\n",
    "# sagemaker session bucket -> used for uploading data, models and logs\n",
    "# sagemaker will automatically create this bucket if it not exists\n",
    "sagemaker_session_bucket=None\n",
    "if sagemaker_session_bucket is None and sess is not None:\n",
    "    # set to default bucket if a bucket name is not given\n",
    "    sagemaker_session_bucket = sess.default_bucket()\n",
    "\n",
    "try:\n",
    "    role = sagemaker.get_execution_role()\n",
    "except ValueError:\n",
    "    iam = boto3.client('iam')\n",
    "    # setup your own rolename in sagemaker\n",
    "    role = iam.get_role(RoleName='AmazonSageMaker-ExecutionRole-20231008T201275')['Role']['Arn']\n",
    "\n",
    "sess = sagemaker.Session(default_bucket=sagemaker_session_bucket)\n",
    "\n",
    "print(f\"sagemaker role arn: {role}\")\n",
    "print(f\"sagemaker bucket: {sess.default_bucket()}\")\n",
    "print(f\"sagemaker session region: {sess.boto_region_name}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Upload the `model.tar.gz` to our sagemaker session bucket:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sagemaker.s3 import S3Uploader\n",
    "\n",
    "# upload model.tar.gz to s3\n",
    "s3_model_uri = S3Uploader.upload(local_path=\"./model.tar.gz\", desired_s3_uri=f\"s3://{sess.default_bucket()}/llava-v1.5-13b\")\n",
    "\n",
    "print(f\"model uploaded to: {s3_model_uri}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will use `HuggingfaceModel` to create our real-time inference endpoint:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sagemaker.config INFO - Not applying SDK defaults from location: /Library/Application Support/sagemaker/config.yaml\n",
      "sagemaker.config INFO - Not applying SDK defaults from location: /Users/tom/Library/Application Support/sagemaker/config.yaml\n",
      "sagemaker.config INFO - Not applying SDK defaults from location: /Library/Application Support/sagemaker/config.yaml\n",
      "sagemaker.config INFO - Not applying SDK defaults from location: /Users/tom/Library/Application Support/sagemaker/config.yaml\n",
      "---------------!"
     ]
    }
   ],
   "source": [
    "\n",
    "from sagemaker.huggingface.model import HuggingFaceModel\n",
    "\n",
    "# create Hugging Face Model Class\n",
    "huggingface_model = HuggingFaceModel(\n",
    "   model_data=s3_model_uri,      # path to your model and script\n",
    "   role=role,                    # iam role with permissions to create an Endpoint\n",
    "   transformers_version=\"4.28.1\",  # transformers version used\n",
    "   pytorch_version=\"2.0.0\",       # pytorch version used\n",
    "   py_version='py310',            # python version used\n",
    "   model_server_workers=1\n",
    ")\n",
    "\n",
    "# deploy the endpoint endpoint\n",
    "predictor = huggingface_model.deploy(\n",
    "    initial_instance_count=1,\n",
    "    instance_type=\"ml.g5.xlarge\",\n",
    "    # container_startup_health_check_timeout=600, # increase timeout for large models\n",
    "    # model_data_download_timeout=600, # increase timeout for large models\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `.deploy()` returns an `HuggingFacePredictor` object which can be used to request inference using the `.predict()` method. Our endpoint expects a `json` with at least `image` and `question` key."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The image is a black and white photograph of a man standing in front of a building. The man is wearing a suit and tie, and he appears to be looking at the camera. The building in the background is large and has many windows. The overall atmosphere of the image is formal and professional.\n"
     ]
    }
   ],
   "source": [
    "data = {\n",
    "    \"image\" : 'https://raw.githubusercontent.com/haotian-liu/LLaVA/main/images/llava_logo.png', \n",
    "    \"question\" : \"Describe the image and color details.\",\n",
    "    # \"max_new_tokens\" : 1024,\n",
    "    # \"temperature\" : 0.2,\n",
    "    # \"stop_str\" : \"###\"\n",
    "}\n",
    "\n",
    "# request\n",
    "output = predictor.predict(data)\n",
    "print(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To run inference with `llava` special token:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The image features a red toy animal, possibly a horse or a donkey, with a pair of glasses on its face. The toy is made of plastic and has a fire-like appearance, giving it a unique and eye-catching look. The red color of the toy and the glasses on its face create a striking contrast against the background, making it the main focus of the image.\n"
     ]
    }
   ],
   "source": [
    "from llava.conversation import conv_templates, SeparatorStyle\n",
    "from llava.constants import (\n",
    "DEFAULT_IMAGE_TOKEN,\n",
    "DEFAULT_IM_START_TOKEN,\n",
    "DEFAULT_IM_END_TOKEN,\n",
    ")\n",
    "def get_prompt(raw_prompt):\n",
    "    conv_mode = \"llava_v1\"\n",
    "    conv = conv_templates[conv_mode].copy()\n",
    "    roles = conv.roles\n",
    "    inp = f\"{roles[0]}: {raw_prompt}\"\n",
    "    inp = (\n",
    "        DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + \"\\n\" + inp\n",
    "    )\n",
    "    conv.append_message(conv.roles[0], inp)\n",
    "    conv.append_message(conv.roles[1], None)\n",
    "    prompt = conv.get_prompt()\n",
    "    stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2\n",
    "    return prompt, stop_str\n",
    "\n",
    "raw_prompt = \"Describe the image and color details.\"\n",
    "prompt, stop_str = get_prompt(raw_prompt)\n",
    "image_path = \"https://raw.githubusercontent.com/haotian-liu/LLaVA/main/images/llava_logo.png\"\n",
    "data = {\"image\" : image_path, \"question\" : prompt, \"stop_str\" : stop_str}\n",
    "output = predictor.predict(data)\n",
    "print(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The inference ` predictor` can also be initilized like with your deployed `endpoint_name` :"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sagemaker.config INFO - Not applying SDK defaults from location: /Library/Application Support/sagemaker/config.yaml\n",
      "sagemaker.config INFO - Not applying SDK defaults from location: /Users/tom/Library/Application Support/sagemaker/config.yaml\n",
      "sagemaker.config INFO - Not applying SDK defaults from location: /Library/Application Support/sagemaker/config.yaml\n",
      "sagemaker.config INFO - Not applying SDK defaults from location: /Users/tom/Library/Application Support/sagemaker/config.yaml\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Couldn't call 'get_role' to get Role ARN from role name arn:aws:iam::297308036828:root to get Role path.\n"
     ]
    }
   ],
   "source": [
    "import sagemaker\n",
    "import boto3\n",
    "sess = sagemaker.Session()\n",
    "try:\n",
    "    role = sagemaker.get_execution_role()\n",
    "except ValueError:\n",
    "    iam = boto3.client('iam')\n",
    "    # setup your own rolename in sagemaker\n",
    "    role = iam.get_role(RoleName='AmazonSageMaker-ExecutionRole-20231008T201275')['Role']['Arn']\n",
    "\n",
    "from sagemaker.huggingface.model import HuggingFacePredictor\n",
    "# initial the endpoint predictor\n",
    "predictor2 = HuggingFacePredictor(\n",
    "    endpoint_name=\"huggingface-pytorch-inference-2023-10-19-05-57-37-847\",\n",
    "    sagemaker_session=sess\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The image features a small toy animal, resembling a horse or a donkey, with a red and orange color scheme. The toy has a pair of glasses on its face, giving it a unique and quirky appearance. The toy is standing on a gray surface, which provides a contrasting background for the vibrant colors of the toy. The combination of red, orange, and gray creates a visually striking scene.\n"
     ]
    }
   ],
   "source": [
    "raw_prompt = \"Describe the image and color details.\"\n",
    "prompt, stop_str = get_prompt(raw_prompt)\n",
    "image_path = \"https://raw.githubusercontent.com/haotian-liu/LLaVA/main/images/llava_logo.png\"\n",
    "data = {\"image\" : image_path, \"question\" : prompt, \"stop_str\" : stop_str}\n",
    "output = predictor2.predict(data)\n",
    "print(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To clean up, we can delete the model and endpoint by `delete_endpoint()`or using sagemaker console:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "# delete sagemaker endpoint\n",
    "predictor.delete_endpoint()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llava",
   "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.13"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}