codeShare commited on
Commit
c45aaa9
·
verified ·
1 Parent(s): 34f34ed

Upload Precompute_Moss_embeddings_for_Kaggle_train.ipynb

Browse files
Precompute_Moss_embeddings_for_Kaggle_train.ipynb ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "collapsed_sections": [
8
+ "2UkdVxcYo9HZ",
9
+ "jRFJRfzHpK_k"
10
+ ]
11
+ },
12
+ "kernelspec": {
13
+ "name": "python3",
14
+ "display_name": "Python 3"
15
+ },
16
+ "language_info": {
17
+ "name": "python"
18
+ }
19
+ },
20
+ "cells": [
21
+ {
22
+ "cell_type": "markdown",
23
+ "source": [
24
+ "# Precompute Moss Image embeddings for Lora Training on Kaggle\n"
25
+ ],
26
+ "metadata": {
27
+ "id": "2UkdVxcYo9HZ"
28
+ }
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "metadata": {
33
+ "id": "1c6f852e"
34
+ },
35
+ "source": [
36
+ "# =============================================================================\n",
37
+ "# Kromoss (MOSS-Image) LoRA Training – PART 1: PRECOMPUTE EMBEDDINGS\n",
38
+ "# =============================================================================\n",
39
+ "\n",
40
+ "from google.colab import userdata, drive\n",
41
+ "import os\n",
42
+ "from huggingface_hub import login\n",
43
+ "\n",
44
+ "HF_TOKEN = userdata.get(\"HF_TOKEN\")\n",
45
+ "login(token=HF_TOKEN, add_to_git_credential=False)\n",
46
+ "print(\"Logged in with HF_TOKEN\")\n",
47
+ "\n",
48
+ "#@title 2. Mount Drive + unpack dataset\n",
49
+ "drive.mount(\"/content/drive\")\n",
50
+ "\n",
51
+ "import zipfile, shutil, gc\n",
52
+ "from pathlib import Path\n",
53
+ "\n",
54
+ "DATA_ZIP = \"/content/drive/MyDrive/tetsu_training_data.zip\"\n",
55
+ "DATA_DIR = Path(\"/content/tetsu_training_data\")\n",
56
+ "\n",
57
+ "if DATA_DIR.exists():\n",
58
+ " shutil.rmtree(DATA_DIR)\n",
59
+ "DATA_DIR.mkdir(parents=True, exist_ok=True)\n",
60
+ "\n",
61
+ "print(f\"Extracting {DATA_ZIP} ...\")\n",
62
+ "with zipfile.ZipFile(DATA_ZIP, \"r\") as z:\n",
63
+ " z.extractall(DATA_DIR)\n",
64
+ "\n",
65
+ "# Flatten single top-level folder if present\n",
66
+ "subdirs = [d for d in DATA_DIR.iterdir() if d.is_dir()]\n",
67
+ "if len(list(DATA_DIR.glob(\"*\"))) == 1 and subdirs:\n",
68
+ " for item in subdirs[0].iterdir():\n",
69
+ " shutil.move(str(item), str(DATA_DIR / item.name))\n",
70
+ " subdirs[0].rmdir()\n",
71
+ "\n",
72
+ "print(\"Dataset ready:\", list(DATA_DIR.iterdir())[:8], \"...\")\n",
73
+ "\n",
74
+ "#@title 3. Global Configuration\n",
75
+ "import torch\n",
76
+ "from transformers import AutoTokenizer, AutoModel, BitsAndBytesConfig\n",
77
+ "\n",
78
+ "REPO_ID = \"lodestones/Kromoss\"\n",
79
+ "RESOLUTION = 1024\n",
80
+ "MIXED_PRECISION = \"bf16\"\n",
81
+ "SEED = 42\n",
82
+ "MAX_SEQ_LEN = 512\n",
83
+ "\n",
84
+ "device = torch.device(\"cuda\")\n",
85
+ "dtype = torch.bfloat16 if MIXED_PRECISION == \"bf16\" else torch.float16\n",
86
+ "torch.manual_seed(SEED)\n",
87
+ "\n",
88
+ "#@title 4. Collect image-caption pairs\n",
89
+ "IMG_EXTS = {\".jpg\", \".jpeg\", \".png\", \".webp\", \".bmp\"}\n",
90
+ "pairs = []\n",
91
+ "for img_path in sorted(DATA_DIR.rglob(\"*\")):\n",
92
+ " if img_path.suffix.lower() not in IMG_EXTS:\n",
93
+ " continue\n",
94
+ " txt_path = img_path.with_suffix(\".txt\")\n",
95
+ " if txt_path.exists():\n",
96
+ " caption = txt_path.read_text(encoding=\"utf-8\").strip()\n",
97
+ " if caption:\n",
98
+ " pairs.append((str(img_path), caption))\n",
99
+ "\n",
100
+ "print(f\"Found {len(pairs)} image-text pairs\")\n",
101
+ "assert len(pairs) > 0, \"No image + .txt pairs found\"\n",
102
+ "\n",
103
+ "#@title 5. Precompute text embeddings with 4-bit quantized TE\n",
104
+ "print(\">>> Loading tokenizer ...\")\n",
105
+ "tokenizer = AutoTokenizer.from_pretrained(\n",
106
+ " REPO_ID, subfolder=\"tokenizer\", trust_remote_code=True, token=HF_TOKEN\n",
107
+ ")\n",
108
+ "\n",
109
+ "def build_prompt(text: str) -> str:\n",
110
+ " return f\"<|im_start|>user\\n{text}<|im_end|>\\n<|im_start|>assistant\\n<think>\\n\"\n",
111
+ "\n",
112
+ "print(\">>> Loading 4-bit NF4 text encoder (fits in ~6 GB) ...\")\n",
113
+ "bnb_config = BitsAndBytesConfig(\n",
114
+ " load_in_4bit=True,\n",
115
+ " bnb_4bit_quant_type=\"nf4\",\n",
116
+ " bnb_4bit_compute_dtype=torch.bfloat16,\n",
117
+ " bnb_4bit_use_double_quant=True,\n",
118
+ ")\n",
119
+ "\n",
120
+ "try:\n",
121
+ " text_encoder = AutoModel.from_pretrained(\n",
122
+ " REPO_ID,\n",
123
+ " subfolder=\"text_encoder\",\n",
124
+ " quantization_config=bnb_config,\n",
125
+ " device_map=\"auto\",\n",
126
+ " trust_remote_code=True,\n",
127
+ " token=HF_TOKEN,\n",
128
+ " )\n",
129
+ " print(\"Loaded quantized text_encoder from lodestones/Kromoss\")\n",
130
+ "except Exception as e:\n",
131
+ " print(f\"Kromoss text_encoder quant failed ({e}), falling back to Qwen/Qwen3.5-9B\")\n",
132
+ " text_encoder = AutoModel.from_pretrained(\n",
133
+ " \"Qwen/Qwen3.5-9B\",\n",
134
+ " quantization_config=bnb_config,\n",
135
+ " device_map=\"auto\",\n",
136
+ " trust_remote_code=True,\n",
137
+ " token=HF_TOKEN,\n",
138
+ " )\n",
139
+ "\n",
140
+ "text_encoder.eval()\n",
141
+ "text_encoder.requires_grad_(False)\n",
142
+ "\n",
143
+ "EMB_CACHE = Path(\"/content/text_emb_cache\")\n",
144
+ "EMB_CACHE.mkdir(parents=True, exist_ok=True)\n",
145
+ "\n",
146
+ "@torch.no_grad()\n",
147
+ "def encode_prompt(prompt: str):\n",
148
+ " text = build_prompt(prompt)\n",
149
+ " tokens = tokenizer(\n",
150
+ " text,\n",
151
+ " return_tensors=\"pt\",\n",
152
+ " padding=False,\n",
153
+ " truncation=True,\n",
154
+ " max_length=MAX_SEQ_LEN,\n",
155
+ " add_special_tokens=False,\n",
156
+ " )\n",
157
+ " input_ids = tokens.input_ids.to(device)\n",
158
+ " attention_mask = tokens.attention_mask.to(device)\n",
159
+ "\n",
160
+ " outputs = text_encoder(\n",
161
+ " input_ids=input_ids,\n",
162
+ " attention_mask=attention_mask,\n",
163
+ " output_hidden_states=False,\n",
164
+ " return_dict=True,\n",
165
+ " )\n",
166
+ " return outputs.last_hidden_state.cpu(), attention_mask.cpu()\n",
167
+ "\n"
168
+ ],
169
+ "execution_count": null,
170
+ "outputs": []
171
+ },
172
+ {
173
+ "cell_type": "code",
174
+ "source": [
175
+ "from tqdm.auto import tqdm\n",
176
+ "import torch\n",
177
+ "\n",
178
+ "print(\">>> Precomputing text embeddings ...\")\n",
179
+ "for idx, (img_path, caption) in enumerate(tqdm(pairs)):\n",
180
+ " cache_file = EMB_CACHE / f\"{idx:06d}.pt\"\n",
181
+ " if cache_file.exists():\n",
182
+ " continue\n",
183
+ " emb, mask = encode_prompt(caption)\n",
184
+ " torch.save({\"emb\": emb, \"mask\": mask, \"caption\": caption, \"img\": img_path}, cache_file)\n",
185
+ "\n",
186
+ "# ---------- Fully unload the quantized text encoder ----------\n",
187
+ "print(\">>> Unloading text encoder completely ...\")\n",
188
+ "if 'text_encoder' in globals():\n",
189
+ " del text_encoder\n",
190
+ "if 'tokenizer' in globals():\n",
191
+ " del tokenizer\n",
192
+ "gc.collect()\n",
193
+ "torch.cuda.empty_cache()\n",
194
+ "torch.cuda.ipc_collect()\n",
195
+ "print(f\"VRAM after TE unload: {torch.cuda.memory_allocated()/1024**3:.2f} GB\")"
196
+ ],
197
+ "metadata": {
198
+ "id": "HDGJLFrocjqs"
199
+ },
200
+ "execution_count": null,
201
+ "outputs": []
202
+ },
203
+ {
204
+ "cell_type": "code",
205
+ "metadata": {
206
+ "id": "fc52c645"
207
+ },
208
+ "source": [
209
+ "# =============================================================================\n",
210
+ "# STEP A: PRE-ENCODE IMAGES WITH VAE & SAVE COMPLETE DATASET TO GOOGLE DRIVE\n",
211
+ "# =============================================================================\n",
212
+ "# This step completely encodes both the images (using VAE) and matches them\n",
213
+ "# with the precomputed text embeddings from the previous step. It saves\n",
214
+ "# them as unified, ready-to-train torch tensors on your Google Drive.\n",
215
+ "# =============================================================================\n",
216
+ "\n",
217
+ "\"\"\"\n",
218
+ "[EXPLANATION OF DATASET PREPARATION]\n",
219
+ "This cell processes our active dataset by:\n",
220
+ "1. Loading the high-fidelity AutoencoderKLFlux2 VAE on CUDA.\n",
221
+ "2. Iterating through the images configured during dataset setup.\n",
222
+ "3. Downsampling/Center-cropping to 1024x1024 resolution.\n",
223
+ "4. Passing the image through the VAE encoder to yield compressed 2D latents.\n",
224
+ "5. Coupling these latents with the matching text embeddings cached in the previous step.\n",
225
+ "6. Saving the combined state (latents + text embeddings + attention masks) directly to Google Drive\n",
226
+ " under '/content/drive/MyDrive/kromoss_precomputed_dataset/' for instantaneous future loading.\n",
227
+ "\"\"\"\n",
228
+ "\n",
229
+ "import torch\n",
230
+ "import gc\n",
231
+ "from pathlib import Path\n",
232
+ "from PIL import Image\n",
233
+ "from tqdm.auto import tqdm\n",
234
+ "from torchvision import transforms\n",
235
+ "from google.colab import userdata\n",
236
+ "from diffusers import AutoencoderKLFlux2\n",
237
+ "\n",
238
+ "# Configuration\n",
239
+ "REPO_ID = \"lodestones/Kromoss\"\n",
240
+ "HF_TOKEN = userdata.get(\"HF_TOKEN\")\n",
241
+ "RESOLUTION = 1024\n",
242
+ "EMB_CACHE = Path(\"/content/text_emb_cache\")\n",
243
+ "\n",
244
+ "# Target directory on Google Drive\n",
245
+ "DRIVE_DATASET_DIR = Path(\"/content/drive/MyDrive/kromoss_precomputed_dataset\")\n",
246
+ "DRIVE_DATASET_DIR.mkdir(parents=True, exist_ok=True)\n",
247
+ "\n",
248
+ "device = torch.device(\"cuda\")\n",
249
+ "\n",
250
+ "print(\">>> Loading VAE model onto CUDA...\")\n",
251
+ "vae = AutoencoderKLFlux2.from_pretrained(\n",
252
+ " REPO_ID,\n",
253
+ " subfolder=\"vae\",\n",
254
+ " torch_dtype=torch.float32, # Encode in float32 for high fidelity\n",
255
+ " token=HF_TOKEN,\n",
256
+ ").to(device)\n",
257
+ "vae.eval()\n",
258
+ "vae.requires_grad_(False)\n",
259
+ "\n",
260
+ "# Transformation Pipeline\n",
261
+ "image_transforms = transforms.Compose([\n",
262
+ " transforms.Resize(RESOLUTION, interpolation=transforms.InterpolationMode.LANCZOS),\n",
263
+ " transforms.CenterCrop(RESOLUTION),\n",
264
+ " transforms.ToTensor(),\n",
265
+ " transforms.Normalize([0.5], [0.5]),\n",
266
+ "])\n",
267
+ "\n",
268
+ "@torch.no_grad()\n",
269
+ "def pre_encode_and_save():\n",
270
+ " # Retrieve all pre-encoded text embedding cache files\n",
271
+ " cached_text_files = sorted(EMB_CACHE.glob(\"*.pt\"))\n",
272
+ " print(f\">>> Found {len(cached_text_files)} cached text embeddings. Encoding corresponding images...\")\n",
273
+ "\n",
274
+ " for text_file in tqdm(cached_text_files, desc=\"Pre-encoding dataset\"):\n",
275
+ " # Load text cached data\n",
276
+ " text_data = torch.load(text_file, map_location=\"cpu\", weights_only=False)\n",
277
+ "\n",
278
+ " # Prepare output destination on Drive\n",
279
+ " drive_save_path = DRIVE_DATASET_DIR / text_file.name\n",
280
+ " if drive_save_path.exists():\n",
281
+ " continue\n",
282
+ "\n",
283
+ " # Load corresponding raw image\n",
284
+ " img_path = text_data[\"img\"]\n",
285
+ " img = Image.open(img_path).convert(\"RGB\")\n",
286
+ "\n",
287
+ " # Process image through VAE\n",
288
+ " pixel_values = image_transforms(img).unsqueeze(0).to(device, dtype=torch.float32)\n",
289
+ " image_latents = vae.encode(pixel_values).latent_dist.sample()\n",
290
+ "\n",
291
+ " # Unified output state containing both modalities\n",
292
+ " precomputed_sample = {\n",
293
+ " \"image_latents\": image_latents.squeeze(0).to(torch.bfloat16).cpu(), # Save in bf16 to conserve space\n",
294
+ " \"encoder_hidden_states\": text_data[\"emb\"].squeeze(0).to(torch.bfloat16).cpu(),\n",
295
+ " \"encoder_attention_mask\": text_data[\"mask\"].squeeze(0).cpu(),\n",
296
+ " \"caption\": text_data[\"caption\"]\n",
297
+ " }\n",
298
+ "\n",
299
+ " # Write directly to Google Drive\n",
300
+ " torch.save(precomputed_sample, drive_save_path)\n",
301
+ "\n",
302
+ "# Execute pre-encoding\n",
303
+ "pre_encode_and_save()\n",
304
+ "\n",
305
+ "# Release VAE and empty GPU memory cache\n",
306
+ "print(\">>> Pre-encoding finished. Unloading VAE model...\")\n",
307
+ "del vae\n",
308
+ "gc.collect()\n",
309
+ "torch.cuda.empty_cache()\n",
310
+ "torch.cuda.ipc_collect()\n",
311
+ "print(f\"VRAM after VAE unload: {torch.cuda.memory_allocated()/1024**3:.2f} GB\")"
312
+ ],
313
+ "execution_count": null,
314
+ "outputs": []
315
+ }
316
+ ]
317
+ }