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

Update train_jirack_accelerate.py

Browse files
Files changed (1) hide show
  1. train_jirack_accelerate.py +19 -26
train_jirack_accelerate.py CHANGED
@@ -12,7 +12,7 @@
12
  # =============================================================================
13
 
14
  import os
15
- # Enable memory optimization for ROCm/HIP BEFORE importing torch!
16
  os.environ["PYTORCH_HIP_ALLOC_CONF"] = "expandable_segments:True"
17
 
18
  import glob
@@ -25,7 +25,7 @@ from tqdm import tqdm
25
  from transformers import Adafactor, get_cosine_schedule_with_warmup
26
 
27
  # --- GLOBAL CONSTANTS ---
28
- USE_COSINE_SCHEDULER = True # Set to False if you want to disable the scheduler (warmup + cosine)
29
 
30
  # --- 1. Lightweight Dataset ---
31
  class SingleShardDataset(Dataset):
@@ -38,8 +38,8 @@ class SingleShardDataset(Dataset):
38
 
39
  # --- 2. Main Training Function ---
40
  def train():
41
- grad_accumulation_steps = 1
42
- batch_size = 1
43
 
44
  # Initialize Accelerator
45
  accelerator = Accelerator(
@@ -58,7 +58,7 @@ def train():
58
  print(f"Shards found: {len(pt_files)}")
59
  print("Initializing JiRack 3.3B...")
60
 
61
- # Strictly import your classes from the local file
62
  from JiRackNative_3b import TernaryTransformer3B, TernaryConfig
63
 
64
  config = TernaryConfig()
@@ -74,7 +74,6 @@ def train():
74
  else:
75
  if accelerator.is_local_main_process:
76
  print(f"-> Checkpoint not found at {checkpoint_load_path}, training will start from scratch.")
77
- # ==================================
78
 
79
  model.gradient_checkpointing_enable()
80
 
@@ -83,7 +82,7 @@ def train():
83
 
84
  criterion = nn.CrossEntropyLoss()
85
 
86
- # First, move the model to the ROCm/HIP device via accelerator
87
  model = accelerator.prepare(model)
88
 
89
  # === ADAFACTOR CONFIGURATION FOR GPU ===
@@ -99,15 +98,11 @@ def train():
99
  # === CALCULATING AND INITIALIZING SCHEDULER WITH WARMUP ===
100
  scheduler = None
101
  if USE_COSINE_SCHEDULER:
102
- # Calculate total number of actual weight updates (optimizer steps)
103
- # 2000 rows per shard / batch_size 1 / grad_accumulation_steps 4 = 500 steps per shard.
104
  steps_per_shard = math.ceil(2000 / (batch_size * grad_accumulation_steps))
105
  total_steps = len(pt_files) * steps_per_shard
106
-
107
- # Set warmup (e.g., 5% of total training steps)
108
  num_warmup_steps = int(0.05 * total_steps)
109
 
110
- # Combined scheduler: smoothly increases LR up to 2e-4, then decays following a cosine curve to 0
111
  scheduler = get_cosine_schedule_with_warmup(
112
  optimizer=optimizer,
113
  num_warmup_steps=num_warmup_steps,
@@ -119,7 +114,7 @@ def train():
119
  print(f" Total training steps: {total_steps}")
120
  print(f" Warmup steps: {num_warmup_steps}")
121
 
122
- # Prepare optimizer and scheduler via accelerator
123
  if scheduler is not None:
124
  optimizer, scheduler = accelerator.prepare(optimizer, scheduler)
125
  else:
@@ -130,7 +125,9 @@ def train():
130
 
131
  if accelerator.is_local_main_process:
132
  print("Starting training...")
 
133
 
 
134
  for shard_path in pt_files:
135
  shard_name = os.path.basename(shard_path)
136
  if accelerator.is_local_main_process:
@@ -168,7 +165,6 @@ def train():
168
 
169
  optimizer.step()
170
 
171
- # Step the scheduler only during an actual gradient sync update
172
  if scheduler is not None and accelerator.sync_gradients:
173
  if not getattr(accelerator, "optimizer_step_was_skipped", False):
174
  scheduler.step()
@@ -180,7 +176,6 @@ def train():
180
  ppl = math.exp(avg_loss) if avg_loss < 20 else float('inf')
181
 
182
  if accelerator.is_local_main_process:
183
- # Extract current LR to display on the tqdm panel
184
  current_lr = scheduler.get_last_lr()[0] if scheduler is not None else optimizer.param_groups[0]['lr']
185
  progress_bar.set_postfix({
186
  "loss": f"{loss.item():.4f}",
@@ -191,22 +186,20 @@ def train():
191
 
192
  shard_counter += 1
193
 
194
- # Save checkpoint after each shard
195
  if accelerator.is_local_main_process:
196
- current_checkpoint_path = os.path.join(checkpoint_dir, f"jirack_shard_{shard_counter}")
197
- os.makedirs(current_checkpoint_path, exist_ok=True)
198
  unwrapped_model = accelerator.unwrap_model(model)
199
- torch.save(unwrapped_model.state_dict(), os.path.join(current_checkpoint_path, "model_weights.pt"))
200
- print(f"✅ Saved after shard {shard_counter}")
201
 
202
- # Final saving step
203
  accelerator.wait_for_everyone()
204
  if accelerator.is_local_main_process:
205
- final_dir = os.path.join(checkpoint_dir, "jirack_final_3b")
206
- os.makedirs(final_dir, exist_ok=True)
207
  unwrapped_model = accelerator.unwrap_model(model)
208
- torch.save(unwrapped_model.state_dict(), os.path.join(final_dir, "model_final_weights.pt"))
209
- print("Final save completed.")
210
 
211
  if __name__ == "__main__":
212
- train()
 
12
  # =============================================================================
13
 
14
  import os
15
+ # Включаем оптимизацию памяти для ROCm/HIP ДО импорта torch!
16
  os.environ["PYTORCH_HIP_ALLOC_CONF"] = "expandable_segments:True"
17
 
18
  import glob
 
25
  from transformers import Adafactor, get_cosine_schedule_with_warmup
26
 
27
  # --- GLOBAL CONSTANTS ---
28
+ USE_COSINE_SCHEDULER = False # Set to False if you want to disable the scheduler (warmup + cosine)
29
 
30
  # --- 1. Lightweight Dataset ---
31
  class SingleShardDataset(Dataset):
 
38
 
39
  # --- 2. Main Training Function ---
40
  def train():
41
+ grad_accumulation_steps = 24
42
+ batch_size = 8
43
 
44
  # Initialize Accelerator
45
  accelerator = Accelerator(
 
58
  print(f"Shards found: {len(pt_files)}")
59
  print("Initializing JiRack 3.3B...")
60
 
61
+ # Импортируем строго ваши классы из локального файла
62
  from JiRackNative_3b import TernaryTransformer3B, TernaryConfig
63
 
64
  config = TernaryConfig()
 
74
  else:
75
  if accelerator.is_local_main_process:
76
  print(f"-> Checkpoint not found at {checkpoint_load_path}, training will start from scratch.")
 
77
 
78
  model.gradient_checkpointing_enable()
79
 
 
82
 
83
  criterion = nn.CrossEntropyLoss()
84
 
85
+ # Переносим модель на устройство через accelerator
86
  model = accelerator.prepare(model)
87
 
88
  # === ADAFACTOR CONFIGURATION FOR GPU ===
 
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)
105
 
 
106
  scheduler = get_cosine_schedule_with_warmup(
107
  optimizer=optimizer,
108
  num_warmup_steps=num_warmup_steps,
 
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:
 
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:
 
165
 
166
  optimizer.step()
167
 
 
168
  if scheduler is not None and accelerator.sync_gradients:
169
  if not getattr(accelerator, "optimizer_step_was_skipped", False):
170
  scheduler.step()
 
176
  ppl = math.exp(avg_loss) if avg_loss < 20 else float('inf')
177
 
178
  if accelerator.is_local_main_process:
 
179
  current_lr = scheduler.get_last_lr()[0] if scheduler is not None else optimizer.param_groups[0]['lr']
180
  progress_bar.set_postfix({
181
  "loss": f"{loss.item():.4f}",
 
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()
198
  if accelerator.is_local_main_process:
199
+ final_path = os.path.join(checkpoint_dir, "model_final_weights.pt")
 
200
  unwrapped_model = accelerator.unwrap_model(model)
201
+ torch.save(unwrapped_model.state_dict(), final_path)
202
+ print(f"Final save completed: {final_path}")
203
 
204
  if __name__ == "__main__":
205
+ train()