coderofpears commited on
Commit
e1640f8
·
verified ·
1 Parent(s): 020a3e3

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. train.py +24 -8
train.py CHANGED
@@ -86,6 +86,18 @@ def train(args):
86
  os.makedirs(ckpt_dir, exist_ok=True)
87
  cfg = build_cfg(args)
88
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  tok = YKTokenizer.load(os.path.join(data_dir, "tokenizer.json"))
90
  arr, seq_len, vocab, n_tokens = load_data(data_dir)
91
  cfg["vocab_size"] = vocab
@@ -93,7 +105,7 @@ def train(args):
93
  print(f"[train] data n_tokens={n_tokens:,} seq_len={seq_len} vocab={vocab}")
94
  print(f"[train] model params = {sum(p.numel() for p in YKDiff(cfg).parameters())/1e6:.1f}M")
95
 
96
- model = YKDiff(cfg).cuda()
97
  n_params = sum(p.numel() for p in model.parameters())
98
  print(f"[train] allocated params = {n_params/1e6:.1f}M")
99
 
@@ -108,13 +120,13 @@ def train(args):
108
  ckpts = sorted([f for f in os.listdir(ckpt_dir) if f.endswith(".pt")])
109
  if ckpts and not args.fresh:
110
  path = os.path.join(ckpt_dir, ckpts[-1])
111
- sd = torch.load(path, map_location="cuda")
112
  model.load_state_dict(sd["model"]); optim.load_state_dict(sd["optim"])
113
  step0 = sd["step"]
114
  print(f"[train] resumed from {path} step={step0}")
115
 
116
  model.train()
117
- amp = torch.cuda.amp.autocast(dtype=torch.bfloat16)
118
  t0 = time.time()
119
  limit = args.hours * 3600.0
120
  step = step0
@@ -127,20 +139,20 @@ def train(args):
127
 
128
  optim.zero_grad(set_to_none=True)
129
  mode_ar = (torch.rand(1).item() < 0.5)
130
- idx = sample_batch(arr, seq_len, args.batch).cuda()
131
 
132
  with amp:
133
  if mode_ar:
134
- m = torch.zeros(args.batch, dtype=torch.long, device="cuda")
135
  logits = model(idx, m, t=None) # causal
136
  loss = F.cross_entropy(
137
  logits[:, :-1].reshape(-1, V),
138
  idx[:, 1:].reshape(-1), ignore_index=pad_id)
139
  mname = "AR"
140
  else:
141
- m = torch.ones(args.batch, dtype=torch.long, device="cuda")
142
- r = torch.rand(args.batch, device="cuda") # per-sample ratio
143
- is_mask = torch.rand(args.batch, seq_len, device="cuda") < r[:, None]
144
  not_pad = idx != pad_id
145
  masked = idx.clone(); masked[is_mask] = mask_id
146
  logits = model(masked, m, t=r)
@@ -154,6 +166,8 @@ def train(args):
154
  loss.backward()
155
  nn.utils.clip_grad_norm_(model.parameters(), 1.0)
156
  optim.step()
 
 
157
 
158
  running = running * 0.9 + float(loss.item()) * 0.1
159
  step += 1
@@ -186,6 +200,8 @@ if __name__ == "__main__":
186
  ap.add_argument("--log-every", type=int, default=25)
187
  ap.add_argument("--ckpt-every", type=int, default=500)
188
  ap.add_argument("--fresh", action="store_true")
 
 
189
  ap.add_argument("--data-dir", default=None)
190
  ap.add_argument("--ckpt-dir", default=None)
191
  ap.add_argument("--hf-repo", default=None,
 
86
  os.makedirs(ckpt_dir, exist_ok=True)
87
  cfg = build_cfg(args)
88
 
89
+ # ---- device resolution (cuda / xla / cpu) ----
90
+ if getattr(args, "device", "cuda") == "xla":
91
+ import torch_xla.core.xla_model as xm
92
+ device = xm.xla_device()
93
+ print(f"[train] device = TPU:XLA ({device})")
94
+ elif getattr(args, "device", "cuda") == "cpu":
95
+ device = torch.device("cpu")
96
+ print("[train] device = CPU")
97
+ else:
98
+ device = torch.device("cuda")
99
+ print(f"[train] device = {device}")
100
+
101
  tok = YKTokenizer.load(os.path.join(data_dir, "tokenizer.json"))
102
  arr, seq_len, vocab, n_tokens = load_data(data_dir)
103
  cfg["vocab_size"] = vocab
 
105
  print(f"[train] data n_tokens={n_tokens:,} seq_len={seq_len} vocab={vocab}")
106
  print(f"[train] model params = {sum(p.numel() for p in YKDiff(cfg).parameters())/1e6:.1f}M")
107
 
108
+ model = YKDiff(cfg).to(device)
109
  n_params = sum(p.numel() for p in model.parameters())
110
  print(f"[train] allocated params = {n_params/1e6:.1f}M")
111
 
 
120
  ckpts = sorted([f for f in os.listdir(ckpt_dir) if f.endswith(".pt")])
121
  if ckpts and not args.fresh:
122
  path = os.path.join(ckpt_dir, ckpts[-1])
123
+ sd = torch.load(path, map_location=device)
124
  model.load_state_dict(sd["model"]); optim.load_state_dict(sd["optim"])
125
  step0 = sd["step"]
126
  print(f"[train] resumed from {path} step={step0}")
127
 
128
  model.train()
129
+ amp = torch.amp.autocast(device_type=device.type, dtype=torch.bfloat16)
130
  t0 = time.time()
131
  limit = args.hours * 3600.0
132
  step = step0
 
139
 
140
  optim.zero_grad(set_to_none=True)
141
  mode_ar = (torch.rand(1).item() < 0.5)
142
+ idx = sample_batch(arr, seq_len, args.batch).to(device)
143
 
144
  with amp:
145
  if mode_ar:
146
+ m = torch.zeros(args.batch, dtype=torch.long, device=device)
147
  logits = model(idx, m, t=None) # causal
148
  loss = F.cross_entropy(
149
  logits[:, :-1].reshape(-1, V),
150
  idx[:, 1:].reshape(-1), ignore_index=pad_id)
151
  mname = "AR"
152
  else:
153
+ m = torch.ones(args.batch, dtype=torch.long, device=device)
154
+ r = torch.rand(args.batch, device=device) # per-sample ratio
155
+ is_mask = torch.rand(args.batch, seq_len, device=device) < r[:, None]
156
  not_pad = idx != pad_id
157
  masked = idx.clone(); masked[is_mask] = mask_id
158
  logits = model(masked, m, t=r)
 
166
  loss.backward()
167
  nn.utils.clip_grad_norm_(model.parameters(), 1.0)
168
  optim.step()
169
+ if device.type == "xla":
170
+ xm.mark_step()
171
 
172
  running = running * 0.9 + float(loss.item()) * 0.1
173
  step += 1
 
200
  ap.add_argument("--log-every", type=int, default=25)
201
  ap.add_argument("--ckpt-every", type=int, default=500)
202
  ap.add_argument("--fresh", action="store_true")
203
+ ap.add_argument("--device", default="cuda", choices=["cuda", "xla", "cpu"],
204
+ help="training device (cuda default; xla for TPU; cpu for tests)")
205
  ap.add_argument("--data-dir", default=None)
206
  ap.add_argument("--ckpt-dir", default=None)
207
  ap.add_argument("--hf-repo", default=None,