Update fine_tune_jit_with_validation_cuda_1b.py
Browse files- fine_tune_jit_with_validation_cuda_1b.py +486 -464
fine_tune_jit_with_validation_cuda_1b.py
CHANGED
|
@@ -1,465 +1,487 @@
|
|
| 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 |
-
from
|
| 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 |
-
self.
|
| 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 |
-
model
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
model
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
if
|
| 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 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 465 |
train()
|
|
|
|
| 1 |
+
# Copyright (c) 2025 CMS Manhattan
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
# Author: Konstantin Vladimirovich Grabko
|
| 4 |
+
# Email: grabko@cmsmanhattan.com
|
| 5 |
+
# Phone: +1(516)777-0945
|
| 6 |
+
#
|
| 7 |
+
# This program is free software: you can redistribute it and/or modify
|
| 8 |
+
# it under the terms of the GNU General Public License as published by
|
| 9 |
+
# the Free Software Foundation, version 3 of the License.
|
| 10 |
+
#
|
| 11 |
+
# This program is distributed in the hope that it will be useful,
|
| 12 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 13 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 14 |
+
# GNU General Public License for more details.
|
| 15 |
+
#
|
| 16 |
+
# You should have received a copy of the GNU General Public License
|
| 17 |
+
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 18 |
+
#
|
| 19 |
+
# Additional terms:
|
| 20 |
+
# Any commercial use or distribution of this software or derivative works
|
| 21 |
+
# requires explicit written permission from the copyright holder.
|
| 22 |
+
|
| 23 |
+
#!/usr/bin/env python3
|
| 24 |
+
"""
|
| 25 |
+
# install tokenizer before run
|
| 26 |
+
mkdir -p tokenizer
|
| 27 |
+
wget -O tokenizer/tokenizer.json https://huggingface.co/gpt2/resolve/main/tokenizer.json
|
| 28 |
+
wget -O tokenizer/vocab.json https://huggingface.co/gpt2/resolve/main/vocab.json
|
| 29 |
+
wget -O tokenizer/merges.txt https://huggingface.co/gpt2/resolve/main/merges.txt
|
| 30 |
+
wget -O tokenizer/tokenizer_config.json https://huggingface.co/gpt2/resolve/main/tokenizer_config.json
|
| 31 |
+
|
| 32 |
+
Updated fine-tuning script, version "prefer Python nn.Module with gradient checkpointing".
|
| 33 |
+
|
| 34 |
+
What it does:
|
| 35 |
+
- Tries to load a local Python implementation of the model (as torch.nn.Module). If found β uses it and
|
| 36 |
+
enables gradient_checkpointing (if the model supports it).
|
| 37 |
+
- If no Python model class is found β falls back to JIT ScriptModule (as before).
|
| 38 |
+
- If the original weights are only available as JIT, attempts to extract state_dict() from the ScriptModule
|
| 39 |
+
and load it into the nn.Module (best-effort).
|
| 40 |
+
- Saves the final trained model as a JIT torch.jit.save at the end, or as state_dict if something fails.
|
| 41 |
+
- Saves the tokenizer locally (./tokenizer) and uses it. Gives a helpful message if the tokenizer is missing.
|
| 42 |
+
- Supports AMP (autocast + GradScaler) on GPU.
|
| 43 |
+
- Optional support for bitsandbytes 8-bit optimizer (if installed).
|
| 44 |
+
- Comments and console messages are in Russian.
|
| 45 |
+
|
| 46 |
+
Before running: if you have a Python file with the model implementation
|
| 47 |
+
(for example gpt_modern_1b.py or gpt_modern_1b_class.py), place it in the same folder
|
| 48 |
+
and make sure it contains a class named JiRackPyTorch (or one of the other names the script looks for).
|
| 49 |
+
If no such file exists β the script will just use the JIT model as before.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
import os
|
| 53 |
+
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "max_split_size_mb:128,garbage_collection_threshold:0.6")
|
| 54 |
+
|
| 55 |
+
import sys
|
| 56 |
+
import importlib
|
| 57 |
+
import math
|
| 58 |
+
import shutil
|
| 59 |
+
import re
|
| 60 |
+
from pathlib import Path
|
| 61 |
+
from typing import Optional
|
| 62 |
+
|
| 63 |
+
import torch
|
| 64 |
+
import torch.nn as nn
|
| 65 |
+
import torch.optim as optim
|
| 66 |
+
from torch.utils.data import IterableDataset, DataLoader
|
| 67 |
+
from transformers import GPT2TokenizerFast
|
| 68 |
+
from tqdm import tqdm
|
| 69 |
+
from torch.cuda.amp import GradScaler, autocast
|
| 70 |
+
|
| 71 |
+
# ========================= SETTINGS =========================
|
| 72 |
+
TRAIN_SEQ_LEN = int(os.environ.get("TRAIN_SEQ_LEN", 64))
|
| 73 |
+
BATCH_SIZE = int(os.environ.get("BATCH_SIZE", 1))
|
| 74 |
+
EPOCHS = int(os.environ.get("EPOCHS", 999))
|
| 75 |
+
LEARNING_RATE = float(os.environ.get("LEARNING_RATE", 6e-6))
|
| 76 |
+
WEIGHT_DECAY = float(os.environ.get("WEIGHT_DECAY", 0.01))
|
| 77 |
+
GRAD_CLIP = float(os.environ.get("GRAD_CLIP", 1.0))
|
| 78 |
+
KEEP_LAST_EPOCHS = int(os.environ.get("KEEP_LAST_EPOCHS", 3))
|
| 79 |
+
VAL_SPLIT_RATIO = float(os.environ.get("VAL_SPLIT_RATIO", 0.05))
|
| 80 |
+
|
| 81 |
+
BASE_MODEL_PATH = Path("models/gpt_modern_1b_class.script.pt")
|
| 82 |
+
LAST_TRAINED_PATH = Path("models/gpt_1b_last_trained.script.pt")
|
| 83 |
+
PT_STATE_DICT_PATH = Path("models/gpt_modern_1b_class.state_dict.pt")
|
| 84 |
+
BACKUP_DIR = Path("models/backups")
|
| 85 |
+
BACKUP_DIR.mkdir(parents=True, exist_ok=True)
|
| 86 |
+
|
| 87 |
+
RAW_PATH = Path("datasets/dialogues_text.txt")
|
| 88 |
+
CLEAN_PATH = Path("datasets/dialogues_text_clean.txt")
|
| 89 |
+
TOKENIZER_LOCAL_DIR = Path("./tokenizer")
|
| 90 |
+
|
| 91 |
+
OUTPUT_DIR = Path("build/fine_tuning_output")
|
| 92 |
+
MODEL_SAVE_NAME = "gpt_finetuned.script.pt"
|
| 93 |
+
|
| 94 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 95 |
+
print(f"Using device: {device}")
|
| 96 |
+
|
| 97 |
+
# ========================= Tokenizer helper =========================
|
| 98 |
+
def _load_tokenizer_local(tokenizer_name: str = "gpt2"):
|
| 99 |
+
"""
|
| 100 |
+
Try to load tokenizer from local files. If not found β give the user instructions.
|
| 101 |
+
"""
|
| 102 |
+
candidates = []
|
| 103 |
+
env_path = os.environ.get("TOKENIZER_PATH")
|
| 104 |
+
if env_path:
|
| 105 |
+
candidates.append(env_path)
|
| 106 |
+
candidates.append(str(TOKENIZER_LOCAL_DIR))
|
| 107 |
+
candidates.append(tokenizer_name)
|
| 108 |
+
candidates.append("./")
|
| 109 |
+
for cand in candidates:
|
| 110 |
+
try:
|
| 111 |
+
tok = GPT2TokenizerFast.from_pretrained(cand, local_files_only=True)
|
| 112 |
+
if getattr(tok, "pad_token", None) is None:
|
| 113 |
+
tok.pad_token = tok.eos_token
|
| 114 |
+
print(f"Tokenizer loaded from: {cand}")
|
| 115 |
+
return tok
|
| 116 |
+
except Exception:
|
| 117 |
+
continue
|
| 118 |
+
|
| 119 |
+
raise RuntimeError(
|
| 120 |
+
"Local tokenizer not found. Place tokenizer.json or (vocab.json + merges.txt) into ./tokenizer\n"
|
| 121 |
+
"OR set the path via TOKENIZER_PATH environment variable.\n"
|
| 122 |
+
"Example: export TOKENIZER_PATH=/path/to/tokenizer\n"
|
| 123 |
+
"If you have internet access, you can temporarily use transformers.GPT2TokenizerFast.from_pretrained('gpt2')"
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
# ========================= Dataset =========================
|
| 127 |
+
class LazyTextDataset(IterableDataset):
|
| 128 |
+
def __init__(self, text_file: Path, seq_len: int = TRAIN_SEQ_LEN, tokenizer_name: str = "gpt2",
|
| 129 |
+
split_type: str = 'train', val_ratio: float = VAL_SPLIT_RATIO):
|
| 130 |
+
self.seq_len = seq_len
|
| 131 |
+
self.tokenizer = _load_tokenizer_local(tokenizer_name)
|
| 132 |
+
self.text_file = Path(text_file)
|
| 133 |
+
self.split_type = split_type
|
| 134 |
+
self.val_ratio = val_ratio
|
| 135 |
+
|
| 136 |
+
print(f"Loading and tokenizing {self.text_file} (one-time tokenization into ids)...")
|
| 137 |
+
with open(self.text_file, "r", encoding="utf-8") as f:
|
| 138 |
+
data = f.read()
|
| 139 |
+
self.tokens = self.tokenizer.encode(data)
|
| 140 |
+
|
| 141 |
+
total_tokens = max(0, len(self.tokens) - 1)
|
| 142 |
+
total_batches = total_tokens // seq_len if seq_len > 0 else 0
|
| 143 |
+
val_size = int(total_batches * val_ratio)
|
| 144 |
+
train_size = total_batches - val_size
|
| 145 |
+
if split_type == 'train':
|
| 146 |
+
self.start = 0
|
| 147 |
+
self.stop = train_size
|
| 148 |
+
elif split_type == 'val':
|
| 149 |
+
self.start = train_size
|
| 150 |
+
self.stop = train_size + val_size
|
| 151 |
+
else:
|
| 152 |
+
raise ValueError("split_type must be 'train' or 'val'")
|
| 153 |
+
self.total_sequences = max(0, self.stop - self.start)
|
| 154 |
+
print(f"Split {split_type}: {self.total_sequences} sequences (out of {total_batches})")
|
| 155 |
+
|
| 156 |
+
def __iter__(self):
|
| 157 |
+
for i in range(self.start * self.seq_len, self.stop * self.seq_len, self.seq_len):
|
| 158 |
+
if i + self.seq_len + 1 > len(self.tokens):
|
| 159 |
+
break
|
| 160 |
+
input_seq = torch.tensor(self.tokens[i: i + self.seq_len], dtype=torch.long)
|
| 161 |
+
label_seq = torch.tensor(self.tokens[i + 1: i + self.seq_len + 1], dtype=torch.long)
|
| 162 |
+
yield input_seq, label_seq
|
| 163 |
+
|
| 164 |
+
def __len__(self):
|
| 165 |
+
return self.total_sequences
|
| 166 |
+
|
| 167 |
+
# ========================= Try to load Python nn.Module model =========================
|
| 168 |
+
def try_load_python_model():
|
| 169 |
+
"""
|
| 170 |
+
Attempt to find and import a local Python model implementation (nn.Module).
|
| 171 |
+
Looks for several possible module and class names.
|
| 172 |
+
Returns (model_instance, source_description) or (None, None).
|
| 173 |
+
"""
|
| 174 |
+
candidates_modules = [
|
| 175 |
+
"gpt_modern_1b_class",
|
| 176 |
+
"gpt_modern_1b",
|
| 177 |
+
"gpt_modern_1b_class_fixed",
|
| 178 |
+
"model", "ji_rack_model"
|
| 179 |
+
]
|
| 180 |
+
candidates_class_names = [
|
| 181 |
+
"JiRackPyTorch",
|
| 182 |
+
"JiRackPyTorch1B",
|
| 183 |
+
"GPTModel",
|
| 184 |
+
"JiRackModel"
|
| 185 |
+
]
|
| 186 |
+
|
| 187 |
+
for modname in candidates_modules:
|
| 188 |
+
try:
|
| 189 |
+
spec = importlib.util.find_spec(modname)
|
| 190 |
+
if spec is None:
|
| 191 |
+
continue
|
| 192 |
+
mod = importlib.import_module(modname)
|
| 193 |
+
for cls_name in candidates_class_names:
|
| 194 |
+
if hasattr(mod, cls_name):
|
| 195 |
+
cls = getattr(mod, cls_name)
|
| 196 |
+
try:
|
| 197 |
+
inst = cls()
|
| 198 |
+
print(f"Loaded Python model class {cls_name} from module {modname}")
|
| 199 |
+
return inst, f"python:{modname}.{cls_name}"
|
| 200 |
+
except Exception as e:
|
| 201 |
+
print(f"Found class {cls_name} in {modname} but instantiation failed: {e}")
|
| 202 |
+
continue
|
| 203 |
+
except Exception:
|
| 204 |
+
continue
|
| 205 |
+
return None, None
|
| 206 |
+
|
| 207 |
+
# ========================= Utility: load weights from JIT script into nn.Module =========================
|
| 208 |
+
def load_weights_from_script_to_module(script_path: Path, module_model: nn.Module):
|
| 209 |
+
"""
|
| 210 |
+
Best-effort: extract state_dict from a ScriptModule and load it into a regular nn.Module.
|
| 211 |
+
Returns True on success.
|
| 212 |
+
"""
|
| 213 |
+
try:
|
| 214 |
+
script_mod = torch.jit.load(script_path, map_location="cpu")
|
| 215 |
+
except Exception as e:
|
| 216 |
+
print(f"Cannot load script {script_path}: {e}")
|
| 217 |
+
return False
|
| 218 |
+
try:
|
| 219 |
+
sd = script_mod.state_dict()
|
| 220 |
+
except Exception as e:
|
| 221 |
+
print(f"ScriptModule.state_dict() failed: {e}")
|
| 222 |
+
return False
|
| 223 |
+
try:
|
| 224 |
+
module_model.load_state_dict(sd, strict=False)
|
| 225 |
+
print("Weights successfully loaded from ScriptModule into Python nn.Module (strict=False).")
|
| 226 |
+
return True
|
| 227 |
+
except Exception as e:
|
| 228 |
+
print(f"load_state_dict failed: {e}")
|
| 229 |
+
return False
|
| 230 |
+
|
| 231 |
+
# ========================= Helper to get logits from any model type =========================
|
| 232 |
+
def get_logits_from_model(model, inputs: torch.Tensor):
|
| 233 |
+
inputs = inputs.to(device)
|
| 234 |
+
out = model(inputs)
|
| 235 |
+
if isinstance(out, (tuple, list)):
|
| 236 |
+
return out[0]
|
| 237 |
+
return out
|
| 238 |
+
|
| 239 |
+
# ========================= Evaluation =========================
|
| 240 |
+
def evaluate(model, dataloader, criterion):
|
| 241 |
+
model.eval()
|
| 242 |
+
total_loss = 0.0
|
| 243 |
+
count = 0
|
| 244 |
+
with torch.no_grad():
|
| 245 |
+
for inputs, targets in dataloader:
|
| 246 |
+
inputs, targets = inputs.to(device), targets.to(device)
|
| 247 |
+
logits = get_logits_from_model(model, inputs)
|
| 248 |
+
logits = logits.contiguous().view(-1, logits.size(-1))
|
| 249 |
+
targets = targets.contiguous().view(-1)[:logits.shape[0]]
|
| 250 |
+
loss = criterion(logits, targets)
|
| 251 |
+
total_loss += float(loss.item())
|
| 252 |
+
count += 1
|
| 253 |
+
model.train()
|
| 254 |
+
return total_loss / max(1, count)
|
| 255 |
+
|
| 256 |
+
# ========================= Training loop =========================
|
| 257 |
+
def train():
|
| 258 |
+
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 259 |
+
print("Loading model...")
|
| 260 |
+
|
| 261 |
+
python_model, python_source = try_load_python_model()
|
| 262 |
+
model = None
|
| 263 |
+
model_source = None
|
| 264 |
+
|
| 265 |
+
# Prefer Python nn.Module if available
|
| 266 |
+
if python_model is not None:
|
| 267 |
+
model = python_model
|
| 268 |
+
model_source = python_source
|
| 269 |
+
loaded = False
|
| 270 |
+
# Try to load latest weights (state_dict first, then JIT β state_dict)
|
| 271 |
+
if PT_STATE_DICT_PATH.exists():
|
| 272 |
+
try:
|
| 273 |
+
sd = torch.load(PT_STATE_DICT_PATH, map_location="cpu")
|
| 274 |
+
model.load_state_dict(sd, strict=False)
|
| 275 |
+
print(f"Loaded state_dict from {PT_STATE_DICT_PATH}")
|
| 276 |
+
loaded = True
|
| 277 |
+
except Exception as e:
|
| 278 |
+
print(f"Failed to load state_dict from {PT_STATE_DICT_PATH}: {e}")
|
| 279 |
+
if not loaded and LAST_TRAINED_PATH.exists():
|
| 280 |
+
if load_weights_from_script_to_module(LAST_TRAINED_PATH, model):
|
| 281 |
+
loaded = True
|
| 282 |
+
if not loaded and BASE_MODEL_PATH.exists():
|
| 283 |
+
if load_weights_from_script_to_module(BASE_MODEL_PATH, model):
|
| 284 |
+
loaded = True
|
| 285 |
+
else:
|
| 286 |
+
# Fallback to JIT ScriptModule
|
| 287 |
+
if LAST_TRAINED_PATH.exists():
|
| 288 |
+
model = torch.jit.load(LAST_TRAINED_PATH, map_location=device)
|
| 289 |
+
model_source = f"jit:{LAST_TRAINED_PATH}"
|
| 290 |
+
elif BASE_MODEL_PATH.exists():
|
| 291 |
+
model = torch.jit.load(BASE_MODEL_PATH, map_location=device)
|
| 292 |
+
model_source = f"jit:{BASE_MODEL_PATH}"
|
| 293 |
+
else:
|
| 294 |
+
print("ERROR: No model found (neither Python module nor JIT). Place a model file or Python implementation.")
|
| 295 |
+
return
|
| 296 |
+
|
| 297 |
+
print(f"Model loaded from: {model_source}")
|
| 298 |
+
|
| 299 |
+
# If we are using a real nn.Module β move to device + enable gradient checkpointing if possible
|
| 300 |
+
is_python_module = isinstance(model, nn.Module)
|
| 301 |
+
if is_python_module:
|
| 302 |
+
model.to(device)
|
| 303 |
+
model.train()
|
| 304 |
+
try:
|
| 305 |
+
model.gradient_checkpointing_enable()
|
| 306 |
+
print("Gradient checkpointing ENABLED on Python nn.Module.")
|
| 307 |
+
except Exception:
|
| 308 |
+
try:
|
| 309 |
+
model.gradient_checkpointing = True
|
| 310 |
+
print("Set attribute gradient_checkpointing = True (best-effort).")
|
| 311 |
+
except Exception:
|
| 312 |
+
print("Gradient checkpointing not available on this Python model.")
|
| 313 |
+
else:
|
| 314 |
+
# ScriptModule path
|
| 315 |
+
try:
|
| 316 |
+
model.to(device)
|
| 317 |
+
except Exception:
|
| 318 |
+
print("Warning: model.to(device) failed for ScriptModule; trying best-effort buffer move.")
|
| 319 |
+
model.train()
|
| 320 |
+
print("Training on ScriptModule (gradient checkpointing not available).")
|
| 321 |
+
|
| 322 |
+
# ========================= Dataset preparation =========================
|
| 323 |
+
if not CLEAN_PATH.exists():
|
| 324 |
+
if not RAW_PATH.exists():
|
| 325 |
+
raise FileNotFoundError(f"Missing dataset {RAW_PATH}")
|
| 326 |
+
print("Cleaning raw dataset β cleaned version...")
|
| 327 |
+
text = RAW_PATH.read_text(encoding="utf-8")
|
| 328 |
+
text = re.sub(r" {2,}", " ", text)
|
| 329 |
+
text = text.replace(" \n", "\n").replace("\n ", "\n")
|
| 330 |
+
CLEAN_PATH.write_text(text, encoding="utf-8")
|
| 331 |
+
print(f"Cleaned dataset saved β {CLEAN_PATH}")
|
| 332 |
+
|
| 333 |
+
train_dataset = LazyTextDataset(CLEAN_PATH, seq_len=TRAIN_SEQ_LEN, split_type='train', val_ratio=VAL_SPLIT_RATIO)
|
| 334 |
+
val_dataset = LazyTextDataset(CLEAN_PATH, seq_len=TRAIN_SEQ_LEN, split_type='val', val_ratio=VAL_SPLIT_RATIO)
|
| 335 |
+
|
| 336 |
+
train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=False, drop_last=True, num_workers=0)
|
| 337 |
+
val_loader = DataLoader(val_dataset, batch_size=BATCH_SIZE, shuffle=False, drop_last=True, num_workers=0)
|
| 338 |
+
|
| 339 |
+
# ========================= Optimizer (try 8-bit first) =========================
|
| 340 |
+
try:
|
| 341 |
+
import bitsandbytes as bnb # type: ignore
|
| 342 |
+
try:
|
| 343 |
+
optimizer = bnb.optim.AdamW8bit(model.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY)
|
| 344 |
+
except Exception:
|
| 345 |
+
optimizer = bnb.optim.Adam8bit(model.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY)
|
| 346 |
+
print("Using bitsandbytes 8-bit optimizer.")
|
| 347 |
+
except Exception:
|
| 348 |
+
optimizer = optim.AdamW(model.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY)
|
| 349 |
+
print("Using standard torch.optim.AdamW (bitsandbytes not available).")
|
| 350 |
+
|
| 351 |
+
criterion = nn.CrossEntropyLoss()
|
| 352 |
+
scaler = GradScaler(enabled=(device.type == 'cuda'))
|
| 353 |
+
|
| 354 |
+
if device.type == 'cuda':
|
| 355 |
+
torch.cuda.empty_cache()
|
| 356 |
+
|
| 357 |
+
total_steps = (len(train_dataset) // BATCH_SIZE) * EPOCHS if len(train_dataset) > 0 else 0
|
| 358 |
+
print(f"\nSTARTING training: epochs={EPOCHS}, approx. steps={total_steps}, examples={len(train_dataset)}")
|
| 359 |
+
print(f"Batch size={BATCH_SIZE}, seq_len={TRAIN_SEQ_LEN}, device={device}, AMP={'on' if device.type=='cuda' else 'off'}")
|
| 360 |
+
|
| 361 |
+
global_step = 0
|
| 362 |
+
for epoch in range(1, EPOCHS + 1):
|
| 363 |
+
print(f"\n=== Epoch {epoch}/{EPOCHS} ===")
|
| 364 |
+
epoch_loss = 0.0
|
| 365 |
+
|
| 366 |
+
pbar = tqdm(train_loader, desc=f"Epoch {epoch} [TRAIN]", leave=False)
|
| 367 |
+
for inputs, targets in pbar:
|
| 368 |
+
inputs, targets = inputs.to(device), targets.to(device)
|
| 369 |
+
optimizer.zero_grad(set_to_none=True)
|
| 370 |
+
|
| 371 |
+
with autocast(enabled=(device.type == 'cuda')):
|
| 372 |
+
logits = get_logits_from_model(model, inputs)
|
| 373 |
+
logits = logits.contiguous().view(-1, logits.size(-1))
|
| 374 |
+
targets_view = targets.contiguous().view(-1)[:logits.shape[0]]
|
| 375 |
+
loss = criterion(logits, targets_view)
|
| 376 |
+
|
| 377 |
+
# Backward pass (AMP-safe)
|
| 378 |
+
if device.type == 'cuda':
|
| 379 |
+
try:
|
| 380 |
+
scaler.scale(loss).backward()
|
| 381 |
+
scaler.unscale_(optimizer)
|
| 382 |
+
except Exception as e:
|
| 383 |
+
print("Scaled backward failed:", e)
|
| 384 |
+
loss.backward()
|
| 385 |
+
try:
|
| 386 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), GRAD_CLIP)
|
| 387 |
+
except Exception:
|
| 388 |
+
pass
|
| 389 |
+
try:
|
| 390 |
+
scaler.step(optimizer)
|
| 391 |
+
scaler.update()
|
| 392 |
+
except RuntimeError as e:
|
| 393 |
+
print("RuntimeError in scaler.step():", e)
|
| 394 |
+
print(torch.cuda.memory_summary())
|
| 395 |
+
# Fallback without scaler
|
| 396 |
+
try:
|
| 397 |
+
scaler.unscale_(optimizer)
|
| 398 |
+
optimizer.step()
|
| 399 |
+
except Exception as e2:
|
| 400 |
+
print("Fallback optimizer.step() failed:", e2)
|
| 401 |
+
raise e
|
| 402 |
+
else:
|
| 403 |
+
loss.backward()
|
| 404 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), GRAD_CLIP)
|
| 405 |
+
optimizer.step()
|
| 406 |
+
|
| 407 |
+
if device.type == 'cuda':
|
| 408 |
+
torch.cuda.empty_cache()
|
| 409 |
+
|
| 410 |
+
loss_val = float(loss.item())
|
| 411 |
+
epoch_loss += loss_val
|
| 412 |
+
global_step += 1
|
| 413 |
+
pbar.set_postfix({"loss": f"{loss_val:.4f}", "ppl": f"{math.exp(min(loss_val, 10)):.2f}", "step": global_step})
|
| 414 |
+
|
| 415 |
+
avg_train_loss = epoch_loss / max(1, len(train_dataset) // BATCH_SIZE)
|
| 416 |
+
print(f"[TRAIN] Avg loss: {avg_train_loss:.4f} | Perplexity: {math.exp(avg_train_loss):.2f}")
|
| 417 |
+
|
| 418 |
+
print("Running validation...")
|
| 419 |
+
val_loss = evaluate(model, val_loader, criterion)
|
| 420 |
+
print(f"[VAL] Avg loss: {val_loss:.4f} | Perplexity: {math.exp(val_loss):.2f}")
|
| 421 |
+
|
| 422 |
+
# Save checkpoint for this epoch
|
| 423 |
+
epoch_dir = OUTPUT_DIR / f"epoch{epoch}"
|
| 424 |
+
epoch_dir.mkdir(parents=True, exist_ok=True)
|
| 425 |
+
try:
|
| 426 |
+
if is_python_module:
|
| 427 |
+
model.eval()
|
| 428 |
+
dummy = torch.randint(0, 50257, (1, min(32, TRAIN_SEQ_LEN)), device=device)
|
| 429 |
+
try:
|
| 430 |
+
traced = torch.jit.trace(model, dummy, strict=False)
|
| 431 |
+
torch.jit.save(traced, epoch_dir / MODEL_SAVE_NAME)
|
| 432 |
+
print(f"Exported traced JIT β {epoch_dir / MODEL_SAVE_NAME}")
|
| 433 |
+
except Exception as e:
|
| 434 |
+
torch.save(model.state_dict(), epoch_dir / "state_dict.pt")
|
| 435 |
+
print(f"Saved state_dict (trace failed): {e}")
|
| 436 |
+
model.train()
|
| 437 |
+
else:
|
| 438 |
+
torch.jit.save(model, epoch_dir / MODEL_SAVE_NAME)
|
| 439 |
+
print(f"Saved ScriptModule β {epoch_dir / MODEL_SAVE_NAME}")
|
| 440 |
+
except Exception as e:
|
| 441 |
+
print("Error while saving epoch model:", e)
|
| 442 |
+
|
| 443 |
+
cleanup_old_epochs()
|
| 444 |
+
|
| 445 |
+
# ========================= Final model save =========================
|
| 446 |
+
final_dir = OUTPUT_DIR / "final"
|
| 447 |
+
final_dir.mkdir(parents=True, exist_ok=True)
|
| 448 |
+
try:
|
| 449 |
+
if is_python_module:
|
| 450 |
+
model.eval()
|
| 451 |
+
dummy = torch.randint(0, 50257, (1, min(32, TRAIN_SEQ_LEN)), device=device)
|
| 452 |
+
traced = torch.jit.trace(model, dummy, strict=False)
|
| 453 |
+
torch.jit.save(traced, final_dir / MODEL_SAVE_NAME)
|
| 454 |
+
print(f"Final traced JIT saved β {final_dir / MODEL_SAVE_NAME}")
|
| 455 |
+
else:
|
| 456 |
+
torch.jit.save(model, final_dir / MODEL_SAVE_NAME)
|
| 457 |
+
print(f"Final ScriptModule saved β {final_dir / MODEL_SAVE_NAME}")
|
| 458 |
+
except Exception:
|
| 459 |
+
torch.save(model.state_dict(), final_dir / "state_dict.pt")
|
| 460 |
+
print("Final model saved as state_dict (trace failed).")
|
| 461 |
+
|
| 462 |
+
# Save tokenizer with the final model
|
| 463 |
+
try:
|
| 464 |
+
train_dataset.tokenizer.save_pretrained(final_dir)
|
| 465 |
+
except Exception:
|
| 466 |
+
pass
|
| 467 |
+
|
| 468 |
+
# Backup previous last-trained model and update the "current" symlink/file
|
| 469 |
+
if LAST_TRAINED_PATH.exists():
|
| 470 |
+
backup_path = BACKUP_DIR / f"gpt_last_trained_backup_{int(LAST_TRAINED_PATH.stat().st_mtime)}.script.pt"
|
| 471 |
+
shutil.copy(LAST_TRAINED_PATH, backup_path)
|
| 472 |
+
print(f"Backed up previous last_trained β {backup_path}")
|
| 473 |
+
|
| 474 |
+
if (final_dir / MODEL_SAVE_NAME).exists():
|
| 475 |
+
shutil.copy(final_dir / MODEL_SAVE_NAME, LAST_TRAINED_PATH)
|
| 476 |
+
print(f"Copied final model β {LAST_TRAINED_PATH}")
|
| 477 |
+
elif (final_dir / "state_dict.pt").exists():
|
| 478 |
+
shutil.copy(final_dir / "state_dict.pt", LAST_TRAINED_PATH.with_suffix(".state_dict.pt"))
|
| 479 |
+
|
| 480 |
+
print("TRAINING COMPLETED.")
|
| 481 |
+
|
| 482 |
+
# ========================= Entrypoint =========================
|
| 483 |
+
if __name__ == "__main__":
|
| 484 |
+
if not RAW_PATH.exists():
|
| 485 |
+
print(f"ERROR: dataset {RAW_PATH} not found. Place your training text there.")
|
| 486 |
+
sys.exit(1)
|
| 487 |
train()
|