File size: 8,507 Bytes
46304f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# 05월 07일 Tokenizer 실습 과제\n",
        "\n",
        "AutoTokenizer, AutoImageProcessor, AutoProcessor를 사용해 텍스트, 이미지, 멀티모달 처리를 실습합니다.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!pip install -q -U transformers pillow torch\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 실습 A. 텍스트 Tokenizer\n",
        "\n",
        "- `AutoTokenizer`로 `bert-base-uncased` 토크나이저를 로드합니다.\n",
        "- padding과 truncation을 적용합니다.\n",
        "- token id를 다시 text로 decode합니다.\n",
        "- `save_pretrained()`로 저장한 뒤 다시 로드하여 결과를 검증합니다.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "from transformers import AutoTokenizer\n",
        "import os\n",
        "\n",
        "# AutoTokenizer: 모델 이름에 맞는 tokenizer를 자동으로 불러오는 클래스\n",
        "tokenizer = AutoTokenizer.from_pretrained(\"bert-base-uncased\")\n",
        "\n",
        "# 입력 문장(text data)\n",
        "texts = [\n",
        "    \"I am studying Hugging Face tokenizers.\",\n",
        "    \"This is a tokenizer practice assignment.\"\n",
        "]\n",
        "\n",
        "# padding: 길이가 짧은 문장을 같은 길이로 맞춤\n",
        "# truncation: 길이가 긴 문장을 max_length에 맞게 자름\n",
        "encoded = tokenizer(\n",
        "    texts,\n",
        "    padding=True,\n",
        "    truncation=True,\n",
        "    max_length=16,\n",
        "    return_tensors=\"pt\"\n",
        ")\n",
        "\n",
        "print(\"input_ids:\")\n",
        "print(encoded[\"input_ids\"])\n",
        "print(\"attention_mask:\")\n",
        "print(encoded[\"attention_mask\"])\n",
        "\n",
        "# decode: token id를 다시 문장으로 변환\n",
        "decoded_text = tokenizer.decode(encoded[\"input_ids\"][0], skip_special_tokens=True)\n",
        "print(\"decoded text:\", decoded_text)\n",
        "\n",
        "# tokenizer 저장\n",
        "TEXT_TOKENIZER_DIR = \"./saved_bert_tokenizer\"\n",
        "tokenizer.save_pretrained(TEXT_TOKENIZER_DIR)\n",
        "\n",
        "# 저장된 tokenizer 다시 로드\n",
        "loaded_tokenizer = AutoTokenizer.from_pretrained(TEXT_TOKENIZER_DIR)\n",
        "loaded_encoded = loaded_tokenizer(\n",
        "    texts,\n",
        "    padding=True,\n",
        "    truncation=True,\n",
        "    max_length=16,\n",
        "    return_tensors=\"pt\"\n",
        ")\n",
        "\n",
        "# 저장 전/후 결과 검증\n",
        "same_input_ids = encoded[\"input_ids\"].tolist() == loaded_encoded[\"input_ids\"].tolist()\n",
        "same_attention_mask = encoded[\"attention_mask\"].tolist() == loaded_encoded[\"attention_mask\"].tolist()\n",
        "\n",
        "print(\"same input_ids:\", same_input_ids)\n",
        "print(\"same attention_mask:\", same_attention_mask)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 실습 B. 이미지 Processor\n",
        "\n",
        "- `AutoImageProcessor`로 ViT 이미지 프로세서를 로드합니다.\n",
        "- PIL 이미지 2장을 만들어 batch로 처리합니다.\n",
        "- `save_pretrained()`로 저장한 뒤 다시 로드하여 결과 shape를 검증합니다.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "from transformers import AutoImageProcessor\n",
        "from PIL import Image\n",
        "\n",
        "# AutoImageProcessor: 이미지 모델에 맞는 전처리기(image processor)를 자동으로 불러오는 클래스\n",
        "image_processor = AutoImageProcessor.from_pretrained(\"google/vit-base-patch16-224\")\n",
        "\n",
        "# 테스트용 이미지 batch 생성\n",
        "image_1 = Image.new(\"RGB\", (224, 224), color=(255, 255, 255))\n",
        "image_2 = Image.new(\"RGB\", (224, 224), color=(0, 0, 0))\n",
        "images = [image_1, image_2]\n",
        "\n",
        "# 이미지 batch 처리\n",
        "image_inputs = image_processor(\n",
        "    images=images,\n",
        "    return_tensors=\"pt\"\n",
        ")\n",
        "\n",
        "print(\"pixel_values shape:\", image_inputs[\"pixel_values\"].shape)\n",
        "\n",
        "# image processor 저장\n",
        "IMAGE_PROCESSOR_DIR = \"./saved_vit_image_processor\"\n",
        "image_processor.save_pretrained(IMAGE_PROCESSOR_DIR)\n",
        "\n",
        "# 저장된 image processor 다시 로드\n",
        "loaded_image_processor = AutoImageProcessor.from_pretrained(IMAGE_PROCESSOR_DIR)\n",
        "loaded_image_inputs = loaded_image_processor(\n",
        "    images=images,\n",
        "    return_tensors=\"pt\"\n",
        ")\n",
        "\n",
        "# 저장 전/후 결과 검증\n",
        "same_pixel_shape = image_inputs[\"pixel_values\"].shape == loaded_image_inputs[\"pixel_values\"].shape\n",
        "\n",
        "print(\"loaded pixel_values shape:\", loaded_image_inputs[\"pixel_values\"].shape)\n",
        "print(\"same pixel shape:\", same_pixel_shape)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 실습 C. 멀티모달 Processor\n",
        "\n",
        "- `AutoProcessor`로 CLIP 프로세서를 로드합니다.\n",
        "- text와 image를 동시에 입력합니다.\n",
        "- `save_pretrained()`로 저장한 뒤 다시 로드하여 text/image 결과를 검증합니다.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "from transformers import AutoProcessor\n",
        "\n",
        "# AutoProcessor: text와 image를 함께 처리하는 multimodal processor를 자동으로 불러오는 클래스\n",
        "clip_processor = AutoProcessor.from_pretrained(\"openai/clip-vit-base-patch32\")\n",
        "\n",
        "# CLIP 입력용 text와 image\n",
        "clip_texts = [\n",
        "    \"a white image\",\n",
        "    \"a black image\"\n",
        "]\n",
        "\n",
        "clip_images = [image_1, image_2]\n",
        "\n",
        "# text와 image 동시 처리\n",
        "clip_inputs = clip_processor(\n",
        "    text=clip_texts,\n",
        "    images=clip_images,\n",
        "    padding=True,\n",
        "    return_tensors=\"pt\"\n",
        ")\n",
        "\n",
        "print(\"CLIP input_ids shape:\", clip_inputs[\"input_ids\"].shape)\n",
        "print(\"CLIP pixel_values shape:\", clip_inputs[\"pixel_values\"].shape)\n",
        "\n",
        "# processor 저장\n",
        "CLIP_PROCESSOR_DIR = \"./saved_clip_processor\"\n",
        "clip_processor.save_pretrained(CLIP_PROCESSOR_DIR)\n",
        "\n",
        "# 저장된 processor 다시 로드\n",
        "loaded_clip_processor = AutoProcessor.from_pretrained(CLIP_PROCESSOR_DIR)\n",
        "loaded_clip_inputs = loaded_clip_processor(\n",
        "    text=clip_texts,\n",
        "    images=clip_images,\n",
        "    padding=True,\n",
        "    return_tensors=\"pt\"\n",
        ")\n",
        "\n",
        "# 저장 전/후 결과 검증\n",
        "same_clip_input_ids_shape = clip_inputs[\"input_ids\"].shape == loaded_clip_inputs[\"input_ids\"].shape\n",
        "same_clip_pixel_shape = clip_inputs[\"pixel_values\"].shape == loaded_clip_inputs[\"pixel_values\"].shape\n",
        "\n",
        "print(\"loaded CLIP input_ids shape:\", loaded_clip_inputs[\"input_ids\"].shape)\n",
        "print(\"loaded CLIP pixel_values shape:\", loaded_clip_inputs[\"pixel_values\"].shape)\n",
        "print(\"same CLIP input_ids shape:\", same_clip_input_ids_shape)\n",
        "print(\"same CLIP pixel shape:\", same_clip_pixel_shape)\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}