Robotics
multilingual
ternary
multimodal
pretraining
jirack
ternarytransformer
kgrabko commited on
Commit
b7ef5ce
·
verified ·
1 Parent(s): b7d2ac9

Update train_jirack_accelerate.py

Browse files
Files changed (1) hide show
  1. train_jirack_accelerate.py +47 -27
train_jirack_accelerate.py CHANGED
@@ -1,3 +1,5 @@
 
 
1
  # =============================================================================
2
  # COPYRIGHT © 2025-2026 Konstantin Vladimirovich Grabko. ALL RIGHTS RESERVED.
3
  # CMS Manhattan JiRack Technology — PATENT PENDING
@@ -10,11 +12,11 @@
10
  # Unauthorized commercial use is strictly prohibited.
11
  # Contact: grabko@cmsmanhattan.com
12
  # =============================================================================
13
-
14
  import os
15
  # Включаем оптимизацию памяти для ROCm/HIP ДО импорта torch!
16
  os.environ["PYTORCH_HIP_ALLOC_CONF"] = "expandable_segments:True"
17
 
 
18
  import glob
19
  import math
20
  import torch
@@ -36,6 +38,14 @@ class SingleShardDataset(Dataset):
36
  def __getitem__(self, idx):
37
  return self.data[idx].long()
38
 
 
 
 
 
 
 
 
 
39
  # --- 2. Main Training Function ---
40
  def train():
41
  grad_accumulation_steps = 24
@@ -47,9 +57,12 @@ def train():
47
  gradient_accumulation_steps=grad_accumulation_steps
48
  )
49
 
50
- pt_chunks_mask = "pretraindata/jirack_pretrain_chunk_*.pt"
51
- checkpoint_dir = "checkpoints"
52
- pt_files = sorted(glob.glob(pt_chunks_mask))
 
 
 
53
 
54
  if not pt_files:
55
  raise FileNotFoundError(f"No chunk files found matching the mask: {pt_chunks_mask}")
@@ -64,13 +77,29 @@ def train():
64
  config = TernaryConfig()
65
  model = TernaryTransformer3B(config)
66
 
67
- # === PINPOINT CHECKPOINT LOADING ===
68
- checkpoint_load_path = "model_weights.pt"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  if os.path.exists(checkpoint_load_path):
70
  if accelerator.is_local_main_process:
71
  print(f"-> Loading saved weights from: {checkpoint_load_path}")
72
  state_dict = torch.load(checkpoint_load_path, map_location="cpu", weights_only=True)
73
  model.load_state_dict(state_dict)
 
 
74
  else:
75
  if accelerator.is_local_main_process:
76
  print(f"-> Checkpoint not found at {checkpoint_load_path}, training will start from scratch.")
@@ -81,14 +110,12 @@ def train():
81
  print("-> Gradient Checkpointing enabled.")
82
 
83
  criterion = nn.CrossEntropyLoss()
84
-
85
- # Переносим модель на устройство через accelerator
86
  model = accelerator.prepare(model)
87
 
88
  # === ADAFACTOR CONFIGURATION FOR GPU ===
89
  optimizer = Adafactor(
90
  model.parameters(),
91
- lr=2e-4, # Peak LR
92
  weight_decay=0.01,
93
  relative_step=False,
94
  scale_parameter=False,
@@ -98,7 +125,6 @@ def train():
98
  # === CALCULATING AND INITIALIZING SCHEDULER WITH WARMUP ===
99
  scheduler = None
100
  if USE_COSINE_SCHEDULER:
101
- # Примерный расчет для сквозного или локального графика
102
  steps_per_shard = math.ceil(2000 / (batch_size * grad_accumulation_steps))
103
  total_steps = len(pt_files) * steps_per_shard
104
  num_warmup_steps = int(0.05 * total_steps)
@@ -110,25 +136,24 @@ def train():
110
  )
111
 
112
  if accelerator.is_local_main_process:
113
- print(f"-> Scheduler ACTIVATED.")
114
- print(f" Total training steps: {total_steps}")
115
- print(f" Warmup steps: {num_warmup_steps}")
116
 
117
- # Подготавливаем оптимизатор и планировщик
118
  if scheduler is not None:
119
  optimizer, scheduler = accelerator.prepare(optimizer, scheduler)
120
  else:
121
  optimizer = accelerator.prepare(optimizer)
122
 
123
  model.train()
124
- shard_counter = 0
125
-
126
  if accelerator.is_local_main_process:
127
  print("Starting training...")
128
  os.makedirs(checkpoint_dir, exist_ok=True)
