ViuAI commited on
Commit
fb73e47
·
verified ·
1 Parent(s): 7c25c00

Upload 2 files

Browse files
Files changed (1) hide show
  1. code/train.py +35 -32
code/train.py CHANGED
@@ -46,41 +46,44 @@ def get_hf_token():
46
  raise ValueError("HF_TOKEN not found in environment or kaggle_secrets.")
47
 
48
  def setup_ddp():
49
- if "RANK" in os.environ and "WORLD_SIZE" in os.environ:
50
- dist.init_process_group("nccl")
51
- rank = int(os.environ["RANK"])
52
- local_rank = int(os.environ["LOCAL_RANK"])
53
- world_size = int(os.environ["WORLD_SIZE"])
54
- is_ddp = True
55
- else:
56
- rank = 0
57
- local_rank = 0
58
- world_size = 1
59
- is_ddp = False
60
  device = torch.device(f"cuda:{local_rank}")
61
  torch.cuda.set_device(device)
62
- return rank, local_rank, world_size, device, is_ddp
63
 
64
- def load_tokenizer_robust(token: str):
65
- logger.info("Loading tokenizer...")
66
- try:
67
- return AutoTokenizer.from_pretrained("ViuAI/ViuRec", token=token, use_fast=True)
68
- except Exception as e:
69
- logger.warning(f"Failed to load fast tokenizer: {e}. Trying use_fast=False.")
 
 
 
 
 
 
 
 
 
 
 
 
70
  try:
71
- return AutoTokenizer.from_pretrained("ViuAI/ViuRec", token=token, use_fast=False)
72
- except Exception as e2:
73
- logger.error(f"Failed to load tokenizer: {e2}")
74
- raise
75
-
76
- def load_model_code(token: str):
77
- if not Path("model.py").exists():
78
- logger.info("model.py not found locally. Downloading from HuggingFace...")
79
  try:
80
- hf_hub_download(repo_id="ViuAI/ViuRec", filename="code/model.py", token=token, local_dir=".")
81
  except Exception as e:
82
- logger.error(f"Failed to download model.py: {e}")
83
- raise
 
 
 
84
 
85
  def load_checkpoint(model, optimizer, scaler, api, token, repo_id, filename="checkpoints/latest_chk.pt", strict=False):
86
  local_path = "latest_chk.pt"
@@ -187,6 +190,7 @@ def main():
187
  parser.add_argument("--lr", type=float, default=3e-4)
188
  parser.add_argument("--weight-decay", type=float, default=0.1)
189
  parser.add_argument("--ctx-len", type=int, default=2048)
 
190
  args = parser.parse_args()
191
 
192
  token = get_hf_token()
@@ -200,9 +204,8 @@ def main():
200
  rng = np.random.default_rng(seed)
201
 
202
  # Load resources
203
- tokenizer = load_tokenizer_robust(token)
204
- vocab_size = len(tokenizer)
205
- load_model_code(token)
206
 
207
  from model import ViuResonance100M, ModelConfig
208
  config = ModelConfig(vocab_size=vocab_size)
 
46
  raise ValueError("HF_TOKEN not found in environment or kaggle_secrets.")
47
 
48
  def setup_ddp():
49
+ if "RANK" not in os.environ or "WORLD_SIZE" not in os.environ:
50
+ return 0, 0, 1, torch.device("cuda" if torch.cuda.is_available() else "cpu"), False
51
+ dist.init_process_group("nccl")
52
+ local_rank = int(os.environ["LOCAL_RANK"])
 
 
 
 
 
 
 
53
  device = torch.device(f"cuda:{local_rank}")
54
  torch.cuda.set_device(device)
55
+ return int(os.environ["RANK"]), local_rank, int(os.environ["WORLD_SIZE"]), device, True
56
 
57
+ def load_tokenizer_robust(hf_token: str, model_repo: str, subfolder: str, is_main: bool):
58
+ if is_main: logger.info("Loading tokenizer...")
59
+ local_candidates = [
60
+ "/kaggle/working/ViuRec/tokenizer",
61
+ "/kaggle/input/viuai-500m-tokenizer",
62
+ "./tokenizer",
63
+ "./viuai-500m-tokenizer"
64
+ ]
65
+
66
+ for fast in [True, False]:
67
+ for p_str in local_candidates:
68
+ p = Path(p_str)
69
+ if (p / "tokenizer.json").exists() or (p / "vocab.json").exists():
70
+ try:
71
+ return AutoTokenizer.from_pretrained(str(p), local_files_only=True, use_fast=fast, trust_remote_code=True)
72
+ except Exception as e:
73
+ if "sentencepiece" in str(e).lower() or "tiktoken" in str(e).lower():
74
+ continue
75
  try:
76
+ return AutoTokenizer.from_pretrained(model_repo, subfolder=subfolder, token=hf_token, use_fast=fast, trust_remote_code=True)
77
+ except Exception as e:
78
+ pass
 
 
 
 
 
79
  try:
80
+ return AutoTokenizer.from_pretrained(model_repo, token=hf_token, use_fast=fast, trust_remote_code=True)
81
  except Exception as e:
82
+ pass
83
+
84
+ if is_main:
85
+ logger.warning("Tokenizer failed, using dummy vocab 64000")
86
+ return None
87
 
88
  def load_checkpoint(model, optimizer, scaler, api, token, repo_id, filename="checkpoints/latest_chk.pt", strict=False):
89
  local_path = "latest_chk.pt"
 
190
  parser.add_argument("--lr", type=float, default=3e-4)
191
  parser.add_argument("--weight-decay", type=float, default=0.1)
192
  parser.add_argument("--ctx-len", type=int, default=2048)
193
+ parser.add_argument("--vocab-size", type=int, default=None)
194
  args = parser.parse_args()
195
 
196
  token = get_hf_token()
 
204
  rng = np.random.default_rng(seed)
205
 
206
  # Load resources
207
+ tokenizer = load_tokenizer_robust(token, "ViuAI/ViuRec", "tokenizer", is_main)
208
+ vocab_size = args.vocab_size or (len(tokenizer) if tokenizer is not None else 64000)
 
209
 
210
  from model import ViuResonance100M, ModelConfig
211
  config = ModelConfig(vocab_size=vocab_size)