129
 
130
  # === ОСНОВНОЙ ЦИКЛ ПО ШАРДАМ ===
131
- for shard_path in pt_files:
 
 
 
 
132
  shard_name = os.path.basename(shard_path)
133
  if accelerator.is_local_main_process:
134
  print(f"\n[Shard {shard_counter + 1}/{len(pt_files)}] {shard_name}")
@@ -138,16 +163,14 @@ def train():
138
  train_loader = DataLoader(
139
  shard_dataset,
140
  batch_size=batch_size,
141
- shuffle=True,
142
- num_workers=2,
143
- pin_memory=True
144
  )
145
 
146
  train_loader = accelerator.prepare(train_loader)
147
 
148
  progress_bar = tqdm(
149
  train_loader,
150
- desc=f"Processing {shard_name}",
151
  disable=not accelerator.is_local_main_process
152
  )
153
 
@@ -162,7 +185,6 @@ def train():
162
  loss = criterion(logits.reshape(-1, logits.size(-1)), targets.reshape(-1))
163
 
164
  accelerator.backward(loss)
165
-
166
  optimizer.step()
167
 
168
  if scheduler is not None and accelerator.sync_gradients:
@@ -184,14 +206,12 @@ def train():
184
  "lr": f"{current_lr:.2e}"
185
  })
186
 
187
- shard_counter += 1
188
-
189
- # Сохранение весов прямо в общую папку с указанием номера шарда в имени файла
190
  if accelerator.is_local_main_process:
191
- shard_checkpoint_path = os.path.join(checkpoint_dir, f"model_weights_shard_{shard_counter}.pt")
192
  unwrapped_model = accelerator.unwrap_model(model)
193
  torch.save(unwrapped_model.state_dict(), shard_checkpoint_path)
194
- print(f"✅ Saved after shard {shard_counter}: {shard_checkpoint_path}")
195
 
196
  # Финальное сохранение
197
  accelerator.wait_for_everyone()
 
1
+ #%%writefile train_jirack_accelerate_v3.py
2
+
3
  # =============================================================================
4
  # COPYRIGHT © 2025-2026 Konstantin Vladimirovich Grabko. ALL RIGHTS RESERVED.
5
  # CMS Manhattan JiRack Technology — PATENT PENDING
 
12
  # Unauthorized commercial use is strictly prohibited.
13
  # Contact: grabko@cmsmanhattan.com
14
  # =============================================================================
 
15
  import os
16
  # Включаем оптимизацию памяти для ROCm/HIP ДО импорта torch!
17
  os.environ["PYTORCH_HIP_ALLOC_CONF"] = "expandable_segments:True"
18
 
19
+ import re
20
  import glob
21
  import math
22
  import torch
 
38
  def __getitem__(self, idx):
39
  return self.data[idx].long()
40
 
41
+ # --- Helpers for Natural Sorting ---
42
+ def natural_sort_key(s):
43
+ return [int(text) if text.isdigit() else text.lower() for text in re.split(r'(\d+)', s)]
44
+
45
+ def extract_shard_number(filename):
46
+ match = re.search(r'model_weights_shard_(\d+)\.pt', filename)
47
+ return int(match.group(1)) if match else 0
48
+
49
  # --- 2. Main Training Function ---
50
  def train():
51
  grad_accumulation_steps = 24
 
57
  gradient_accumulation_steps=grad_accumulation_steps
58
  )
59
 
60
+ # Определяем абсолютные пути относительно расположения самого скрипта
61
+ script_dir = os.path.dirname(os.path.abspath(__file__))
62
+ pt_chunks_mask = os.path.join(script_dir, "pretraindata/jirack_pretrain_chunk_*.pt")
63
+ checkpoint_dir = os.path.join(script_dir, "checkpoints")
64
+
65
+ pt_files = sorted(glob.glob(pt_chunks_mask), key=natural_sort_key)
66
 
67
  if not pt_files:
68
  raise FileNotFoundError(f"No chunk files found matching the mask: {pt_chunks_mask}")
 
77
  config = TernaryConfig()
78
  model = TernaryTransformer3B(config)
79
 
80
+ # === DYNAMIC CHECKPOINT DISCOVERY (ABSOLUTE PATHS) ===
81
+ checkpoint_load_path = os.path.join(script_dir, "model_weights.pt")
82
+ start_shard_idx = 0
83
+
84
+ # Сканируем папку checkpoints по абсолютному пути
85
+ shard_checkpoints = glob.glob(os.path.join(checkpoint_dir, "model_weights_shard_*.pt"))
86
+
87
+ if shard_checkpoints:
88
+ shard_checkpoints = sorted(shard_checkpoints, key=natural_sort_key)
89
+ latest_shard_checkpoint = shard_checkpoints[-1]
90
+ completed_shards = extract_shard_number(latest_shard_checkpoint)
91
+
92
+ checkpoint_load_path = latest_shard_checkpoint
93
+ start_shard_idx = completed_shards # Если закончили шард 2, индекс следующего равен 2 (3-й шард)
94
+
95
+ # Загружаем найденные веса
96
  if os.path.exists(checkpoint_load_path):
97
  if accelerator.is_local_main_process:
98
  print(f"-> Loading saved weights from: {checkpoint_load_path}")
99
  state_dict = torch.load(checkpoint_load_path, map_location="cpu", weights_only=True)
100
  model.load_state_dict(state_dict)
101
+ if accelerator.is_local_main_process and start_shard_idx > 0:
102
+ print(f"-> Resuming training from Shard {start_shard_idx + 1} (Skipping first {start_shard_idx} shards)")
103
  else:
104
  if accelerator.is_local_main_process:
105
  print(f"-> Checkpoint not found at {checkpoint_load_path}, training will start from scratch.")
 
110
  print("-> Gradient Checkpointing enabled.")
111
 
112
  criterion = nn.CrossEntropyLoss()
 
 
113
  model = accelerator.prepare(model)
114
 
115
  # === ADAFACTOR CONFIGURATION FOR GPU ===
116
  optimizer = Adafactor(
117
  model.parameters(),
118
+ lr=2e-4,
119
  weight_decay=0.01,
120
  relative_step=False,
121
  scale_parameter=False,
 
125
  # === CALCULATING AND INITIALIZING SCHEDULER WITH WARMUP ===
126
  scheduler = None
127
  if USE_COSINE_SCHEDULER:
 
128
  steps_per_shard = math.ceil(2000 / (batch_size * grad_accumulation_steps))
129
  total_steps = len(pt_files) * steps_per_shard
130
  num_warmup_steps = int(0.05 * total_steps)
 
136
  )
137
 
138
  if accelerator.is_local_main_process:
139
+ print(f"-> Scheduler ACTIVATED. Total steps: {total_steps}")
 
 
140
 
 
141
  if scheduler is not None:
142
  optimizer, scheduler = accelerator.prepare(optimizer, scheduler)
143
  else:
144
  optimizer = accelerator.prepare(optimizer)
145
 
146
  model.train()
 
 
147
  if accelerator.is_local_main_process:
148
  print("Starting training...")
149
  os.makedirs(checkpoint_dir, exist_ok=True)
150
 
151
  # === ОСНОВНОЙ ЦИКЛ ПО ШАРДАМ ===
152
+ for shard_counter, shard_path in enumerate(pt_files):
153
+ # Пропускаем уже обработанные шарды
154
+ if shard_counter < start_shard_idx:
155
+ continue
156
+
157
  shard_name = os.path.basename(shard_path)
158
  if accelerator.is_local_main_process:
159
  print(f"\n[Shard {shard_counter + 1}/{len(pt_files)}] {shard_name}")
 
163
  train_loader = DataLoader(
164
  shard_dataset,
165
  batch_size=batch_size,
166
+ shuffle=True
 
 
167
  )
168
 
169
  train_loader = accelerator.prepare(train_loader)
170
 
171
  progress_bar = tqdm(
172
  train_loader,
173
+ desc=f"Training {shard_name}",
174
  disable=not accelerator.is_local_main_process
175
  )
176
 
 
185
  loss = criterion(logits.reshape(-1, logits.size(-1)), targets.reshape(-1))
186
 
187
  accelerator.backward(loss)
 
188
  optimizer.step()
189
 
190
  if scheduler is not None and accelerator.sync_gradients:
 
206
  "lr": f"{current_lr:.2e}"
207
  })
208
 
209
+ # Сохраняем веса с абсолютным путем
 
 
210
  if accelerator.is_local_main_process:
211
+ shard_checkpoint_path = os.path.join(checkpoint_dir, f"model_weights_shard_{shard_counter + 1}.pt")
212
  unwrapped_model = accelerator.unwrap_model(model)
213
  torch.save(unwrapped_model.state_dict(), shard_checkpoint_path)
214
+ print(f"✅ Saved after shard {shard_counter + 1}: {shard_checkpoint_path}")
215
 
216
  # Финальное сохранение
217
  accelerator.wait_for_everyone()